Monday, October 15, 2007

Automatically applying a master page upon activating it as a feature

Today, I was facing the problem of making all My Sites use the same master page. I figured this would be possible through feature stapling, by providing the master page to every newly created My Site. The problem here was that it did copy the master page to the master page gallery, but it did not selected it yet. To do this, I found a great solution thanks to Paul Papanek Stork.

If you want the complete explenation, you can read it all through on his blog. The key I needed was the following bit of code which will fire when activating or deactivating the feature:

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;

namespace CustomMaster
{
public class ChangeMaster:Microsoft.SharePoint.SPFeatureReceiver
{
public override void FeatureInstalled (SPFeatureReceiverProperties properties)
{
}

public override void FeatureUninstalling (SPFeatureReceiverProperties properties)
{
}

public override void FeatureActivated (SPFeatureReceiverProperties properties)
{
SPWeb CurrentWeb = properties.Feature.Parent as SPWeb;
CurrentWeb.MasterUrl = "/_catalogs/masterpage/MyDefault.master";
CurrentWeb.CustomMasterUrl = "/_catalogs/masterpage/custom.master";
CurrentWeb.Update();
}

public override void FeatureDeactivating (SPFeatureReceiverProperties properties)
{
SPWeb CurrentWeb = properties.Feature.Parent as SPWeb;
CurrentWeb.MasterUrl = "/_catalogs/masterpage/default.master";
CurrentWeb.CustomMasterUrl = "/_catalogs/masterpage/default.master";
CurrentWeb.Update();
}
}
}

Just build the feature as Paul describes it, include your own custom master page in the solution and then write a stapling feature that binds this master page feature to the "SPSITE#0" template. Every new My Site will now automatically use your custom master page. Of course, this will also work for every other site template and if you also want the whole portal to automatically use this master page, then use the "GLOBAL" template when stapling your feature.

2 comments:

Paul Papanek Stork said...

Actually, this won't work as a "stapled" feature due to timing issues. If you want to use it as a "stapled"feature you will need to split the event handler and the module into two seperate features and adjust the sequence number high enough to make sure the .master exists before trying to use it.

Tom said...

Thanks for adding that Paul! I didn't face this problem because I activate it by hand the first time, to make sure that the files get provisioned and exist for future use. I only copy the master page file to the rootweb and then link to that master page.