Extension Methods for Daily Use

Introduction
 
Extension Methods allows the programmer to extend the functionality of a type without having to derive from the type. Because of this flexibility and the way the methods need to be declaring it creates many possibilities for simplification of binding, encrypting, and special sorting algorithms.
 
Note: For a deeper understanding of Extension Methods please see Extension Methods (C# Programming Guide)
 
Binding
 
For the last couple of years I worked primairly in Asp.net and binding is part of the daily boiler plate code.  The binding extension below works for a DropDownList, but it would work the same way for a ListBox or other controls like the GridView. Figure 1 illustrates the extension method under our DropDownList.
  1. public static void Bind(this DropDownList control, object dataSource,string dataTextField, string dataValueField)  
  2. {  
  3.     control.DataSource = dataSource;  
  4.     control.DataTextField = dataTextField;  
  5.     control.DataValueField = dataValueField;  
  6.     control.DataBind();  
  7. } 
Extension Methods
 
Figure 1
 
Now I have the ability to reduce all my DropDownList controls binding code to a line similar to the following.
  1. dllProjects.Bind(IssueViewRepository.GetAllProjects(), "Project1""IssuesTable"); 
Encryption
 
The other code that needs to be written for production systems is the ability to encrypt and decrypt strings.  There are many sources that cover security and hashing algorithms so the following code just extends any string to add the ability to called Encrypt and Decrypt the string. 
  1. public static string Encrypt(this string value)  
  2. {  
  3.     CryptoStream cryptoStream = null;  
  4.     RijndaelManaged rijndaelManaged = null;  
  5.     ICryptoTransform encrypt = null;  
  6.     MemoryStream memoryStream = new MemoryStream();  
  7.     try  
  8.     {  
  9.         if (!string.IsNullOrEmpty(value))  
  10.         {  
  11.             // Create crypto objects  
  12.             rijndaelManaged = new RijndaelManaged();  
  13.             rijndaelManaged.Key = Key;  
  14.             rijndaelManaged.IV = IV;  
  15.             encrypt = rijndaelManaged.CreateEncryptor();  
  16.             cryptoStream = new CryptoStream(memoryStream, encrypt, CryptoStreamMode.Write);  
  17.             // Write encrypted value into memory  
  18.             byte[] input = Encoding.UTF8.GetBytes(value);  
  19.             cryptoStream.Write(input, 0, input.Length);  
  20.             cryptoStream.FlushFinalBlock();  
  21.             // Retrieve the encrypted value to return  
  22.             return Convert.ToBase64String(memoryStream.ToArray());  
  23.         }  
  24.         else  
  25.             return value;  
  26.     }  
  27.     catch (Exception) { return value; }  
  28.     finally  
  29.     {  
  30.         if (rijndaelManaged != null) rijndaelManaged.Clear();  
  31.         if (encrypt != null) encrypt.Dispose();  
  32.         if (memoryStream != null) memoryStream.Close();  
  33.     }  
  34. }  
  35.   
  36. public static string Decrypt(this string value)  
  37. {  
  38.     try  
  39.     {  
  40.         byte[] workBytes = Convert.FromBase64String(value);  
  41.         byte[] tempBytes = new byte[workBytes.Length];  
  42.         // Create the Rijndael engine  
  43.         RijndaelManaged rijndael = new RijndaelManaged();  
  44.         // Bytes will flow through a memory stream  
  45.         MemoryStream memoryStream = new MemoryStream(workBytes);  
  46.         // Create the cryptography transform  
  47.         ICryptoTransform cryptoTransform = rijndael.CreateDecryptor(Key, IV);  
  48.         // Bytes will be processed by CryptoStream  
  49.         CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Read);  
  50.         // Move the bytes through the processing stream  
  51.         cryptoStream.Read(tempBytes,0,tempBytes.Length);  
  52.         // Close the streams  
  53.         memoryStream.Close();  
  54.         cryptoStream.Close();  
  55.         return Encoding.UTF8.GetString(tempBytes).TrimEnd('\0');  
  56.     }  
  57.     catch (Exception) { return value; }  
  58. }  
Sorting
 
I always had an issue with sorting a ListBox, but now that you can write an extension to control the sorting algorithm, it could be applied to all your controls without re-writing code. Below Sorting is just a structure with an Index and Weight value to give to each Item in the control. The following algorithm is extremely simplistic because it uses the ASCI value from the first letter as the Weight and since ASCI increment alphabetically we have no issues here.
  1. public static void Sort(this ListBox listBox)  
  2. {  
  3.     try  
  4.     {  
  5.         ListItemCollection collection = listBox.Items;  
  6.         List<ListItem> newCollection = new List<ListItem>(1);  
  7.         List<Sorting> sorter = new List<Sorting>(1);  
  8.         if (collection.Count > 0)  
  9.         {  
  10.             for (int x = 0; x < collection.Count; x++)  
  11.             {  
  12.                 ListItem Item = collection[x];  
  13.                 Sorting sort = new Sorting() { Index = x, Weight = 0 };  
  14.                 if (!string.IsNullOrEmpty(Item.Text) && Item.Text.Length > 0)  
  15.                     sort.Weight = (int)Item.Text[0];  
  16.                 sorter.Add(sort);  
  17.             }  
  18.             sorter = sorter.OrderBy(x => x.Weight).ToList<Sorting>();  
  19.             foreach (Sorting sort in sorter)  
  20.                 newCollection.Add(collection[sort.Index]);  
  21.         }  
  22.         listBox.Items.Clear();  
  23.         listBox.Items.AddRange(newCollection.ToArray());  
  24.     }  
  25.     catch (Exception) { }  
  26. }  
Conclusion
 
I don't see everyone rushing to re-write all their utility classes into extensions anytime soon, but much like the utilities we write and find ourselves reusing time and time again, extension methods are a great feature to keep in mind.