Monday, 9 April 2012

ABC of C# Iterator Pattern


Introduction
The aim of this alternative tip is to give more relevant information to the beginner as well as why the heck one should bother about iterators at all.
Lets start with that: why to bother what the iterator pattern is? You use the iterator pattern most likely in your every day work maybe without being aware of:
IList<string> names = new List<string>() { "Himanshu", "Hetal", "Viral" };

foreach (string name in names)
{
    Console.Write("Name : {0}", name);
}

The iterator tells the foreach loop in what sequence you get the elements.

Using  Code

A class that can be used in a foreach loop must provide a IEnumerator<T> GetEnumerator() { ... } method. The method name is reserved for that purpose. This function defines in what sequence the elements are returned.

Some classes may also provide the non-generic IEnumerator GetEnumerator() { ... } method. This is from the older days where there were no generics yet, e.g. all non-generic collections like Array, etc. provide only that "old-fashioned" iterator function.

Behind the scenes, the foreach loop

foreach (string name in names) { ... }

translates into:

Explicit Generic Version                                                                               Explicit non-generic version

using (var it = names.GetEnumerator())          var it = names.GetEnumerator()
while (it.MoveNext())                           while (it.MoveNext())
{                                               {
    string name = it.Current;                       string name = (string)it.Current;
    ....                                            ....
}                                               }

the two explicit iterator calls can be combined into one:

var it = names.GetEnumerator()
using (it as IDisposable)
while (it.MoveNext())
{
    string name = it.Current;
    ....
}

So, the core of the C# implementation of the Iterator Pattern is the GetEnumerator() method. What are now these IEnumerator/IEnumerator<T> interfaces?

What’s an iterator?

An iterator provides a means to iterate (i.e. loop) over some items. The sequence of elements is given by the implementations of the IEnumerator/IEnumerator<T> interfaces:

namespace System.Collections
{
    public interface IEnumerator
    {
        object Current { get; }
        bool MoveNext();
        void Reset();
    }
}
namespace System.Collections.Generic
{
    public interface IEnumerator<out T> : IDisposable, IEnumerator
    {
        T Current { get; }
    }
}

The pattern is basically given by MoveNext() and Current. The semantics is that one has to first call MoveNext() to get to the first element. If MoveNext() returns false, then there is no more element. Current returns the current element. You are not supposed to call Current if the preceeding MoveNext() returned false.
The MoveNext() gives the next element in the sequence of elements - what ever that sequence is, e.g. from first to last, or sorted by some criteria, or random, etc.
You know now how to apply the iterator pattern (e.g. in a foreach loop) and that this is possible for all classes that provide the above mentioned GetEnumerator() method (the iterator).
What is IEnumerable/IEnumerable<> for?
These interfaces are quite simple:
namespace System.Collections
{
    public interface IEnumerable
   {
        IEnumerator GetEnumerator();
   }
}

namespace System.Collections.Generic
{
    public interface IEnumerable<out T> : IEnumerable
   {
        IEnumerator<T> GetEnumerator();
   }
}
So, easy answer: they provide an iterator (one "old-fashioned", one with generics).
A class that implements one of these interfaces provides an iterator implementation. Furthermore, such an instance can be used wherever one of these interface is needed.
 Note: it is not required to implement this interface to have an iterator: one can provide its GetEnumerator() method without implementing this interface. But in such a case, one can not pass the class to a method where IEnumerable<T> is to be passed.
E.g. there is a List<T> constructor that takes an IEnumerable<T> to initialize its content from that iterator.
namespace System.Collections.Generic
{
    public class List<T> : IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection, IEnumerable
    {
        ...
        public List(IEnumerable<T> collection);
        ...
    }
}
If you look now at the LINQ extension methods: many of these base on IEnumerable<T>, thus, extending any iterator class by some new function that often return yet another iterator. E.g.
namespace System.Linq
{
    public static class Enumerable
     {

        ...
        public static IEnumerable<TResult> Select<TSource, TResult>(
this IEnumerable<TSource> source, Func<TSource, TResult> selector);

        ...
        public static IEnumerable<TSource> Where<TSource>(
this IEnumerable<TSource> source, Func<TSource, bool> predicate);

        ...
    }
}
This is used as:
    List<string> list = ...;
    var query = from s in list where s.Length > 2 select s;
    foreach (string s in query)
    {
       ...
    }
And again, the C# language provides an alterantive way to express this (one could say simpler):
    List<string> list = ...;
    var query = from s in list where s.Length > 2 select s;
     foreach (string s in query)
    {
       ...
    }
This is LINQ - Language Integrated Queries: Extension methods that can be expressed in the form from ... in ... where ... select (to show some of the LINQ keywords). Please note that you can always write a LINQ expression as a chain of extension methods as shown above.
So, now you know the benefits of the IEnumerable<T> interfaces and where and how they are used.








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