Friday, September 30, 2011

Master Page Feature Receiver

If you have a visual studio 2010 project to deploy a master page and you want it applied during feature activation and unapplied when the feature is deactivated, use a feature receiver.  Visual Studio templates for SharePoint 2010 give you the ability to add a “Feature Receiver” which allows you to add some custom code to act on a feature at various phases of activation (for the master page, we only care about the “FeatureActivated” event and the “FeatureDeactivating” event).

To add the feature receiver, from your Visual Studio Project’s Solution Explorer, right click on your feature name and click Add Event Receiver. This automatically opens the receiver in the code window to edit. Replace the “FeatureActivated” and the “FeatureDeactivating” events with code in the following format (this code is for deploying to the web scope – you need to use the SPSite object if deploying to the Site scope instead of the SPWeb object).

        // Uncomment the method below to handle the event raised after a feature has been activated.
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
SPWeb currentWeb = properties.Feature.Parent as SPWeb;
Uri masterURI = new Uri(currentWeb.Url + "/_catalogs/masterpage/custom_v4.master");
currentWeb.MasterUrl = masterURI.AbsolutePath;
currentWeb.CustomMasterUrl = masterURI.AbsolutePath;
currentWeb.Update();
}

// Uncomment the method below to handle the event raised before a feature is deactivated.
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
SPWeb currentWeb = properties.Feature.Parent as SPWeb;
Uri masterURI = new Uri(currentWeb.Url + "/_catalogs/masterpage/v4.master");
currentWeb.MasterUrl = masterURI.AbsolutePath;
currentWeb.CustomMasterUrl = masterURI.AbsolutePath;
currentWeb.Update();
}



The above code sets the Master Page to your custom master page when the feature is activated and sets it back to the default master page when it is deactivated.



You should now have all that you need for deploying your custom brand files to your portal sites.

No comments:

Post a Comment