23 February 2009

Create a Fake HttpContext for SharePoint

While coding for SharePoint I usualy start by putting code in a console application to create the nessasary functionaly and on a later stage move it over to a browser application. I do this because I find it speeding up the development cycle, because SharePoint deployment cause a bit of overhead. But once in a while I need the HttpContext.Current to be set and I there isn't one in a console app.

To overcome this problem I created my own WorkerRequest class and a helper method that returns a HttpContext to fake a current http context. Both the class and method take a SPWeb as contructor parameter to put the correct SharePoint context into the http context.
public class FakeSharePointWorkerRequest : SimpleWorkerRequest
{
    private readonly string _ServerName;

    public FakeSharePointWorkerRequest(SPWeb web) : base(web.ServerRelativeUrl, web.Site.WebApplication.IisSettings[SPUrlZone.Default].Path.FullName, string.Empty, string.Empty, null)
    {
        _ServerName = web.Site.HostName;
    }

    public override string GetServerName()
    {
        return _ServerName;
    }
}

public static HttpContext GetFakeHttpContextForSharePoint(SPWeb web)
{
    FakeSharePointWorkerRequest workerRequest = new FakeSharePointWorkerRequest(web);
    HttpContext httpContext = new HttpContext(workerRequest);
    httpContext.Items["HttpHandlerSPWeb"] = web;
    httpContext.Items["HttpHandlerSPSite"] = web.Site;
 
    return httpContext;
}
Usage example
using(SPSite site = new SPSite("http://demosite"))
{
    using(SPWeb web = site.OpenWeb())
    {
        bool httpContextIsFake = false;
        if (HttpContext.Current == null)
        {
            // Must be set before using the SPLimitedWebPartManager in a console app
            HttpContext.Current = GetFakeHttpContextForSharePoint(web);
            httpContextIsFake = true;
        }
 
        // Do your own thingies!
        // .....
 
        // Don't forget to reset the current http context
        if (httpContextIsFake)
        {
            HttpContext.Current = null;
        }                     
    }
}

No comments:

Post a Comment