Get the filename from the File Path using X++ in AX 2012

Get the filename from the File Path using X++ in AX 2012

Description:-

AX has a standard method in the Global Class to split the file name from the entire file path.The method is fileNameSplit().The method takes file path as the parameter.It splits the file path into three different strings file path, file name, file extension respectively.The usage of the function can be seen below.

Create Job from AOT:-
  • In the AOT, click Job.
  • Right-click the Job node, and then select New Job.

static void Filename(Args _args)
{
    Filename filepath;
    Filename filename;
    Filename fileType;
    str fileNameString,fileNamePath;
    ;
    fileNamePath=@"C:\Users\umesh.adroja\Desktop\DocumentsFile.docx";
    [filepath, filename, fileType] = fileNameSplit(fileNamePath);
    fileNameString= filename + fileType;
    info(strFmt("filename=%1 \nfileType=%2",filename,fileType));
}

Now the fileNameString will return you the file name with extension.

Console Application Using Windows Scheduler in Asp.Net

Description:-

The Task Scheduler allows you to create all kinds of automated tasks in Windows. You can schedule a program to run at a specific time interval, a message to be displayed when something happens and so on. You can schedule just about anything with it. The only limit is your imagination.

You must be logged on as an administrator to perform these steps. If you aren't logged on as an administrator, you can only change settings that apply to your user account.

If you use a specific program on a regular basis, you can use the Task Scheduler wizard to create a task that opens the program for you automatically according to the schedule you choose. For example, if you use a financial program on a certain day each month, you can schedule a task that opens the program automatically to avoid the risk of forgetting to open it yourself.

1.       Open Task Scheduler by clicking the Start button, clicking Control Panel, clicking System and Security, clicking Administrative Tools, and then double-clicking Task Scheduler.‌ If you're prompted for an administrator password or confirmation, type the password or provide confirmation.
2.       Click the Action menu, and then click Create Basic Task.
3.       Type a name for the task and an optional description, and then click next.
4.       Do one of the following:
  • To select a schedule based on the calendar, click Daily, Weekly, Monthly, or one time, click next; specify the schedule you want to use, and then click next.
  • To select a schedule based on common recurring events, click when the computer starts or When I log on, and then click next.
  • To select a schedule based on specific events, click when a specific event is logged, click next; specify the event log and other information using the drop-down lists, and then click next.
  • To schedule a program to start automatically, click Start a program, and then click next.

5.       Click Browse to find the program you want to start, and then click next.
6.       Click Finish.

To schedule a task to run automatically when the computer starts

If you want a task to run when the computer starts, whether a user is logged on or not, follow these steps.

1.    Open Task Scheduler by clicking the Start button, clicking Control Panel, clicking System and Security, clicking Administrative Tools, and then double-clicking Task Scheduler.‌ If you're prompted for an administrator password or confirmation, type the password or provide confirmation.
2.       Click the Action menu, and then click Create Basic Task.
3.       Type a name for the task and an optional description, and then click next.
4.       Click when the computer starts, and then click next.
5.       To schedule a program to start automatically, click Start a program, and then click next.
6.       Click Browse to find the program you want to start, and then click next.
7.       Select the Open the Properties dialog for this task when I click Finish check box and click Finish.
8.       In the Properties dialog box, select Run whether user is logged on or not, and then click OK.

As in the preceding scenario we can have multiple solutions for that:

1.       Create a Windows Service, implement your logic and a set timer.
2.       Create a console application and implement your logic, then create a scheduler and refer action as console application .exe file.
3.      Any third-party scheduler like Quartz scheduler.

Here we will explain use of a console application with the Windows Scheduler.
First we need to create a console application in Visual Studio. Please see the following screenshot, I have created a console app with starter logic:

static void Main(string[] args)
{
  RunScheduler();
}
public static void RunScheduler()
{
  string path = Path.GetFullPath("D:\\MyTest") + "\\" + DateTime.Now.ToString("MM_dd_yyyy_HH_mm") + "_Log.txt";
  try
  {
    if (!File.Exists(path))
    {
      File.Create(path);
    }
  }
  catch (Exception ex)
  {
    string errorpath = @"D:\MyTest.txt";
    File.AppendAllText(errorpath, Environment.NewLine + ex.Message);
  }
}

After implementing our logic we need to build the application in release mode. Once it builds successfully, it creates one .exe file in your directory.

Now my application is ready for setting up in the Windows Scheduler.
Before you start the scheduler you should have Admin Rights in system.
To open Windows Scheduler go to the Start menu and in the search box type "Scheduler", then it will display the Task Scheduler. Click on that.

Now create your task Scheduler for Repeats every 1 minute.
After Check your Folder you can get every minute new text file in your folder.

How to Create File Tampering Check in Windows Form

How to Create File Tampering Check in Windows Form

Description:-

In this Article we will see FileTamperingCheck using windows form. Here we will also check for byte test to check file bytes or hash code using windows form.
Now Generate Source Browse button click event to open Dialog for Open File.

