Wednesday, August 10, 2011

C# / Windows Phone 7 - AES Encryption on WP7

You may already know that data-in-transit is secured via SSL. When calling a web service, however, the need may arise to encrypt and decrypt data. There are several cryptography algorithms on Windows Phone 7 that are supported, but we are providing a solid sample implementation using a 128-bit block size and 128-bit key size. AESManaged has a fixed block size of 128 bits and a key size of 128, 192, or 256 bits. Also, the Cipher Mode is defaulted to CBC, with a PKCS7 Padding.
class AES {
 
    public static byte[] Encrypt (byte[] data, byte[] key, byte[] iv) {
        if (data == null || data.Length <= 0)
             throw new ArgumentNullException("data");
        if (key == null || key.Length <= 0)
             throw new ArgumentNullException("key");
        if (iv == null || iv.Length <= 0)
             throw new ArgumentNullException("key");
 
        byte[] encrypted;
 
        using (AesManaged AESM = new AesManaged()) {
 
            // Defaults
            // CipherMode = CBC
            // Padding = PKCS7
 
            AESM.KeySize = 128;
            AESM.BlockSize = 128;
            AESM.Key = key;
            AESM.IV = iv;
 
            ICryptoTransform encryptor = AESM.CreateEncryptor();
            encrypted = encryptor.TransformFinalBlock(data, 0, data.Length);
 
        }
        return encrypted;
    }
 
    public static byte[] Decrypt (byte[] cipherText, byte[] key, byte[] iv) {
        if (cipherText == null || cipherText.Length <= 0)
             throw new ArgumentNullException("cipherText");
        if (key == null || key.Length <= 0)
             throw new ArgumentNullException("key");
        if (iv == null || iv.Length <= 0)
             throw new ArgumentNullException("key");
 
        byte[] decrypted;
 
        using (AesManaged AESM = new AesManaged()) {
 
            // Defaults
            // CipherMode = CBC
            // Padding = PKCS7
 
            AESM.KeySize = 128;
            AESM.BlockSize = 128;
            AESM.Key = key;
            AESM.IV = iv;
 
            ICryptoTransform decryptor = AESM.CreateDecryptor();
            decrypted = decryptor.TransformFinalBlock(cipherText, 0, cipherText.Length);
 
        }
        return decrypted;
    }
}
Click here to download the source code of an example application that demonstrates encryption and decryption using the above AES class.

Thursday, August 4, 2011

C# / Threading - Progressbar with Database Transactions

To some, threading can be slightly confusing. If you happen to want to do a transaction on the computer you are writing the application for that may take a while, whether it be a database, communication with some PLC, saving large files, and happen to want to include a Progressbar, this sample may help. I am not going to step much into handling stepping with Progressbars, but rather the threading. It was found that thread pools are easily the 'weapon of choice' when it comes to processing asynchronous I/O, post work items, etc. If you don't use threading, you may see that your application locks up for the length of time it takes to process these transactions. In terms of code, you do the following:
using (SqlConnection sqlConn = new SqlConnection(String.Format("Data Source = {0}; User Id = {1}; Password = {2}; Timeout = 0; Integrated Security = True;", cboDatasources.SelectedItem.ToString(), txtUserName.Text, txtPassword.Text)))
{
    // Open SQL Connection
    sqlConn.Open();
  
    ThreadPool.QueueUserWorkItem(delegate 
    {
        // Do some work here
    }
  
    // Close SQL Connection
    sqlConn.Close();
}
Once you have the groundwork for the threading, if you need to modify any content inside threads that were generated in the main threads, such as controls, you need to Invoke.
Invoke(new Action(delegate
{ 
     lblProgressUpdate.Text = "Something happening..."; 
     ProgressBarExample.Increment(15);
}));

Tuesday, August 2, 2011

SQL - Finding SQL Server Installation Path

If trying to automate creating databases you may need to get the installation path of the SQL Server instance you are connected to, to do this use the following query.
declare @rc int, @dir nvarchar(400) 
  
exec @rc = master.dbo.xp_instance_regread
      N'HKEY_LOCAL_MACHINE',
      N'Software\Microsoft\MSSQLServer\Setup',
      N'SQLPath', 
      @dir output, 'no_output'
select @dir AS InstallationDirectory