Creating a NuGet package

If you read my last post you probably know that NuGet is here to stay. To start using NuGet packages, either throught the Package Manager Console or the “Add Library Package Reference” dialogue box, shouldn’t be that hard to figure out. But what about creating packages? It turns out it is almost as simple as using them. I will try to cover the most basic scenarios in this post about how to create your own package and get it up on nuget.org. In the rest of the post I assume you have signed up on nuget.org and you have found your access key under your account.

Ok, so let’s get busy

In the previous version of NuGet, it is currently on version 1.2, it wasn’t possible to create a package directly from the csproj-file, but now it is. So in the most basic scenarios all you need to do create a package is run to runt the nuget pack command on a csproj-file like:

c:\path\to\your\project>nuget pack DoSomeAwesomeStuff.csproj

Running that command will make the project build and create a .nupkg file that is your first NuGet package!. That wasn’t hard, was it? But it is more to it, when running that command NuGet will look in you project and see if you have any NuGet references in your project and include those as NuGet references, which is great! But, there is one feature that is lacking if you ask me… and that is that the content folder, and most likely the tool folder as well, is not added by convention when running this command. Luckily for us it is not that hard to create a work around for this issue. Instead of running the above command you can use:

c:\path\to\your\project>nuget spec DoSomeAwesomeStuff.csproj

which will create a NuGet spec-file for that project. The file will look something like:

<?xml version="1.0"?>
<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
  <metadata>
    <id>$id$</id>
    <version>$version$</version>
    <authors>$author$</authors>
    <owners>$author$</owners>
    <licenseUrl>http://LICENSE_URL_HERE_OR_DELETE_THIS_LINE</licenseUrl>
    <projectUrl>http://PROJECT_URL_HERE_OR_DELETE_THIS_LINE</projectUrl>
    <iconUrl>http://ICON_URL_HERE_OR_DELETE_THIS_LINE</iconUrl>
    <requireLicenseAcceptance>false</requireLicenseAcceptance>
    <description>$description$</description>
    <tags>Tag1 Tag2</tags>
  </metadata>
</package>

All the metadata tags, the ones like $tagName$, will be replaced by the value in the assembly.cs file if you don’t change it to some constant value. When you have this file you can start modifying it to include some content files for example. Content files are files that are placed in the content folder in the created NuGet package, all files in the content folder will be copied to project where the package is installed. So one of my final spec-files look like this:

<?xml version="1.0"?>
<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
  <metadata>
    <id>$id$</id>
    <version>$version$</version>
    <authors>Tomas Jansson</authors>
    <owners>Tomas Jansson</owners>
    <licenseUrl>https://github.com/mastoj/SimpleCompression/blob/master/SimpleCompression/license.txt</licenseUrl>
    <projectUrl>https://github.com/mastoj/SimpleCompression</projectUrl>
    <iconUrl>https://github.com/mastoj/SimpleCompression/raw/master/SimpleCompression/SimpleCompression_icon.png</iconUrl>
    <requireLicenseAcceptance>false</requireLicenseAcceptance>
    <description>$description$</description>
    <tags>ASP.NET MVC3 Compression javascript css</tags>
  </metadata>
  <files>
    <file src="content\App_Start\*.*" target="content\App_Start" />
  </files>
</package>

As you can see I’ve swapped some of the metadata parameters against static values that is not present in the assembly.cs file, so it is no problem at all to mix static values with generic ones. But the most important part is that I’ve added an element to the root node, files, which specify where I have the content I want to include and where I want it to go in the package. That’s all you need to do if you want to include one or more files, in the above example I’m including a startup file for example.

When I now run the nuget pack command on the csproj-file, not the spec-file, NuGet will look at the spec file and include the content files I have specified and the NuGet references will still be added since they are specified in the .csproj-file. It will also use the metadata from the assembly.cs to update the metadata for the package.

The last step in the process is to submit the package to nuget.org, and that is as simple as creating the package. I recommend to do it in two steps the first time, set api access key and the submit. When you have set the api access key you don’t have to write it every time you submit or update a package. So here are the commands:

c:\path\to\your\project>nuget setApiKey xxxxxx-xxxx-xxxx-xxxx-xxxxxx
c:\path\to\your\project>nuget push YourProject.x.x.nupkg

I think that is all to it. Of course there are some other ways as well, like creating spec-file from the dll/exe-file for example, but this is the way I think is most efficient way to do it and will probably be the way I’ll create NuGet packages in the future. Of course it would be nice if you could specify everything in the project so you didn’t have to update the spec-file, but that seems to be something I’ll have to live with.

