harbar.net component based software & platform hygiene

Simple example of why Microsoft.Web.Administration rocks

Print | posted on Wednesday, October 29, 2008 8:28 PM

I've had a bunch of requests to start talking more about IIS7 development and whilst I've covered some examples of this previously in my SharePoint and Windows 2008 presentations I thought I'd start by providing a very simple example from APM. This is also to answer (bizarrely) the same question from two readers of this blog.

This example shows how to retrieve a list of Application Pools on the box. You'd think this would be straightforward and efficient right? and easy to do in managed code without any nastiness? right? :) wrong. On IIS6 this is what you need to do:

// enumerates App Pools and properties (using legacy IIS6 metabase)
private static AppPools GetAppPoolsIIS6()
{
    AppPools ret = new AppPools();
    try
    {
        using (DirectoryEntry appPools = new DirectoryEntry(_metabasePath))
        {
            foreach (DirectoryEntry ap in appPools.Children)
            {
                AppPool item = new AppPool();
                item.Name = ap.Name;
                item.Status = GetAppPoolState((int)ap.Properties["AppPoolState"].Value);
                item.Pids = GetProcessIDs(ap.Name);
                ap.Dispose();
                ret.Add(item);
            }
        }
    }
    catch (Exception ex)
    {
        ret = null;
        throw ex;
    }
    return ret;
}

Of course there is some other stuff in here for my specific requirements in APM - I have a custom class to wrap the other information on the app pools I use later on, so ignore that stuff.

So this is calling System.DirectoryServices (which is a managed code wrapper for ADSI - which is a nasty wrapper for LDAP) to query the metabase, then I have to iterate through the DirectoryEntry collection, which is completely ignorant of type - note the disgusting literals necessary. It's basically horrible code and not just because I wrote it. It's the definition of platform hygiene issues :)

Here's how to do the same thing using Microsoft.Web.Administration:

// enumerates App Pools (using Microsoft.Web.Administration)
private static ArrayList GetAppPoolNamesIIS7()
{
    ArrayList ret = new ArrayList();
    try
    {
        using (ServerManager serverManager = new ServerManager())
        {
            foreach (ApplicationPool ap in serverManager.ApplicationPools)
            {
                ret.Add(ap.Name);
            }
        }
    }
    catch (Exception ex)
    {
        ret = null;
        throw ex;
    }
    return ret;
}

I think you get the point... No horrible wrapped wrappers for native libraries, no chances of any type foul ups. Clean, simple and fast - just how it should be.

Of course I realise I need to dust off my HTML skillz and sort out some code formatting on this here blog, but right now I can't be bothered!