Month: February 2008


Why Do You Write Code?

Jeff Blankenburg posed an interesting question on his blog the other day. He asked, “Why do you write code?”. I started thinking about that question and decided that I not only wanted to answer that question on my blog, but that the answer to that question itself would provide a good synopsis about me for my readers.

The short answer is that it is really who I am. I’ve been fascinated with computers and technology for as long as I can remember. We got an Intellivision when I was very young and had the computer add-on when I was in kindergarten. I remember being able to pull sprites from the game cartridges and move them around the screen and writing rudimentary BASIC programs. The system had so little RAM that it had to have a modified version of BASIC; PRINT became PRIN to save a few bites.

I remember being enamored with what that computer represented. I could give instructions to a machine and it would do as I had asked. I loved programming on the computer because it shared two major themes with another love of my life, Mathematics. First of all, programming was about solving problems. I am at point A, I need to get to point B, what steps can I employ to make that happen? Secondly, computer programming was exact. Barring weirdness, a computer executed its instructions the same way given the same inputs the same way that 2 + 2 will always equal 4. There is something comforting in that.

After the Intellivision computer, we got a Commodore 64 and then a Commodore 128. Games Magazine used to publish BASIC programs for you to input into your computer. There were a lot of PEEK and POKE commands in the lines of code that I didn’t understand at the time, but I still felt like the world’s biggest hacker to make this code run.

As I grew up, I went through a variety of languages and ultimately ended up where I am now, writing C#.Net code. The platforms and the languages have changed, but what I do is still about taking a challenge and performing steps against it in order to reach my goal. 2 + 2 still always equals 4, though sometimes I really have to pay attention to make sure that the computer is getting 2 and 2 and not -87 and 1,348,849 😉 The computer isn’t very smart and does only exactly what it is told, which I guess sometimes makes me not very smart!

Even with that limitation, I feel extremely fortunate to have a career I love that remains challenging and fulfilling. There is nothing like the feeling when you’ve been given a difficult task and you are able to overcome it. That’s why I write code.

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.