In a coming post I’ll show an example of how you can use a NuGet package to extend the functionality of the Package Manager Console, that is creating your own PowerShell commands that gets included in the Console.

The Star of MIX11 is NuGet!

NuGet

Last week I had the pleasure to attend the MIX11 conference in Las Vegas. My first thought when I signed up for the conference was that it would be all about WP7 and web development. I think I was wrong. The star of MIX11 was NuGet if you ask me. Almost all the sessions I attended were using NuGet in their demo, and with all right. NuGet is probably the most powerful tool that has come to the .NET development community in a very long time.

What is that makes NuGet so special? I think it is the simplicity to use, the team has really nailed many of the features. Even though it is very easy to use, if you go deeper and start to take advantage of the Package Manager Console and start using the advanced features of PowerShell a whole new world could be opening. I haven’t started to do that myself yet, but I think many of the presentations at MIX11 really showed some the potential, specially the new scaffolding tools that is shipped with MVC 3 update.

Is there anything that I think might be missing in NuGet? Yes, in fact there is. Although I haven’t run in to the issue yet I might think there might be a problem with the dependencies later on. What if you start installing packages from both a local repository and from NuGet gallery and the package exist in both galleries? The spec file doesn’t specify where the package come from, and that is something that I think might be something you would like so you have more control of which packages that are used.

I will try to make a short blog post about how to create your own packages and installing them and others later this week.

AppleScript to download files from channel9

So this started with Scott Guthrie posted a blog post that listed all presentations from mvcConf. Since I want to se all presentations I want an easy way to download them all. I didn’t find a torrent for the downloads, but Jon Galloway posted a PowerShell script to download all files that I could use, but I didn’t feel like booting up into windows so I thought I could learn some AppleScript instead and ended up with the following script after some time:

try
    display dialog "Enter url: " default answer "http://channel9.msdn.com/Series/mvcConf/RSS"
    set feedUrl to text returned of result
    set filter to GetFilterFromUserInput()
    set outputFolder to POSIX path of (choose folder)
    set urls to GetUrlsFromFeedWithFilter(feedUrl, filter)
    if (count of urls) is equal to 0 then
        display dialog "No files that matches the file type, try another file type."
    else
        set numberOfDownloadedFiles to (DownloadFiles(urls, outputFolder) as text)
        display dialog numberOfDownloadedFiles & " file(s) downloaded"
    end if
on error errorMsg number errorNum
    display dialog "Error (" & errorNum & "):" & return & return & errorMsg buttons "Cancel" default button 1 with icon caution
end try
on DownloadFiles(urls, outputFolder)
    set downloadedFiles to 0
    repeat with thisLine in urls
        set fileName to GetFileNameFromUrl(thisLine)
        set filePath to outputFolder & fileName
        set fileCheck to FileExists(filePath)
        if fileCheck then
        else
            set downloadedFiles to downloadedFiles + 1
            do shell script "curl -sS " & thisLine & " > " & filePath
        end if
    end repeat
    return downloadedFiles
end DownloadFiles

on GetFileNameFromUrl(sourceUrl)
    do shell script "echo " & sourceUrl & " | sed -n 's/.*\\/\\(.*\\)$/\\1/p'"
    set fileName to result
    return fileName
end GetFileNameFromUrl

on GetUrlsFromFeedWithFilter(feedUrl, filter)
    do shell script "curl -sS " & feedUrl & " | sed -n 's/" & filter & "/\\1/gp'"
    return paragraphs of result
end GetUrlsFromFeedWithFilter

on GetFilterFromUserInput()
    choose from list {"High Quality WMV", "MP3", "Medium Quality WMV", "High Quality MP4", "MP4"}
    set selectedItem to (first item in result) as text
    if selectedItem is equal to "High Quality WMV" then
        return ".*media\\:content[^>]*url=\"\\([^>]*2MB_ch9\\.wmv\\)\".*"
    end if
    if selectedItem is equal to "MP3" then
        return ".*media\\:content[^>]*url=\"\\([^>]*\\.mp3\\)\".*"
    end if
    if selectedItem is equal to "Medium Quality WMV" then
        return ".*media\\:content[^>]*url=\"\\([^>]*_ch9\\.wmv\\)\".*"
    end if
    if selectedItem is equal to "High Quality MP4" then
        return ".*media\\:content[^>]*url=\"\\([^>]*high_ch9\\.mp4\\)\".*"
    end if
    if selectedItem is equal to "MP4" then
        return ".*media\\:content[^>]*url=\"\\([^>]*low_ch9\\.mp4\\)\".*"
    end if
