Code Tips

C# Extension Methods

One of my favorite features of C# 3.0 is the extension method. An extension method basically allows you to add a method to a class without altering the class itself. All you need to do is declare some static methods with a “this” keyword in the parameters. .Net will then add this method on to whatever class you indicate is a parameter of the method (immediately following the “this” keyword). Then, as long as you have included the namespace in your using declarations in the code file, you are all set. Some examples would probably help. Here are some sample declarations.

public static class MyExtensions
    /// <summary>
    /// Validates (poorly) if an email address is in
    /// the right format.
    /// </summary>
    /// <param name="address">The email address to validate</param>
    /// <returns></returns>
    public static bool IsEmailAddress(this string address)
        // Note: A purposely short pattern.  Not suitable
        // for enterprise-level validation
        Regex regex = new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$");
        return regex.IsMatch(address);

    /// <summary>
    /// Determines the future datetime, given the number
    /// of minutes to go forward.
    /// </summary>
    /// <param name="minutes">Number of Minutes to Add</param>
    /// <returns></returns>
    public static DateTime MinutesFromNow(this int minutes)
        return System.DateTime.Now.AddMinutes(minutes);

    /// <summary>
    /// Reverses the characters in a string. 
    /// This method should have been included in the base library.
    /// </summary>
    /// <param name="input">The string to be reversed</param>
    /// <returns></returns>
    public static string Reverse(this string input)
        char[] inputArray = input.ToCharArray();
        return new string(inputArray);

You can see that I’ve created three methods and added XML comments to them (so I get intellisense on those methods later). Looking at the Reverse method, I declare it just like a normal method, “public static string Reverse” but then in the arguments, I just add a “this” before I set the parameter. So, instead of just “string input”, I have “this string input”. This tells .Net to add this method as an extension on the string class.

You can see from this example that I see my Reverse method in a string’s intellisense as well as my comments for the method.
Example of the Reverse() extension method

My total code to use each of my extension methods listed above is as follows.

static void Main()
    Console.WriteLine("Reversed String: {0}", "PeteOnSoftwareRules!".Reverse());
    Console.WriteLine("Now: {0}", System.DateTime.Now);
    Console.WriteLine("In 20 Mins: {0}", 20.MinutesFromNow());
    Console.WriteLine(" {0}", "".IsEmailAddress());
    Console.WriteLine("NotAnEmailAddress: {0}", "NotAnEmailAddress".IsEmailAddress());

When I run the code, I get the following results.
Example of the extension methods' output.

Good so far, but for now it seems like I am just changing how you would write some validation methods. Instead of IsEmailAddress(“”), I am suggesting you write “”.IsEmailAddress(). That is true so far. You could also create your own type that inherits from string and add a method, but then everyone else would have to use your type instead of the built-in .Net type. That’s not good at all. Additionally, extension methods add value by solving another problem.

Sometimes, you have to work with a framework or some third party class that has been sealed. I have for you the following example. It isn’t super useful, but concise, and will show my point 😉

public sealed class CannotInheritAndExtend
    public string FirstName = string.Empty;
    public string LastName = string.Empty; 

    public void PrintFirstName()
        Console.WriteLine("First Name: {0}", this.FirstName);

I really need this class to write out the last name, also. With this example, it is impossible to say “public class WillInheritAndExtend : CannotInheritAndExtend” and then just add my own method. Go ahead and try. You will get a beautiful compiler error. What you can do, however, is the following:

public static void PrintLastName(this CannotInheritAndExtend input)
    Console.WriteLine("Last Name: {0}", input.LastName);

Now my method is included in intellisense for the original class.
Intellisense for the new method on the sealed class.

So, now I can have this code

CannotInheritAndExtend a = new CannotInheritAndExtend();
a.FirstName = "pete";
a.LastName = "shearer";

that produces the desired output.
Results of new method on the sealed class.

As you can see, extension methods are really very helpful. They allow you to keep original types intact, but extend functionality onto them. I hope you find them as useful and cool as I do.

Book Reviews

Pro CSS Techniques

Pro CSS TechniquesAPress is far and away my favorite tech book publisher. You’ll probably hear (read) my say that over and over again. When I need to learn a new technology or just get better at an old one, I always look to see what APress has in their stable before venturing out anywhere else.

I’ve used CSS like the next guy. I started off just adding an in-line style or two. Then, I learned about external .css files. Then, I discovered the CSS Zen Garden and realized that I didn’t know anything. However, I still just muddled along, piecing together what I could, trying my best to separate structure from layout.

There are several good resources online to learn about CSS syntax and a few “best practices”, but nothing as comprehensive as this book. Pro CSS Techniques takes you from the base syntax of CSS to tons of nuances included in the latest version (CSS 3 as of the writing of the book, I believe). Also included are tons of “gotchas” for dealing with browser compatibility in a very pragmatic way. I would venture to say that many developers do not inherently follow the advice in this book and struggle mightily for it.

