Monday 24 January 2011

Programmatically Set Master Page of Publishing Sites

Case
SharePoint Standard has a nice feature that allows configurating the Master Page on a Site Collection Level. This feature presents itself when you enabled the ‘SharePoint Server Publishing Infrastructure’-feature, found in the Site Collection Features.

Now you can use the ‘Site Master Page Settings’ (/_Layouts/ChangeSiteMasterPage.aspx) to set the Site Master Page and System Master Page.

Problem
But what does a Site and System Master Page mean? And how do you set these properties programmatically?


Solution

Site Master Page
This is the master page that is being used by publishing pages. This means that you use an other masterpage for views, etc.

System Master Page
This is the master page that is being used by system pages like settings.aspx, Forms and view pages like the view of document library pages.

The code
[Guid("00000000-0000-0000-0000-000000000000")] // Add Guid here
public class
StylingEventReceiver : SPFeatureReceiver
{
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
if (properties != null
&& properties.Feature != null
&& properties.Feature.Parent != null
&& properties.Feature.Parent.GetType() == typeof(SPSite))
{
SPSite site = (SPSite)properties.Feature.Parent;

using (SPWeb rootWeb = site.RootWeb)
{
rootWeb.AllowUnsafeUpdates = true;
rootWeb.MasterUrl = "/_catalogs/masterpage/v4.customer.master";
rootWeb.CustomMasterUrl = "/_catalogs/masterpage/V4.customer.master";
rootWeb.Update();
rootWeb.AllowUnsafeUpdates = false;
}
}
}

public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
if (properties != null
&& properties.Feature != null
&& properties.Feature.Parent != null
&& properties.Feature.Parent.GetType() == typeof(SPSite))
{
SPSite site = (SPSite)properties.Feature.Parent;

using (SPWeb rootWeb = site.RootWeb)
{
rootWeb.AllowUnsafeUpdates = true;
rootWeb.MasterUrl = "/_catalogs/masterpage/v4.master";
rootWeb.CustomMasterUrl = "/_catalogs/masterpage/v4.master";
rootWeb.Update();
rootWeb.AllowUnsafeUpdates = false;
}
}
}
}

No comments:

Post a Comment