end GetFilterFromUserInput

on FileExists(filePath)
    try
        set fileExist to POSIX file filePath as alias
        return true
    on error errorMsg number errorNum
        return false
    end try
end FileExists

It is my first AppleScript ever so there are probably several improvements that could be done but it will do the job for you.

I think it will work for basically all feeds from Channel9, but the default one is for mvcConf since that was the goal for me. Some short notes:

  • You specify a feed url, as the default one.
  • Save the script as an application to make it easier to run.
  • You can specify what type you want to download.
  • Everything is filtered using regex so the script work with feeds formatted the same way as the feed for mvcConf and has the same file endings.
  • The script will not overwrite existing files.

I will moste likely put it up on github later on.

Combine and compress scripts and css

First off, this is something that exists in several different flavours but I decided to write a version that I like. The problem that I wanted to solve was this:

  • An easy way to register scripts and css files.
  • Combine and compress files.
  • Group files and set priority.
  • Disable compression so I can switch to debug in production.
  • Change compression engine if you find a better one then the default one.
  • I don’t want to keep two copies for each script; that is, the original and a minified version.

That is the basic problem I want to solve, but in addition to those two points I want the following:

  • Should be done runtime and not during build.
  • The result should be stored in cache so we get a really fast answer after the first request.
  • The cached result should have a dependency to the files which it depends on.
  • Set a version number to the cached result so we can “invalidate” the clients cache.

I’ve probably forgot something but let get to the solution and see what we got. Before we continue you can get the project at github

The helpers

First of we need some kind of extension to the HtmlHelper, yes I targeted ASP.NET MVC first. Before we get to the actual helper class let us see what I want to write in the markup using razor syntax:

@Html.RegisterCss("~/Content/Site.css")
@Html.RegisterScript("~/Scripts/jquery-1.4.4.js", compress: false, ignore: true)
@Html.RegisterScript("~/Scripts/jquery-ui.js", compress: false)
@Html.CreateScriptTags()
@Html.CreateCssTags()

As you can see I want four different extension methods and the purpose should be sort of obvious be let us print them down.

  • Html.RegisterCss – register a css file in the ResourceManager
  • Html.RegisterScript – register a javascript file in the ResourceManager
  • Html.CreateScriptTags – print the html tag(s) for the registered javascript files
  • Html.CreateCssTags – print the html tag(s) for the registered css files

For the two first methods there are four parameters except the file name:

  • resourceGroup – default value is “” and all the files in the same grouped gets combined to one file
  • priority- set this if you want the order to be different from the given order (high value comes first), default value is 0
  • compress – default value is true, set to false if you for some reason don’t want to compress a file
  • ignore – if this is set to true everything else will be ignored and the regular tag will be printed, default value is of course false

The two last has one overload that takes resourceGroup if you only want to print the tags for one resourceGroup. If no resourceGroup is specified all files will be printed. The source code for the helpers.

The ResourceManager

The ResourceManager has most of the logic in the application, maybe to much but that another discussion. As of now it handles the registering of scripts and css files, it print tags depending on the registered files and it also handles the caching of files that should be handled. This part is a little bit hard to explain but I give it a try. The flow is basically this:

  1. First you register your files, lets call them “script1.js” and “script2.js”.
  2. When you use Html.CreateScriptTags this will generate a combined file, virtual file, called something like “js_<hash code of the files>.js” and use this when creating the resulting tag.
  3. When we have the “virtual” file name we store it in the cache, which contains a dictionary per resource type, and map it to the list of original files.
  4. When we get the request of our “virtual” file we can look in the cache after the original files so we know what we are asking for.

I think that is the basic flow and all of those operation are done through the FileResourceManager.

The routing

Why do we need to care about routing you might ask? The answer to this is that the resource we are going to provide will not exist, it will only exist in memory in a “virtual” folder. So we need to route all our request to this “virtual” folder to our custom handler, that I will explain after the routing part. Routing doesn’t need to be that hard. All you need to do is implement the interface IRouteHandler which defines one method, GetHttpHandler, that should return the handler that should be used for the request. The code for the handler.

An example of how you configure your route can be found here.

