Monday, 9 April 2012

How to encrypt/decrypt Query string


Introduction
In our development routine many time we need to pass information from one page to another. Most popular way to do this is to pass Query String along with url. But as we all know, it’s not safe as it’s visible to user. Here is a solution.

Objective
Pass information through Query String after encode them

Using the Code
In this example I developed a class, that contains method for encrypting and decrypting Query string.
I’m using TripleDES algorithm which using MD5 generated hash as a sault. Code for same is given below.
// The Querystring to encrypt.
string Msg = Request.QueryString;
string Password = "Pa5sw0rd";

string EncryptedString = MySample.EncryptString(Msg, Password);

In the EncryptString function we apply the TripleDES algorithm with a 128 bit key. But first we need to turn the above passphrase (‘Pa5sw0rd’) into a 128 bit key. One useful coincidence is that the MD5 hash algorithm accepts a set of bytes of any length and turns them into a 128 bit hash. So by running the password through the MD5 hashing algorithm we create our key.

// Step 1. We hash the passphrase using MD5
// We use the MD5 hash generator as the result is a 128 bit byte array
// which is a valid length for the TripleDES encoder we use below

MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));

The TripleDES algorithm itself turns a byte array into an encrypted byte array. So we first need to convert our C# message string (which is Unicode encoded) into a byte array through the System.Text.UTF8Encoding encoder.

The key is used to initialize the TripleDES algorithm. In addition we need to specify that we will only encode something once (CipherMode.ECB) and because its unlikely that our source string fits into a single TripleDES block we need to specify how we want to pad any remaining bytes (PaddingMode.PKCS7).

// Step 2. Create a new TripleDESCryptoServiceProvider object
TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();

// Step 3. Setup the encoder
TDESAlgorithm.Key = TDESKey;
TDESAlgorithm.Mode = CipherMode.ECB;
TDESAlgorithm.Padding = PaddingMode.PKCS7;

The encrypted byte array is finally converted into a Base64 encoded string for easy storage. The DecryptString function is very similar to the encryption function, except that it turns the Base64 encoded encrypted message back into the original UTF8 string.

Complete code is given below.

using System;
using System.Text;
using System.Security.Cryptography;

namespace EncryptStringSample
{
    class MySample
    {

        public static string EncryptString(string Message, string Passphrase)
        {
            byte[] Results;
            System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();

            // Step 1. We hash the passphrase using MD5
            // We use the MD5 hash generator as the result is a 128 bit byte array
            // which is a valid length for the TripleDES encoder we use below

            MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
            byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));

            // Step 2. Create a new TripleDESCryptoServiceProvider object
            TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();

            // Step 3. Setup the encoder
            TDESAlgorithm.Key = TDESKey;
            TDESAlgorithm.Mode = CipherMode.ECB;
            TDESAlgorithm.Padding = PaddingMode.PKCS7;

            // Step 4. Convert the input string to a byte[]
            byte[] DataToEncrypt = UTF8.GetBytes(Message);

            // Step 5. Attempt to encrypt the string
            try
            {
                ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor();
                Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length);
            }
            finally
            {
                // Clear the TripleDes and Hashprovider services of any sensitive information
                TDESAlgorithm.Clear();
                HashProvider.Clear();
            }

            // Step 6. Return the encrypted string as a base64 encoded string
            return Convert.ToBase64String(Results);
        }

        public static string DecryptString(string Message, string Passphrase)
        {
            byte[] Results;
            System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();

            // Step 1. We hash the passphrase using MD5
            // We use the MD5 hash generator as the result is a 128 bit byte array
            // which is a valid length for the TripleDES encoder we use below

            MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
            byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));

            // Step 2. Create a new TripleDESCryptoServiceProvider object
            TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();

            // Step 3. Setup the decoder
            TDESAlgorithm.Key = TDESKey;
            TDESAlgorithm.Mode = CipherMode.ECB;
            TDESAlgorithm.Padding = PaddingMode.PKCS7;

            // Step 4. Convert the input string to a byte[]
            byte[] DataToDecrypt = Convert.FromBase64String(Message);

            // Step 5. Attempt to decrypt the string
            try
            {
                ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();
                Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);
            }
            finally
            {
                // Clear the TripleDes and Hashprovider services of any sensitive information
                TDESAlgorithm.Clear();
                HashProvider.Clear();
            }

            // Step 6. Return the decrypted string in UTF8 format
            return UTF8.GetString(Results);
        }
    }
}

