Dec 5, 2008

synchronize master page for application page and site page

The master page of application page is under "_layouts" folder, an example is like MasterPageFile="~/_layouts/application.master". Here is trick to demo how to switch it to the site's master page.

public class SuperBrandingModule : 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.Site.RootWeb;
                    if (site.Properties["CurrentMasterPage"] != null)
                    {
                        string CurrentMasterPage = site.Properties["CurrentMasterPage"];
                        if (!CurrentMasterPage.Equals(string.Empty))
                        {
                            page.MasterPageFile = CurrentMasterPage;
                        }
                    }
                }
            }
        }
    }

    public void Dispose() { }
}