The resource handling

All the route handler in the previous section does is returning a new FileResourceHandler (click me to see the code) and that is what this secion will be about. The FileResourceHandler implements the interface IHttpHandler which defines the method ProcessRequest. What FileResourceHandler does is:

  1. Get resource type from request; that is, check the extension to see if it is a javascript or css file.
  2. Get the files for the “virtual” files that is requested from the FileResourceManager.
  3. If the resulting list is null or empty set the response status code to NotFound.
  4. Select compressor function based on resource type.
  5. Compress the files and store it in a StringBuilder, also return the files that has been compressed and are in the StringBuilder.
  6. Add response to the cache and also set a file dependency to all the files included in the respones so it automatically clear the cache if any of the files has been changed.
  7. Return the result in the StringBuilder.

Configuration

You can configure everything through the static class SimpleCompressionConfiguration. Here are the properties you can set:

  • Disable – if set to true the compress and combine is disabled.
  • CompressorToUse – set this to an object implementing the. ICompress interface if you don’t want to use the defaul compressor, the default one is Yahoo.Yui.Compressor.
  • FolderForCachedResources – this is where all your “virtual” files will be mapped. Note that you must configure the routing for this folder. The default is “/cache/”.
  • ClientVersionPrefix – change this if you want to force an update of the script on the clients since it will be prepended to the “virtual” files.

I think that is it. I haven’t talked about every file but main part is covered. The project can is still on github and it includes a sample project on MVC 3 with razor. There is probably room for improvement since it is the first draft. One thing I think I should implement pretty soon is the ability to specify cache. The reason for this is that if you have your setup in a distributed environment it is not 100 % guaranteed that you will come back to the same server for the scripts as for the original request. So if there is a possibility to specify cache manager through dependency injection that is up to the user to specify (through a distributed cache).

Generic data mapper for DataReader

Isn’t it boring to write mappers to map data from a db to objects? Wouldn’t it be nice if someone wrote one that is simple to use and works in most cases? I guess so and maybe there are several out there, but I wrote one myself anyway. I know a lot of people think you should use EF, linq to sql, nHibernate or some other ORM… but this is an existing project and I want to improve that as much as I could with the tools at hand without adding new frameworks, I’m just glad we are moving away from DataSets :).

This is sort of an update version of my earlier post Generic mapper for datareader, but I figured I could do it better.

First I want to say that the code is not optimized so if you have a really high volume of data access it might be slow, but for most situations this will most likely do just just fine. The implementation focus only on querying where you get a list of objects out from the query. I will be doing this top down so everything hopefully makes sense why I’m doing them.

Step 1: I wan’t to query a database, and I want to do it in the same way regarding to error handling and logging. So I decided on some query code that look something like this

public class MyDataAccessClass : BaseDataAccess, IMyDataAccessClass
{
    public IList<MyEntity> GetEntities(DateTime date)
    {
        var database = new DataBase(); // 1.
        var dbCommand = database.GetStoredProcCommand("StoredProcName"); // 2.
        database.AddInParameter(dbCommand, "FromDate", DbType.DateTime, date); // 2.
        var result = ExecuteDbCommand<MyEntity>(db, dbCommand, "Property1"); // 3.
        return result;
    }
}

So what do we got here?

  1. We create our database object, could be any one just as the concept is the same.
  2. We create our command, this is the reason this code is not abstracted since the command we want to execute depends on the result we want and we need the database object to create the command. Also, add parameters to command.
  3. We got something that will execute the query for us and return a list of objects of the type we specifies. The last parameter (“Property1″) is used to define properties that I don’t want to map when doing the query.

Step 2 will be to write the ExecuteDbCommand<ReturnType>. So to do that I implemented an abstract base class that all the data access classes can inherit from. It looks something like this:

public abstract class DataAccessBase
{
    protected IList<T> ExecuteDbCommand<T>(Database db, DbCommand command, params string[] excludeProperties) where T : new()
    {
        using (Tracer myTracer = new Tracer(Constants.TraceLog))
        {
            try
            {
                var reader = db.ExecuteReader(command); // 1.
                var mapper = new DataReaderMapper<T>(); // 2.
                var result = mapper.MapListExcludeColumns(reader, excludeProperties); // 3. 
                return result;
            }
            catch(Exception ex)
            {
                // Handle your exception
            }
        }
    }
}

