Custom Application Master Page for WSS 3.0/MOSS 2007/SharePoint 2010 via HttpModule

Some times when you would like the system to use a custom application master pages for all the sites under site collections or subsites and sites , i found implementing and HTTP module would be the best choice (no other choice 🙂 ) esp with WSS 3.0 .

deploy this code as an http module and add and httpmodule entry in the web.config where ever you would like to implement it.
and create a custom master page and name it as CustomApplication.master and place in the master page gallery so the code will automatically pick the master page from there and works great.


using System;
using System.Web;
using System.Web.UI;
using System.IO;
using Microsoft.SharePoint;

namespace ApplicationHttpModule
{
public class ApplicationMasterModule: IHttpModule
{
public void Init(HttpApplication context)
{
context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);
}
void context_PreRequestHandlerExecute(object sender, EventArgs e)
{
Page page = HttpContext.Current.CurrentHandler as Page;
if (page != null)
{
page.PreInit += new EventHandler(page_PreInit);
}
}

void page_PreInit(object sender, EventArgs e)
{

Page page = sender as Page;
if (page != null)
{
// Is there a master page defined?
if (page.MasterPageFile != null)
{
// only change the application.master files as those are the offenders
if (page.MasterPageFile.Contains(“application.master”))
{
SPWeb site = SPContext.Current.Web;
string MasterUrlPath = site.ServerRelativeUrl;
if (!MasterUrlPath.EndsWith(@”/”))
MasterUrlPath += @”/”;
MasterUrlPath += @”_catalogs/masterpage/CustomApplication.master”;

//check custom application master page exists in masterpages folder not.
//If yes apply it otherwise apply sitecollection level custom app. master page
if (site.GetFile(MasterUrlPath).Exists)
{
page.MasterPageFile = MasterUrlPath;
}
else
{
page.MasterPageFile = “/_layouts/ApplicationMasterPages/CustomApplication.master”;
}

}
}
}
}

public void Dispose()
{
}
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *

Bitnami