private void btnBrowseSrc_Click(System.Object sender, System.EventArgs e)
{
     OpenFileDialog1.Title = "Open File";
     OpenFileDialog1.Filter = "Files (*.*)|*.*";
                    
     if (OpenFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
     {
         return;
     }
                    
     string sFilePath = OpenFileDialog1.FileName;
                    
     if (System.IO.File.Exists(sFilePath) == false)
     {
        sFilePath = "";
        return;
     }
     else
     {
        txtSourceFile.Text = sFilePath;
     }                    
}

Same here to Generate Test browse button to open Test file.

private void btnBrowseTest_Click(System.Object sender, System.EventArgs e)
{
   OpenFileDialog1.Title = "Open File";
   OpenFileDialog1.Filter = "Files (*.*)|*.*";
                    
   if (OpenFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
   {
      return;
   }
                    
   string sFilePath = OpenFileDialog1.FileName;
                    
   if (System.IO.File.Exists(sFilePath) == false)
   {
      sFilePath = "";
      return;
   }
   else
   {
      txtTestFile.Text = sFilePath;
   }                
}

Now generate Hash Test button click event to Code for Check Length, Bytes, and HashCode to compare it to Other File.

private void btnTest_Click(System.Object sender, System.EventArgs e)
{
  HashAlgorithm myHash;
  myHash = HashAlgorithm.Create();
  if (txtTestFile.Text == string.Empty || this.txtSourceFile.Text == string.Empty)
  {
    MessageBox.Show("Set all form fields prior to initiating a test", "Missing Form Data", MessageBoxButtons.OK);
  }
  
  FileStream fs1 = new FileStream(txtTestFile.Text, FileMode.OpenOrCreate);
  byte[] fs1Bytes = new byte[fs1.Length + 1];
  fs1.Read(fs1Bytes, 0, (int)fs1.Length);
  byte[] arr1 = myHash.ComputeHash(fs1Bytes);
  fs1.Close();

  FileStream fs2 = new FileStream(txtSourceFile.Text, FileMode.OpenOrCreate);
  byte[] fs2Bytes = new byte[fs2.Length + 1];
  fs2.Read(fs2Bytes, 0, (int)fs2.Length);
  byte[] arr2 = myHash.ComputeHash(fs2Bytes);
  fs2.Close();
  if (BitConverter.ToString(arr1) == BitConverter.ToString(arr2))
  {
    MessageBox.Show("The file examined has not been tampered with.", "Hash Test Passed");
    //display comparison
    MessageBox.Show("Original Hash: " + Environment.NewLine + BitConverter.ToString(arr1) + Environment.NewLine + "Test Hash: " + Environment.NewLine + BitConverter.ToString(arr2), "Hash Test Results");
  }
  else
  {
    MessageBox.Show("The file examined has been tampered with.", "Hash Test Failed");
    //display comparison
    MessageBox.Show("Original Hash: " + Environment.NewLine + BitConverter.ToString(arr1) + Environment.NewLine + "Test Hash: " + Environment.NewLine + BitConverter.ToString(arr2), "Hash Test Results");
  }
}

Now Generate Byte Test button Click event to compare Bytes, Length of Both Files.

private void btnByteCompare_Click(System.Object sender, System.EventArgs e)
{
  FileStream fs1 = new FileStream(txtTestFile.Text, FileMode.OpenOrCreate);
  byte[] fs1Bytes = new byte[fs1.Length+ 1];
  fs1.Read(fs1Bytes, 0, (int) fs1.Length);
  fs1.Close();
                    
  FileStream fs2 = new FileStream(txtSourceFile.Text, FileMode.OpenOrCreate);
  byte[] fs2Bytes = new byte[fs2.Length+ 1];
  fs2.Read(fs2Bytes, 0, (int) fs2.Length);
  fs2.Close();
                    
  int i = 0;
  for (i = 0; i <= fs1Bytes.Length - 1; i++)
  {
    if (!System.Convert.ToBoolean(fs1Bytes[i] == fs2Bytes[i]))
    {
      MessageBox.Show("The file examined has been tampered with at position " + i.ToString(), "Byte Test Failed");
      return;
    }
  }
                    
  MessageBox.Show("The file examined has not been tampered with.", "Byte Test Passed");
}

Now you are done to Test Application run your windows application and Select both files and test it.

How to Encrypt and Decrypt Text using chaocipher in Console Application

Description:-

In this Article we will encrypt and Decrypt Text using cipher Encryption in Console Application. Here you can insert your Cipher Text for Encrypt and Decrypt your Text Data in Cipher text.

How does the cipher work?

For full details of how the cipher is applied, you should consult Mr Rubin's paper which, by cryptographic standards, is very easy to read and understand.
Briefly, the idea is that you start with two alphabets: a 'left' alphabet (for ciphertext) and a 'right' alphabet (for plaintext).

You then convert each letter in the plaintext to ciphertext by looking up the index of the former in the right alphabet and then using that index of read off the corresponding ciphertext letter from the left alphabet.

However, unlike a normal substitution cipher, you then make some permutations to both the left and right alphabets before encrypting the next letter. Similar operations are carried out after encrypting each letter until the plaintext is exhausted.

Decryption follows a similar pattern except that the permutations used are slightly different from those used in encryption.

This is a clever idea which is known as an 'autokey' cipher in cryptography because the next key is generated from the previous one. Clearly, the permutations used need to be such that they can be easily reversed by the decryption process.

C# Implementation

Although a C# implementation is said to exist, I could not find it on the internet and so have written my own.

The following console application is based on the algorithm described in Mr Rubin's paper and uses the example which he gives so we can check that it is working correctly. The resulting ciphertext is then decrypted back to the plaintext.

No attempt has been made to optimize the code though, for a large piece of plaintext, performance could almost certainly be improved by using unsafe code and pointers to manipulate the character arrays.

Step 1: Create Console Application and Code below to understand how it works.

        static void Main(string[] args)
        {
            string plainText = "UMESHPATELAHMEDABAD";
            Console.WriteLine("The original plainText is : {0}", plainText);
            Console.WriteLine("\nThe left and right alphabets after each permutation during encryption are\n");
            string cipherText = Chao.Encrypt(plainText);
            Console.WriteLine("\nThe ciphertext is {0}\n", cipherText);
            string plainText2 = Chao.Decrypt(cipherText);
            Console.WriteLine("\nThe recovered plaintext is {0}", plainText2);
            Console.ReadKey();
        }

        static class Chao
        {
            private static string lAlphabet = "HXUCZVAMDSLKPEFJRIGTWOBNYQ";
            private static string rAlphabet = "PTLNBQDEOYSFAVZKGJRIHWXUMC";

            public static string Encrypt(string plainText)
            {
                char[] left = lAlphabet.ToCharArray();
                char[] right = rAlphabet.ToCharArray();
                char[] pText = plainText.ToCharArray();
                char[] cText = new char[pText.Length];
                char[] temp = new char[26];
                int index;
                char store; 
                for (int i = 0; i < pText.Length; i++)
                {
                    Console.WriteLine("{0}  {1}", new string(left), new string(right)); 
                    index = Array.IndexOf(right, pText[i]);
                    cText[i] = left[index];
                    if (i == pText.Length - 1) break; 
                    // permute left 
                    for (int j = index; j < 26; j++) temp[j - index] = left[j];
                    for (int j = 0; j < index; j++) temp[26 - index + j] = left[j];
                    store = temp[1];
                    for (int j = 2; j < 14; j++) temp[j - 1] = temp[j];
                    temp[13] = store;
                    temp.CopyTo(left, 0); 
                    // permute right 
                    for (int j = index; j < 26; j++) temp[j - index] = right[j];
                    for (int j = 0; j < index; j++) temp[26 - index + j] = right[j];
                    store = temp[0];
                    for (int j = 1; j < 26; j++) temp[j - 1] = temp[j];
                    temp[25] = store;
                    store = temp[2];
                    for (int j = 3; j < 14; j++) temp[j - 1] = temp[j];
                    temp[13] = store;
                    temp.CopyTo(right, 0);
                } 
                return new string(cText);
            }

            public static string Decrypt(string cipherText)
            {
                char[] left = lAlphabet.ToCharArray();
                char[] right = rAlphabet.ToCharArray();
                char[] cText = cipherText.ToCharArray();
                char[] pText = new char[cText.Length];
                char[] temp = new char[26];
                int index;
                char store; 
                for (int i = 0; i < cText.Length; i++)
                {
                    Console.WriteLine("{0}  {1}", new string(left), new string(right)); 
                    index = Array.IndexOf(left, cText[i]);
                    pText[i] = right[index];
                    if (i == cText.Length - 1) break; 
                    // permute left 
                    for (int j = index; j < 26; j++) temp[j - index] = left[j];
                    for (int j = 0; j < index; j++) temp[26 - index + j] = left[j];
                    store = temp[1];
                    for (int j = 2; j < 14; j++) temp[j - 1] = temp[j];
                    temp[13] = store;
                    temp.CopyTo(left, 0); 
                    // permute right 
                    for (int j = index; j < 26; j++) temp[j - index] = right[j];
                    for (int j = 0; j < index; j++) temp[26 - index + j] = right[j];
                    store = temp[0];
                    for (int j = 1; j < 26; j++) temp[j - 1] = temp[j];
                    temp[25] = store;
                    store = temp[2];
                    for (int j = 3; j < 14; j++) temp[j - 1] = temp[j];
                    temp[13] = store;
                    temp.CopyTo(right, 0);
                } 
                return new string(pText);
            }
        }

My Output looks like below image.

The print out of the left and right alphabets after each permutation during the decryption process has been suppressed as the output would otherwise have exceeded the length of a maximized console window on my machine.

I am not sure how strong this cipher is by modern cryptographic standards but clearly, relative to the effort needed to implement it, it is very strong indeed!

Although the present implementation only covers upper-case letters, it would be easy to adapt it to deal with larger character sets and, for those interested in developing their own ciphers, it should make an excellent starting point.