Ok, now it starts to get interesting. As you can see this takes any type T that has a default constructor (by constraint). So what does the code actually do, let me break it down for you:

  1. Create the list where we want to store the objects we read from the reader.
  2. Execute the databse command.
  3. Call our mapper to map the reader to a list of objects.

No we are almost done, what we still have left is to implement our magic DataReaderMapper which will be our third and final step, it looks something like this:

public class DataReaderMapper<T> where T : new()
{
    public IList<T> MapListAll(IDataReader reader)
    {
        return MapListExcludeColumns(reader);
    }

    public IList<T> MapListExcludeColumns(IDataReader reader, params string[] excludeColumns)
    {
        var listOfObjects = new List<T>();
        while (reader.Read())
        {
            listOfObjects.Add(MapRowExclude(reader, excludeColumns));
        }
        return listOfObjects;
    }

    public T MapRowExclude(IDataReader reader, params string[] columns)
    {
        return MapRow(reader, false, columns);
    }

    public T MapRowInclude(IDataReader reader, params string[] columns)
    {
        return MapRow(reader, true, columns);
    }

    public T MapRowAll(IDataReader reader)
    {
        return MapRow(reader, true, null);
    }

    private T MapRow(IDataReader reader, bool includeColumns, params string[] columns)
    {
        T item = new T(); // 1. 
        var properties = GetPropertiesToMap(includeColumns, columns); // 2. 
        foreach (var property in properties)
        {
            int ordinal = reader.GetOrdinal(property.Name); // 3. 
            if(!reader.IsDBNull(ordinal)) // 4.
            {
                // if dbnull the property will get default value, 
                // otherwise try to read the value from reader
                property.SetValue(item, reader[ordinal], null); // 5.
            }
        }
        return item;
    }

    public IEnumerable<System.Reflection.PropertyInfo> GetPropertiesToMap(bool includeColumns, string[] columns)
    {

        var properties = typeof(T).GetProperties().Where(y => 
            (y.PropertyType.Equals(typeof(string)) || 
            y.PropertyType.Equals(typeof(byte[])) ||
            y.PropertyType.IsValueType) && 
            (columns == null || (columns.Contains(y.Name) == includeColumns)));
        return properties;
    }
}

I have removed all the comments to shorten the post :). As you can see there are a bunch of overloads and variations, like including/excluding properties etc. If we start with the MapListExcludeColumns, which is the reason we ended up here. The basic thoughts are to create a list and an item for each read of the reader. When we add an item we call the MapRowExclude method, which calls the private method MapRow… and that is where all the magic is and of course I will walk you through it:

  1. Create the item that we will return.
  2. Get the properties that we are going to map, if you look at the method it calls the method only returns value type properties, strings and byte arrays. That is because I want to keep it simple and assumes we have simple data objects. Also, it only returns those properties we want to have included.
  3. Get the ordinal from the reader by the property name.
  4. We only want to map if the reader actually has a value for that ordinal.
  5. If it is not null set value using the PropertyInfo we have at this point.

Note that as of now it works only by the convention that the column names in the reader is the same as of the properties in the target object. That is something I will fix by adding a mapping concept using a simple dictionary, but that is something I will do later on.

I think this it, that’s very easy to use mapper. As of now I think I am good. I will make a real project of this and it up on github when I get a hang of github :). If you find any errors or have any improvements suggestions please tell.

Disposible WCF client wrapper

Ok, so you have implemented your WCF service and is about to implement your service client. As usual you want your client to be disposed as it should so you start writing something like:

using(var client = new SomeServiceType())
{
    // Do stuff with your client
}  // Can throw exception here

Usually this works perfectly fine, but in the case with WCF this won’t work as expected. The reason for this is that Microsoft is sort of “violating” their own definition that a call to Dispose should never throw an exception, but in case with WCF that is not true. The call to Dispose for the client (which appears when leaving the using block above) might throw an exception when Close is called in the Dispose function due to some communication issues. Why is this so bad you might ask? The problem is if you get an exception inside of your using block, if you get an exception there it would be “swallowed” by the exception caused in the Dispose method. If you want to read about it more you can find some information at the following locations:

One solution I found on the web is presented here, but I don’t like that solution since it is somewhat introducing a new word Use instead of Using that we are used to. So instead of that solution I wrote a generic wrapper that takes the type it is wrapping, creates a static factory that generates clients of that type and exposes the communication channel as a public property. When creating a new instance of the wrapper the factory is not re-created, instead it uses the old one and opens the channel object. The client wrapper implements the IDisposable interface and in the Dispose method the wrapper closes the channel properly and “swallows” the exception that might occur when Abort on the channel is called (which should never occur). The wrapper code is as follows:

