Tuesday, January 27, 2009

Programmatically Apply a Master Page and Theme to Specific Managed Path

I recently had a request from a client that required programmatically applying a master page and theme to all new site collections (and sub sites) under a specific managed path.  I created a feature to deploy the master page and one to automatically apply the master page (ensynch.master) and theme (ensynch_theme) on site creation.  This was done by stapling the feature at the farm level to the required site definitions.  Using an IF statement I was able to apply the master page and theme settings to all site collections (and sub sites) created under the managed path.  In the example code below the managed path is called MANAGEDPATH.
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;

namespace Ensynch.SetCustomMaster
{
public class ChangeMaster : Microsoft.SharePoint.SPFeatureReceiver
{
public override void FeatureInstalled
(SPFeatureReceiverProperties properties)
{
}
public override void FeatureUninstalling
(SPFeatureReceiverProperties properties)
{
}
protected string EndOfURL(string url)
{
    return url.Substring(url.LastIndexOf("/") + 1);
}
        public override void FeatureActivated
        (SPFeatureReceiverProperties properties)
        {
            SPWeb CurrentWeb = properties.Feature.Parent as SPWeb;
            if (CurrentWeb.ServerRelativeUrl.StartsWith("/MANAGEDPATH"))
            {
                if (CurrentWeb.IsRootWeb == true)
                {
                    CurrentWeb.MasterUrl = CurrentWeb.ServerRelativeUrl + "/_catalogs/masterpage/ensynch.master";
                    CurrentWeb.CustomMasterUrl = CurrentWeb.ServerRelativeUrl + "/_catalogs/masterpage/ensynch.master";
                }
                else
                {
                    CurrentWeb.MasterUrl = "/MANAGEDPATH/" + EndOfURL(CurrentWeb.Site.Url) + "/_catalogs/masterpage/ensynch.master";
                    CurrentWeb.CustomMasterUrl = "/MANAGEDPATH/" + EndOfURL(CurrentWeb.Site.Url) + "/_catalogs/masterpage/ensynch.master";
                }
                CurrentWeb.ApplyTheme("ENSYNCH_THEME");
                CurrentWeb.Update();
                CurrentWeb.Dispose();
            }
        }
        public override void FeatureDeactivating
        (SPFeatureReceiverProperties properties)
        {
            SPWeb CurrentWeb = properties.Feature.Parent as SPWeb;
            CurrentWeb.MasterUrl = CurrentWeb.ServerRelativeUrl + "/_catalogs/masterpage/default.master";
            CurrentWeb.CustomMasterUrl = CurrentWeb.ServerRelativeUrl + "/_catalogs/masterpage/default.master";
            CurrentWeb.ApplyTheme("none");
            CurrentWeb.Update();
            CurrentWeb.Dispose();
        }
    }
}

Jeff

No comments:

Post a Comment