Pro CSS Techniques also includes tons of “real world”-type examples so that you can see how to put this in action. The code examples are also built in such a way so that you do work one way, find out why that doesn’t work, then correct it. I find that more helpful than just showing only 100% correct code and giving a passing explanation as to why other ways aren’t correct.

If you want to become a better web developer, want to learn more about CSS, and you aren’t Eric Meyer or one of the authors of this book, I recommend you pick it up.

Code Tips

Code Tip: C# Coalesce

I have to admit something. I’m something of a Sql Coalesce() fan. I know that Sql Server has an IsNull() function, but there are two bad things about it. First, it is proprietary to Sql Server and I like to try to write my Sql as close to ANSI as I can so that I don’t build up too many bad habits that cause me to have problems when I have to work in other DB platforms. Secondly, IsNull() only takes one option (well, you could nest your IsNull() statements, but that is unwieldy). Coalesce() lets you give a list of items and just takes the first one of them to not be null. Apparently, IsNull() is also slower. All hail, Coalesce()!!!

Several months ago, I was doing some coding in C# and I was actually wishing that C# had a Coalesce function so that I could not have to do a bunch of manual null checking in my code. On a whim, I decided to Google C# Coalesce and see if someone had written one or if there was one hidden in the framework somewhere. To my surprise, I found that C# did have such an animal. Here is an example of its use.

// Checks the HTML Form for a value,
// if that wasn't submitted, use the value
// potentially set elsewhere in the code,
// if that is null, set the variable to
// a blank string.
string value = Request.Form["someField"] as string ?? someVariable ?? string.Empty;

I can’t tell you how much I love having this.

Code Optimization

A Speed Problem

SpeedFirst let me give you a little of the background. At work, we are building a web application. Among other things, we’d like it to be fast. We made many painstaking decisions to build it to be fast. My last post talked about some of the things that we were going to undertake to make sure that it was fast through the pipe.

However, we were having a problem. Page loads were taking over 5 seconds and that was after the initial hit penalty that ASP.Net gives you. I put tracing information in our handler and it turns out that all of our framework code was executing in .05 seconds. That wasn’t the problem. The step of getting the base handler (for the hand off to ASP.Net) however, was taking over 5 seconds.

We had another interesting problem. The ASP.Net Cache object didn’t work. It would be alive for the duration of a page hit, but on the next hit it was gone. My boss suggested that the pages were compiling every time, and we ultimately did see that in the %windir%\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files directory. The question was, “Why?”.

We had wanted the site files to be dynamically compiled for ease of updating, while our framework code remained in pre-compiled .dlls. To troubleshoot, I recommended that we pre-compile the website as well and see what happened. Page hits got down to half a second a piece. Interesting.

Shortly after, though, I got a brainstorm. We were writing log files into a folder in the bin directory (a holdover convention from a previous application) and every time that directory changed (on every page hit), ASP.Net would sense that the bin directory changed (since the log folder was in it and a part of it) and think that the site had changed and now needed a recompile. It makes perfect sense in retrospect!

We moved the log directory outside of the bin, went back to dynamic compilation, and got the same performance improvement that we got with the pre-compiled version – much to my relief.

Book Reviews

High Performance Web Sites

High Performance Web SitesI’m starting to get involved in this book, High Performance Web Sites by Steve Souders. My boss picked it up and read it and had really good things to say. Then the CEO read it and was really geeked about it. So, I decided that I’d better give it more than the cursory glance that I’d previously allotted it. I know that there is a lot of push to write one’s server code to run as quickly as possible, but I feel that the subjects that this book is covering are being largely overlooked.

Mr. Souders wrote the book while he was a Yahoo employee (he works at Google as of January 7th). He is also the creator of YSlow and an expert in web performance. However, you can actually get a lot of the tips if you check out this page and install YSlow onto your machine. YSlow is an addon for Firebug, itself a plugin for Firefox. If you are doing web development, you should already know about Firebug. If you don’t, run – don’t walk – to download it and you can thank me later.

When you run YSlow, it analyzes the current page for each of the 13 points that the Yahoo Developer Network has identified as major causes of web site slowness. It assigns you a grade to each item and gives the site an overall score. For instance, this blog scores a D (65). According to YSlow, I need to add an expires header, use GZip compression, and configure ETags in order to get this site up to par. As an experiment, I may very well dig into trying to get my score up to at *least* a B! If you aren’t sure what these points mean or what I’m talking about, you should check out the links above or get the book.

The book is very well written and is grouped in such a way so that it can be digested separately by different members of a team or by one person. The appendices of the book contain case studies of several major sites using the tools I discussed above and explains what each could do to improve user experience. At $20.00 on Amazon (and used from $11 and change), every web developer really should read this book, implement it, and keep it as a reference for future development.