/// <summary>
/// Wraps a service client so you can use "using" without worrying of getting
/// your business exception swalloed. Usage:
/// <example>
/// <code>
/// using(var serviceClient = new ServiceClientWrapper&lt;IServiceContract&gt;)
/// {
/// serviceClient.Channel.YourServiceCall(request);
/// }
/// </code>
/// </example>
/// </summary>
/// <typeparam name="ServiceType">The type of the ervice type.</typeparam>
public class ServiceClientWrapper<ServiceType> : IDisposable
{
    private ServiceType _channel;
    /// <summary>
    /// Gets the channel.
    /// </summary>
    /// <value>The channel.</value>
    public ServiceType Channel
    {
        get { return _channel; }
    }

    private static ChannelFactory<ServiceType> _channelFactory;

    /// <summary>
    /// Initializes a new instance of the <see cref="ServiceClientWrapper&lt;ServiceType&gt;"/> class.
    /// As a default the endpoint that is used is the one named after the contracts full name.
    /// </summary>
    public ServiceClientWrapper() : this(typeof(ServiceType).FullName)
    { }

    /// <summary>
    /// Initializes a new instance of the <see cref="ServiceClientWrapper&lt;ServiceType&gt;"/> class.
    /// </summary>
    /// <param name="endpoint">The endpoint.</param>
    public ServiceClientWrapper(string endpoint)
    {
        if (_channelFactory == null)
            _channelFactory = new ChannelFactory<ServiceType>(endpoint);
        _channel = _channelFactory.CreateChannel();
        ((IChannel)_channel).Open();
    }

    /// <summary>
    /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
    /// </summary>
    public void Dispose()
    {
        try
        {
            ((IChannel)_channel).Close();
        }
        catch (CommunicationException e)
        {
            ((IChannel)_channel).Abort();
        }
        catch (TimeoutException e)
        {
            ((IChannel)_channel).Abort();
        }
        catch (Exception e)
        {
            ((IChannel)_channel).Abort();
            // TODO: Insert logging
        }
    }
}

Now when you have your wrapper all you need to do is use the following code:

public class ClientWrapperUsage
{
    public static void main(string[] args)
    {
        using(var clientWrapper = new ServiceClientWrapper<ServiceType>())
        {
            var response = clientWrapper.Channel.ServiceCall();
        }
    }
}

I think the solution is quite ok, but I think we should never have been forced to implement our own wrapper to solve the issue. The code is also availble at github in this gist

Refactor your code – remove those if-else if-else and switch statements

I’m currently working with some legacy code and came across a really long if-else if-else function. We’ve all been down that path writing that type of code. A situation where this is pretty common in .Net, and that is where I stumbled on it this time, is when acting on a some kind of command from a grid view for example. The code that I refactored looked something like this:

public void gridView_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
    string commandName = e.CommandName;
    if(commandName == "command1")
    {
        // A lot of code for command 1
    }
    else if(commandName == "command2")
    {
        // A lot of code for command2
    }
    else if(commandName == "command3")
    {
        // A lot of code for command3
    }
    else if(commandName == "command4")
    {
        // A lot of code for command4
    }
}

Every where were it says “A lot of code for commandx” contained some kind of logic that was pretty hard to understand. So the first step in refactoring this piece of code is actually to learn what those commands are and create separate methods for each method like such:

public void Command1()
{
    // A lot of code for command1
}

public void Command2()
{
    // A lot of code for command2
}
public void Command3()
{
    // A lot of code for command3
}
public void Command4()
{
    // A lot of code for command4
}

The function name must also have a descriptive name and not just Commandx as I have in the example here. Now one might think that we could just change our if-else if-else to a switch and call the commands from the switch. But I don’t think that is enough. The event handler should just handle the event it should NOT be responsible for executing the right command, so what I ended up doing was a dictionary where I mapped the command names to their respective functions and created a function that was responsible for executing the right command given a command string. The final code looked something like:

private Dictionary<string, Action> _commandDictionary;
public Dictionary<string, Action> CommandDictionary
{
    get
    {
        if (_commandDictionary == null)
        {
            _commandDictionary = new Dictionary<string, Action>();
            _commandDictionary.Add("Command1", Command1);
            _commandDictionary.Add("Command2", Command2);
            _commandDictionary.Add("Command3", Command3);
            _commandDictionary.Add("Command4", Command4);
        }
        return _commandDictionary;
    }
}