Wednesday, 11 January 2012

Asynchronous Processing

Introduction
                        Hi, today we will demonstrate asynchronous processing using delegates and events. One might think what the need of doing work   asynchronously in windows environment. Yes, it is required. By sample example we will prove this.
The Program
                        In this program we will develop a class will have certain events and delegates to handle those events. Our class will have a function to perform task and continuously changes the status through raising events.
public class Task
    {
        public delegate void UpdateStatusEventHandler(string text, int total, int current);
        public delegate void UpdateTextEventHandler(string text);
        public delegate void UpdateProgressBarEventHandler(int total, int value);

        public event UpdateStatusEventHandler UpdateStatus;
        public event UpdateTextEventHandler UpdateText;
        public event UpdateProgressBarEventHandler UpdateProgressBar;

        ……….
    }
                As shown in code we define 3 events for updating status, text and progress bar value as per task perform. For handling these events we define 3 delegates. As we all knows delegate works asynchronously, so whenever we raise these events, they will execute asynchronously.
This event handled from Windows Form. Code to handle these events are as follows.
            Task task = new Task();
            task.UpdateProgressBar += new Task.UpdateProgressBarEventHandler(task_UpdateProgressBar);
            task.UpdateStatus += new Task.UpdateStatusEventHandler(task_UpdateStatus);
            task.UpdateText += new Task.UpdateTextEventHandler(task_UpdateText);
in order to handle these events we’ve to register them first. To register them first create instance of class which owns those events. As you can see delegates which we defined in that class are working as event handler and each event handler has reference of a function having code for handling this events.
        private void task_UpdateStatus(string text, int total, int current)
        {
            eUpdateStatus(lblStatus, text, total, current);
        }

        private void task_UpdateText(string text)
        {
            eUpdateText(lblText, text);
        }

        private void task_UpdateProgressBar(int total, int value)
        {
            eUpdateProgressBar(pbTask, total, value);
        }
Now let us see how to update windows contron state asynchronously. For that you have to define delegates. As we knows delegates are special typed class which can point function having same signature. We’ll define delegates and functions that work asynchronouly for us.
        private delegate void delUpdateStatus(Label lbl, string text, int total, int current);       
        private void mUpdateStatus(Label lbl, string text, int total, int current)
        {
            if (lbl.InvokeRequired)
            {
                lbl.BeginInvoke(new delUpdateStatus(mUpdateStatus1), lbl, text, total, current);
            }
        }

        private void mUpdateStatus1(Label lbl, string text, int total, int current)
        {
            lbl.Text = string.Format("{0}/{1}\n {2}", current, total, text);
            lbl.Update();
            lbl.Parent.Update();
            this.Update();
        }
As we shown above we defined delegate and its function for updating label status. Here you notice BeginInvoke method which execute asynchronously for updating control status


Tuesday, 18 October 2011

What is Mock Objects?

Mock objects are objects that are isolated from there dependencies for testing purpose. In other words mock object is a simulated object that mimics the behavior of a real object in controlled ways. Mock objects are often used in unit testing to analyze the performance of actual objects. In this context, an object is the smallest testable part of an application. A mock object makes use of the same interface as the element of code it is intended to imitate.
Mock objects have two roles during a test case: actor and critic.
The actor behavior is to simulate objects that are difficult to set up or time consuming to set up for a test i.e.  database connection. Setting up a test database at the start of each test would slow testing to a crawl and would require the installation of the database engine and test data on the test machine. If we can simulate the connection and return data of our choosing we not only win on the pragmatics of testing, but can also feed our code spurious data to see how it responds. We can simulate databases being down or other extremes without having to create a broken database for real. In other words, we get greater control of the test environment.
If mock objects only behaved as actors they would simply be known as "server stubs". This was originally a pattern named by Robert Binder (Testing object-oriented systems: models, patterns, and tools, Addison-Wesley) in 1999.
A server stub is a simulation of an object or component. It should exactly replace a component in a system for test or prototyping purposes, but remain lightweight. This allows tests to run more quickly, or if the simulated class has not been written, to run at all.
However, the mock objects not only play a part (by supplying chosen return values on demand) they are also sensitive to the messages sent to them (via expectations). By setting expected parameters for a method call they act as a guard that the calls upon them are made correctly. If expectations are not met they save us the effort of writing a failed test assertion by performing that duty on our behalf.
In the case of an imaginary database connection they can test that the query, say SQL, was correctly formed by the object that is using the connection. Set them up with fairly tight expectations and you will hardly need manual assertions at all.


