Blog

C# Custom Sorting using Anonymous Methods and the Comparer Generic

Quick and Concise sorting without all the extra code or bother of implementing custom sorting through interfaces, sound impossible? Here we will use a generic list full of a custom object type of our defining and we will sort it using Anonymous Methods and the generic Comparer class provided for us by the .Net framework.

Custom Class:

public class Book

{

public string ISBN { get; set; }

public string Title { get; set; }

public int Volume { get; set; }

}

On the Fly Sorting:

{

List library = new List();

//Add a bunch of books to the library collection here

//Sort the library alphabetically by Title

library.Sort( delegate (Book bookOne, Book bookTwo)

{

return Comparer.Default.Compare(bookOne.Title, bookTwo.Title);

});

//Sort the library by Volume number

library.Sort( delegate (Book bookOne, Book bookTwo)

{

return Comparer.Default.Compare(bookOne.Volume, bookTwo.Volume);

});

}

C# Anonymous Methods as Event Handler

As standard practice in .Net you create separate Event Handlers to handle the events of all controls on a form. In my personal code I always attempt to keep action code out of the event handlers and isolate it in its own method, this helps to keep things clean and easily altered if events change (see example below).

Example Code
        protected void Page_Load(object sender, EventArgs e)
        {
            Button1.Click += Button1_Click;
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            LoadSomeData();
        }

        private void LoadSomeData()
        {
            //Do something here.
        }

Now in .Net 2.0 we are allowed to use what are called Anonymous Methods. Anonymous Methods are code blocks which can be passed as (delegate) parameters to methods accepting delegates. Anonymous Methods allow us to get ride of extra methods and the overhead they create and simply pass an Anonymous Method. Because of this new feature instead of creating a separate method as an event handler to handle the button’s click event we can simply pass the Anonymous Method as the parameter using the delegate key word. This removes that extra method and reduces our code (see example below).

Example Code:
        protected void Page_Load(object sender, EventArgs e)
        {
            Button1.Click += delegate(object sender1, EventArgs e1)
                                 {
                                     LoadSomeData();
                                 };
        }

        private void LoadSomeData()
        {
            //Do something here.
        }

This is of course an extremely simplified use of Anonymous Methods meant to be just an example of how they work, although simple it is still a valid use and may or may not help you in your code. In future posts I will attempt to show the use of Anonymous Methods in more complex scenarios but for now at least we understand what they are and how they can be used.

XPath, XML and Namespaces

Rant: First off I find it extremely irritating when individuals use Namespaces in simple XML documents just for the heck of it! Just because you can use it doesn’t mean you should. Use Namespaces where appropriate, like when there are naming conflicts due to the use of multiple Schema’s on a single document.  This is of course just my opinion so take it or leave it!

One issue I have run across on multiple occasions when parsing XML documents with multiple Namespaces (or even a single Namespace) using XPath is the fact that XPath is designed to select nodes that are not within a Namespace or within a specific Namespace. for some reason I always just assume the XPath expression “//customer” will pull out all customer elements in a document no matter where in the document they are located.

Code Example: {    XmlNodeList selected = Customers.SelectNodes("//customer");}

This is true, if and only if your document does not have any Namespaces defined or all of your customer elements are outside of any defined Namespaces. But if your document contains a Namespace and those customer elements are inside it the code will simply return a big fat null.

In order to overcome Namespace issues you have to use the XmlNamespaceManager class which is passed along with your XPath query. Not only do you need to pass the manager with the XPath you now have to modify the query to use the Namespace prefix you assigned when instantiating the manager.

Code Example:{    XmlNamespaceManager manager = new XmlNamespaceManager(new NameTable());    manager.AddNamespace("c", "MyCustomerNamespace");    XmlNodeList selected  = Customers.SelectNodes("//c:customer", manager);}

Now you will retrieve all of the customer elements in the XML document because now you have specified that instead of searching all nodes without a Namespace it should search all nodes within the “MyCustomerNamespace” Namespace.

C# Casting Objects to Types

In .Net C# there are 3 ways to cast an object to a specific type. Implicit, Explicit and As. So what is the difference and why do I need to know?

