How to Approximate Application_Start in SharePoint Like a Gentleman

Sometimes, you just need to start something.

application_start_in_sharepoint

In a typical ASP.NET application, if we need to start something when it cranks to life in IIS, we simply add some custom code to the trusty Application_Start handler in our Global.asax file:

public class OmgAwesomeApplication : System.Web.HttpApplication {
    protected void Application_Start() {
        // omg something awesome here
    }
}

In a SharePoint app, however1, there is no Global.asaxfile, and indeed no such trusty method. This is by design, of course–running custom code inside SharePoint means relinquishing some control, especially over shared territory like events in the HttpApplication‘s lifecycle.

Still. Sometimes, you just need to start something.

Good place to start, Init?

So how can we hook into the start of an application in a SharePoint context? Rather than waiting for a leg up from our Visual Studio project template, let’s use the old rusted side door in ASP.NET that takes us straight into the Application Start kitchen.

An HTTP Module is simply code that is configured to run in IIS in response to requests on the server. The IHttpModule interface provides one method named Init. On-label usage dictates that we use this method to subscribe to the given HttpApplication‘s BeginRequest and EndRequest events:

public void Init(HttpApplication application) {
    application.BeginRequest +=
        (new EventHandler(this.Application_BeginRequest));
    application.EndRequest +=
        (new EventHandler(this.Application_EndRequest));
}

Now clear your mind, and forget about subscribing to these events. For our purposes here, we just want to run some code one time (and one time only) when the HttpApplication starts up. And it just so happens that our Init function runs right when the HttpApplication starts up. So:

public abstract class ApplicationStartHandler : IHttpModule {
    protected abstract void OnStart();
    public void Init(HttpApplication application) {
        OnStart();
    }
    public void Dispose() { }
}

Notice that I’ve built this out as an abstract class. This is not just because I am a gentleman. It’s because I want to encapsulate the pattern of running our yet-to-be-written custom code in the Init function. It’s also because I want to name the pattern in a way that makes it readable and understandable. Plus? I’m fancy.

If you don’t already, you’re really going to appreciate this fanciness/gentlemanliness in a few minutes.

Pulling our socks up and moving on, let’s inherit ApplicationStartHandler, and override the OnStart method to do something interesting (like perhaps boot up a ServiceStack host):

public class ServiceStackStarter : ApplicationStartHandler {
    protected override void OnStart() {
        var host = new MyAwesomeAppHost();
        host.Init();
    }
}

One last step before our fanciness is ready for prime time: we must let IIS know that our module exists. We do this by registering it in the Web Application’s web.config file, under configuration/system.webServer/modules.

<add name="ServiceStackStarter" type="Fazzaro.Blog.ServiceStackStarter, Fazzaro.Blog, Version=1.0.0.0, Culture=neutral, PublicKeyToken=544b79730baa4957" />

As you can see, this requires skill in the realm of obtaining the PublicKeyToken of your module’s assembly. Details on this yak-shavery can be found here.

And once that’s in? Cut, print. Golly, was that ever a piece of 1337 SharePoint hax0r cake2.

Um. Hey, why is the server room on fire?

Multithreading, Mutual Exclusion, and the Advantages of Having Been a Gentleman

Yeah. IIS is a web server. And when we inject code into its very guts like this, we have to account for the fact that multiple instances of said code are being run at any given time.

To pull off the fix for our original cavalier implementation, we must add a static flag and a mutex to the ApplicationStartHandler class, using them in combination to ensure that the OnStart method is run once (and only once):

public abstract class ApplicationStartHandler : IHttpModule { 

    private readonly static object _mutex = new object(); 
    private static bool _initialized = false; 

    protected abstract void OnStart(); 

    public void Init(HttpApplication application) { 
        if (!_initialized) 
            lock (_mutex) 
            if (!_initialized) 
                Application_Start(); 
    }

    private void Application_Start() { 
        _initialized = true; 
        OnStart(); 
    }

    public void Dispose() { } 
}

Our OnStart method will now indeed run once and only once when the HttpApplication starts up, with no Global.asax in sight. And because we were gentlemen about the whole abstracting thing, our consuming code (in this case, the ServiceStackStarter class above) need not change in response to this fix.

This isn’t the first time I’ve noted here that standing on the shoulders of giants sometimes means leaving one of your favorite tools down on the ground. The trick is to stop being so shy about asking the giant to hand you a screwdriver.


  1. I’ve really got to stop beginning all of my sentences like this.
  2. Mmm. 1337 SharePoint hax0r cake.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s