A mock object can be useful in place of a real object that:
  • Runs slowly or inefficiently in practical situations
  • Occurs rarely and is difficult to produce artificially
  • Produces non-deterministic results
  • Does not yet exist in a practical sense
  • Is intended mainly or exclusively for conducting tests

Query Execution in LinQ


In LINQ, queries have two different behaviors of execution: immediate and deferred. In this article, we will take a quick overview of how Deferred query execution and Immediate Query Execution works in LINQ
Deferred Query Execution
To understand Deferred Query Execution, let’s take the following example which declares some Employees and then queries all employees with Age > 28:

class Employee

{

public int ID { get; set; }

public string Name { get; set; }

public int Age { get; set; }

}

static void main(string[] args)
{
var empList = new List<Employee>(
new Employee[]
{
new Employee{ID=1, Name=“Himanshu”, Age=“30″},
new Employee{ID=2, Name=“Rahul”, Age=“35″},
new Employee{ID=3, Name=“Hetal”, Age=“26″},
new Employee{ID=4, Name=“Varsha”, Age=“28″},
});
var lst = from e in empList
where e.Age > 28 //<= query seems to be executed here
select new { e.Name };
foreach (var emp in lst)
Console.WriteLine(emp.Name);
Console.ReadLine();
}
OUTPUT: Himanshu, Rahul
Looking at the query shown above, it appears that the query is executed at the point where the arrow is pointing towards. However that’s not true. The query is actually executed when the query variable is iterated over, not when the query variable is created. This is called deferred execution.
Now how do we prove that the query was not executed when the query variable was created? It’s simple. Just create another Employee instance after the query variable is created
static void main(string[] args)
{
var empList = new List<Employee>(
new Employee[]
{
new Employee{ID=1, Name=“Himanshu”, Age=“30″},
new Employee{ID=2, Name=“Rahul”, Age=“35″},
new Employee{ID=3, Name=“Hetal”, Age=“26″},
new Employee{ID=4, Name=“Varsha”, Age=“28″},
});
var lst = from e in empList
where e.Age > 28 //<= query Variable
select new { e.Name };
empList.Add(new Employee { ID = 5, Name = “Tarun”, Age = “39″ }); //<= New employee initialization
foreach (var emp in lst)
Console.WriteLine(emp.Name);
Console.ReadLine();
}
Notice we are creating a new Employee instance after the query variable is created. Now had the query been executed when the query variable is created, the results would be the same as the one we got earlier, i.e. only two employees would meet the criteria of Age > 28. However the output is not the same
OUTPUT: Himanshu, Rahul, Tarun.
What just happened is that the execution of the query was deferred until the query variable was iterated over in a foreach loop. This allows you to execute a query as frequently as you want to, like fetching the latest information from a database that is being updated frequently by other applications. You will always get the latest information from the database in this case.

Immediate Query Execution
You can also force a query to execute immediately, which is useful for caching query results. Let us say we want to display a count of the number of employees that match a criteria.
static void main(string[] args)
{
var empList = new List<Employee>(
new Employee[]
{
new Employee{ID=1, Name=“Himanshu”, Age=“30″},
new Employee{ID=2, Name=“Rahul”, Age=“35″},
new Employee{ID=3, Name=“Hetal”, Age=“26″},
new Employee{ID=4, Name=“Varsha”, Age=“28″},
});
var lst = (from e in empList
where e.Age > 28
select e).Count(); //<= Immediate Execution
empList.Add(new Employee { ID = 5, Name = “Tarun”, Age = “39″ });
Console.WriteLine(“Total employees whose age is > 28 are {0}”, lst);
Console.ReadLine();
}
In the query shown above, it order to count the elements that match the condition, the query must be executed, and this is done automatically when Count( ) is called. So adding a new employee instance after the query variable declaration does not have any effect here, as the query is already executed. The output will be 2, instead of 3.
The basic difference between a Deferred execution vs Immediate execution is that Deferred execution of queries produce a sequence of values, whereas Immediate execution of queries return a singleton value and is executed immediately. Examples are using Count(), Average(), Max() etc.