Implicit Casting: this is where the system takes care of the casting for you with no extra code on your part. Implicit Casting happens when one type such as an Int is cast to a Double. Because an Integer is a whole number (having no decimal place) and a Double is a floating point number (having a decimal place) the conversion of lets say the Integer 5 to a double of 5.0 no information about the original Integer is lost (5 == 5.0). Because there is no loss of data the .Net system has no issue with making the conversion without warning you.

Code Example:
{
    int i = 5;
    double d = i;
}

Explicit Casting: in this case there is the possibility data may be lost in the conversion from one type to another and the system therefore will not take care of the cast itself, it requires you to make sure you know what you are doing and specifically tell it you are fine if data is lost in the conversion. Taking our previous example and just switching it around a Double 5.25 cast to a Integer of 5 causes a loss of data and thus a loss in precision because of this .Net requires you to verify its OK to dump the .25 from the Double.

Code Example:
{
    double d = 5.25;
    int i = (int)d;
}

Both of the above Casting options will return an exception if the casting is not possible for any reason at all, thus casting needs to take place within a Try-Catch block in order to handle these situations. If you don’t want to handle exceptions thrown by these 2 Casting options there is one more that is rarely used by developers, the AS keyword.

AS: the as keyword in .Net allows you to specify an Explicit Cast needs to happen but instead of an Exception being thrown if the cast is not possible a null value is simply returned. Now you only need to check if the value is null before continuing on with your code, if it is you then have the option to do some more processing to get the value you need. This limits the overhead and code that is needed to handle casting exceptions. Now there is a limitation to the use of the as operator, unfortunately it only performs reference conversions or boxing conversions.  It cannot perform conversions like user-defined conversions for these you will need to use Explicit Casting.

Code Example:
{
    double d = 5.25;
    int i = d as int;
}

ASP.net Checking for an AJAX ScriptManager on the Current Page

Depending on the way in which you have designed your web application (Master Pages, Master Pages within Master Pages, Templates, Embedded Controls)  or if you are using a out of the box framework you may or may not know if an AJAX ScriptManager has been loaded on the current page. Lets say you have a custom control which uses the built in .Net AJAX library in order to function correctly. Instead of just assuming a ScriptManager has been placed on the page by the original page or framework developer and possibly experience exceptions caused by the lack of a ScriptManager or placing one within your control and possibly experiencing exceptions due to too many ScriptManagers on the page, you should simply check the page first. If no ScriptManager is available then add one dynamically from within your control.

A ScriptManager must be placed in the Page’s Form and there can only be one per page. The following code example checks the current page to see if a ScriptManager has been loaded, if so the control loads normally, if not a ScriptManager is instantiated and added to the current Page.Form.Controls collection and the control is then loaded.

You will also notice in this code block that I have set the AsyncPostBackTimeout to a large number. I have found on several occasions that when there are long running processes called through AJAX calls the default timeout is way too short. This timeout needs to be increased otherwise the call times out and your update panels never complete their update.

        protected void Page_Load(object sender, EventArgs e)
        {
            if (
ScriptManager.GetCurrent(this)
== null)
            {
                sManager = new ScriptManager();
                sManager.AsyncPostBackTimeout = 999999;
                Form.Controls.Add(sManager);
            }
        }

C# Extension Methods

Microsoft has added a wonderful new addition to the .Net framework, Extension Methods! Extension methods allow you to add custom methods to already existing types (class) without the need to derive a new type from them or modify them (some of which you can’t such as built in .Net System types i.e. String, Int, Double). How it all works is these newly defined methods attach themselves to the type which they are referncing and can be used as if they are one of the original methods created at its inception. I good example of the perfect implementation of Extension Methods is the new LINQ library which when referenced in your code adds tons of new, fancy methods to collection types which implement the IEnumerable interface (there may be more to it than I have written here, but I am trying to be brief).

In order to set up your own custom Extension Methods within your assembly you need to define a Static Class which will hold all of these methods. Depending on the number of these methods you have for each type you wish to extend you may want to have a seperate Static Class for each of those types containing only the methods for that type. Extension Methods are Static just as the class that holds them.

Here is an example using the default System.String type:

public static class CustomStringExtensions

{
    public static bool ContainsQuestion(this String str)
    {
        return str.Contains('?');
    }
}

Now as long as you reference the assembly which contains this class every String object you use will automatically have the ContainsQuestion method.