public void gridView_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
    string commandToExecute = e.CommandName;
    ExecuteCommand(commandToExecute);
}

private void ExecuteCommand(string command)
{
    if (CommandDictionary.ContainsKey(command))
    {
        CommandDictionary[command]();
    }
    else
    {
        throw new ArgumentException("Invalid command: {0}", command);
    }
}

public void Command1()
{
    // A lot of code for command1
}

public void Command2()
{
    // A lot of code for command2
}

public void Command3()
{
    // A lot of code for command3
}

public void Command4()
{
    // A lot of code for command4
}

The resulting code is not necessarily shorter, but every piece of code has it’s own “purpose”. The event handler just extract the command that should be executed, the ExecuteCommand makes the check if the command is valid and calls the responding command and the command functions do the actual work that is requested. Some advantages you get with this solution are that it is much easier to test each function by itself than it is was before and it is much easier to follow what the code actually does.

You could take this one step further, or if you don’t have something like Action that I use here in your language of choice, and create an interface called ICommand that defines an Execute method and wrap all the commands in separate classes that implements that interface. But for now this works fine for me since I only use it in one place and it is not meant to be used anywhere else.

Debugging your Windows Service in Visual Studio

It could be hard to debug your windows services if you play by the book. If you do play by the book you need to install the windows service and then attach a debugger to the process to be able to debug the service, of course you might need to do that in some cases maybe to make sure that the service acts as it should under the account it is running. However, to debug the actual functionality it is always easier to just hit F5 in Visual Studio and start debugging and here is how you do that. First, create a Service project for your reusable code. The first file you should add is a windows service class, CustomServiceBase, that extends the ServiceBase class.

namespace Service
{
    public class CustomServiceBase : ServiceBase
    {
        public void StartService(string[] args)
        {
            OnStart(args);
        }

        public void StopService()
        {
            OnStop();
        }
    }
}

This will be your new ServiceBase class instead of ServiceBase. Basically all it do is adding two methods that is used later on so we don’t have to use reflection to access the OnStart and the OnStop methods. The next file you need to add to your Service is the generic ServiceManager class that will acts as your runner.

namespace Service
{
    public delegate void ServiceManagerHandler(object sender, EventArgs args);

    public class ServiceManager<T> where T : CustomServiceBase, new() 
    {
        public event ServiceManagerHandler ServiceDefaultModeStarting;
        public event ServiceManagerHandler ServiceInteractiveModeStarting;

        public void Run()
        {
            if (!Debugger.IsAttached)
            {
                StartServiceDefault();
            }
            else
            {
                StartServiceInteractive();
            }
        }

        private void StartServiceDefault()
        {
            if (ServiceDefaultModeStarting != null)
                ServiceDefaultModeStarting(this, null);
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] 
                { 
                    new T() 
                };
            ServiceBase.Run(ServicesToRun);
        }

        private void StartServiceInteractive()
        {
            if (ServiceInteractiveModeStarting != null)
                ServiceInteractiveModeStarting(this, null);
            Console.Title = Assembly.GetEntryAssembly().FullName;
            Console.WriteLine(Assembly.GetEntryAssembly().FullName);
            T service = new T();

            Console.WriteLine();
            try
            {
                Console.WriteLine();
                Console.WriteLine("Calling StartService()");
                Console.WriteLine("-----------------------------------------------");

                service.StartService(null);

                Console.WriteLine();
                Console.WriteLine("Service running in foreground, press enter to exit...");
                Console.ReadLine();

                Console.WriteLine("Calling StopService()");
                Console.WriteLine("-----------------------------------------------");

                service.StopService();
            }
            catch (Exception ex)
            {
                throw;
            }
        }
    }
}

This is the most simplest version doesn’t take any arguments when starting the service. It’s straight forward to add that functionality but we don’t need it in the project I am in. So what does the ServiceManager do? It takes a CustomServiceBase type as the generic input, the it checks to see if a debugger is attached or not. What do we achieve with this? If you start it in debug mode in Visual Studio a debugger will be attach and we can take control over the execution, so in that case we call the StartServiceInteractiveMode which calls the StartService method in the CustomServiceBase class and then waits for some input before it calls the StopService method. Now you might ask how I know I have a console available? The answer is I don’t, I’m using my own convention that the ServiceImplementation project will be console application. To use this new simple library you created above your regular ServiceImplementation project will look something like this:

