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.

public static void Bind(this DropDownList control, object dataSource,string dataTextField, string dataValueField)
{
    control.DataSource = dataSource;
    control.DataTextField = dataTextField;
    control.DataValueField = dataValueField;
    control.DataBind();
}

1.gif

Figure 1

Now I have the ability to reduce all my DropDownList controls binding code to a line similar to the following.

dllProjects.Bind(IssueViewRepository.GetAllProjects(), "Project1", "IssuesTable");

Encryption

The other code that needs to be writtem 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. 

public static string Encrypt(this string value)
{
    CryptoStream cryptoStream = null;
    RijndaelManaged rijndaelManaged = null;
    ICryptoTransform encrypt = null;
    MemoryStream memoryStream = new MemoryStream();
    try
    {
        if (!string.IsNullOrEmpty(value))
        {
            // Create crypto objects
            rijndaelManaged = new RijndaelManaged();
            rijndaelManaged.Key = Key;
            rijndaelManaged.IV = IV;
            encrypt = rijndaelManaged.CreateEncryptor();
            cryptoStream = new CryptoStream(memoryStream, encrypt, CryptoStreamMode.Write);
            // Write encrypted value into memory
            byte[] input = Encoding.UTF8.GetBytes(value);
            cryptoStream.Write(input, 0, input.Length);
            cryptoStream.FlushFinalBlock();
            // Retrieve the encrypted value to return
            return Convert.ToBase64String(memoryStream.ToArray());
        }
        else
            return value;
    }
    catch (Exception) { return value; }
    finally
    {
        if (rijndaelManaged != null) rijndaelManaged.Clear();
        if (encrypt != null) encrypt.Dispose();
        if (memoryStream != null) memoryStream.Close();
    }
}

public static string Decrypt(this string value)
{
    try
    {
        byte[] workBytes = Convert.FromBase64String(value);
        byte[] tempBytes = new byte[workBytes.Length];
        // Create the Rijndael engine
        RijndaelManaged rijndael = new RijndaelManaged();
        // Bytes will flow through a memory stream
        MemoryStream memoryStream = new MemoryStream(workBytes);
        // Create the cryptography transform
        ICryptoTransform cryptoTransform = rijndael.CreateDecryptor(Key, IV);
        // Bytes will be processed by CryptoStream
        CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Read);
        // Move the bytes through the processing stream
        cryptoStream.Read(tempBytes,0,tempBytes.Length);
        // Close the streams
        memoryStream.Close();
        cryptoStream.Close();
        return Encoding.UTF8.GetString(tempBytes).TrimEnd('\0');
    }
    catch (Exception) { return value; }
}

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 apply 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 algoritm is extremly simplistic because it uses the ASCI value from the first letter as the Weight and since ASCI increment alphabetically we have no issues here.

public static void Sort(this ListBox listBox)
{
    try
    {
        ListItemCollection collection = listBox.Items;
        List<ListItem> newCollection = new List<ListItem>(1);
        List<Sorting> sorter = new List<Sorting>(1);
        if (collection.Count > 0)
        {
            for (int x = 0; x < collection.Count; x++)
            {
                ListItem Item = collection[x];
                Sorting sort = new Sorting() { Index = x, Weight = 0 };
                if (!string.IsNullOrEmpty(Item.Text) && Item.Text.Length > 0)
                    sort.Weight = (int)Item.Text[0];
                sorter.Add(sort);
            }
            sorter = sorter.OrderBy(x => x.Weight).ToList<Sorting>();
            foreach (Sorting sort in sorter)
                newCollection.Add(collection[sort.Index]);
        }
        listBox.Items.Clear();
        listBox.Items.AddRange(newCollection.ToArray());
    }
    catch (Exception) { }
}

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.

Up Next
    Ebook Download
    View all
    Learn
    View all