Tuesday, January 25, 2011

Recursively set SharePoint MasterPages and CSS

Here is a quick sample of how to set master pages and CSS recursively and make sure that they are inherited from the parent site. This would be used within a SharePoint project’s FeatureEventReceiver class.

using System;
using System.Runtime.InteropServices;
using Microsoft.SharePoint;
namespace Acme.Intranet.Ui.Features.Feature1
{
[Guid("0a7b9817-012b-4210-b4b9-a27913eb9598")]
public class Feature1EventReceiver : SPFeatureReceiver
{
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
using (SPSite site = (SPSite)properties.Feature.Parent)
{
using (SPWeb web = site.RootWeb)
{
string masterPageUrl = new Uri(web.Url + "/_catalogs/masterpage/Custom.master").AbsolutePath;
web.MasterUrl = masterPageUrl;
web.CustomMasterUrl = masterPageUrl;
web.Update();
foreach (SPWeb childWeb in web.Webs)
{
SetMasterPagesAndCss(site.Url, childWeb.ServerRelativeUrl, masterPageUrl, true);
}
}
}
}

public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
using (SPSite site = (SPSite)properties.Feature.Parent)
{
using (SPWeb web = site.RootWeb)
{
string masterPageUrl = new Uri(web.Url + "/_catalogs/masterpage/v4.master").AbsolutePath;
web.MasterUrl = masterPageUrl;
web.CustomMasterUrl = masterPageUrl;
web.Update();
foreach (SPWeb childWeb in web.Webs)
{
SetMasterPagesAndCss(site.Url, childWeb.ServerRelativeUrl, masterPageUrl, false);
}
}
}
}

public void SetMasterPagesAndCss(string siteUrl, string webUrl, string masterPageUrl, bool inheritsMasterAndCss)
{
string boolVal = "False";
if (inheritsMasterAndCss)
{
boolVal = "True";
}
using (SPSite site = new SPSite(siteUrl))
{
using (SPWeb web = site.OpenWeb(webUrl))
{
web.Navigation.UseShared = true;
web.MasterUrl = masterPageUrl;
web.AllProperties["__InheritsMasterUrl"] = boolVal;
web.CustomMasterUrl = masterPageUrl;
web.AllProperties["__InheritsCustomMasterUrl"] = boolVal;
web.AlternateCssUrl = web.ParentWeb.AlternateCssUrl;
web.AllProperties["__InheritsAlternateCssUrl"] = boolVal;
web.Update();
foreach (SPWeb childWeb in web.Webs)
{
SetMasterPagesAndCss(siteUrl, childWeb.ServerRelativeUrl, masterPageUrl, inheritsMasterAndCss);
}
}
}
}
}
}

2 comments: