Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
DevExpress UI Controls
Search :       Advanced Search »
Home » C# Language » Extension Methods for Daily Use

Extension Methods for Daily Use

Extension Methods allows the programmer to extend the functionality of a type without having to derive from the type.

Author Rank :
Page Views : 3012
Downloads : 0
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
DevExpress Free UI Controls
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


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.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Felipe Ramos
Developer for the last 7-8 years using .NET technologies.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Comments
Nice Article by Mike On September 2, 2010
I like the encryption methods on string! Thanks Felipe.
Reply | Email | Modify 
Re: Nice Article by Felipe On September 2, 2010
Thanks Mike, glad to be of service.
Reply | Email | Modify 

 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.