namespace ServiceImplementation
{
    public partial class YourService : CustomServiceBase
    {
        public void OnStart(string[] args)
        {
            // Code to run on start
        }

        public void OnStop()
        {
            // Code to run on stop
        }
    }
}

This is no different compared to a regular service implementation class. The Program class will look something like this

namespace ServiceImplementation
{
    public static void Main()
    {
        var serviceManager = new ServiceManager<ConversionService>();
        serviceManager.ServiceDefaultModeStarting += new ServiceManagerHandler(serviceManager_ServiceDefaultModeStarting);
        serviceManager.ServiceInteractiveModeStarting += new ServiceManagerHandler(serviceManager_ServiceInteractiveModeStarting);
        serviceManager.Run();
    }

    static void serviceManager_ServiceInteractiveModeStarting(object sender, EventArgs args)
    {
        // if you want to do something when the service is starting in interactive/debug mode
    }

    static void serviceManager_ServiceDefaultModeStarting(object sender, EventArgs args)
    {
        // if you want to do something when the service is starting in default mode
    }
}

You don’t have to implement the two event methods if you don’t need to but it could be good in logging purpose.

Note: Remeber that the ServiceImplementation project should be a console application and nothing else.

So that’s basically all you need to make your windows services debuggable unde visual studio. If you have any problem or find it useful let me know.

Certifications, do we need them?

My short answer to this question is no.

There have been a lot of discussions about certifications and the use of them on the web. I have taken several certifications like Sun Certified Java Programmer (SCJP), multiple Microsoft Certified Technology Specialist (MCTS) and Microsoft Certified Technology Professional (MCPD) the last couple of years. So why do I answer “no” to this question? The main reason is that it don’t think they say so much about how good you are at the topic in which you have a certification, all it says is that you have been ambitious and spend some extra hours during your spare time (if you do it the same way as me) to pass the exam. Of course that is not all bad since you have actually taken your spare time to take those exams and that says something about you and your personality. On a personal level I could use a certification as a criteria to compare two people… but that would be after I would look at other criterias as involvement in open source project and such. One thing that I’m pretty sure off is that if a person has more than one certification in one area it starts to mean something, it’s hard to take several exams and not learn something.

The main reason I think those certification exists is from a selling point, if there are more people certified it’s more legit to use that technology since there is more people that “knows” the technology in question. On a company level I also think that the certification is more reasonable since you need several persons that have personal certification to get certified as a company and when the volumes of the number certified increase in a group the likelihood that at least some of them are really good at the topic increases.

So here comes the twist to this post. I don’t think we need the certifications, but I do think it is a perfectly fine way to learn about the topic so I do recommend them. For me the Microsoft certification was the starting point for me to learn about .Net and force myself to start reading about the areas in .Net development I hadn’t touch when I took the later exams, but they didn’t make me an “expert” at .Net. To be an expert you need to spend the extra time to read other areas like object oriented design, design patterns and about the framework that exist in the .Net community, and of course you should also try them out as much as possible.

Summary: Do we need certifications? No, but take them anyway to force yourself to read about topics you haven’t looked at before. Also, they make more sense for companies, but still I don’t think they make all the different.

Convert DataTable to generic list extension

The background to the following post is this question on Stack Overflow and my old blog post about generic list to DataTable. The question on Stack Overflow is basically asking the opposite of what I wrote in my blog post, but doing the opposite is almost the same code so I figured I just write it down and here it is:

public static class DataTableExtensions
{
    public static IList<T> ToList<T>(this DataTable table) where T : new()
    {
        IList<PropertyInfo> properties = typeof(T).GetProperties().ToList();
        IList<T> result = new List<T>();

        foreach (var row in table.Rows)
        {
            var item = CreateItemFromRow<T>((DataRow)row, properties);
            result.Add(item);
        }

        return result;
    }

    private static T CreateItemFromRow<T>(DataRow row, IList<PropertyInfo> properties) where T : new()
    {
        T item = new T();
        foreach (var property in properties)
        {
            property.SetValue(item, row[property.Name], null);
        }
        return item;
    }
}

You could probably add some overload to exclude properties, I would in that case go for the signature static List<T> ToList<T>(this DataTable table, params string[] excludeProperties), but I leave that up to you. You might also need some error handling depending on where the code is used.