Donnerstag, 26. Juli 2012

How to deploy custom Masterpage by Code

In our current project we had the advice to deploy a masterpage by a feature.

While deploying the new masterpage to the masterpage-gallery was quite simple (and documented), activating the masterpage for the site(s) was not that straightforward. Most instructions one can find on the web are dealing with that by iterating through all webs and setting the masterpage one by one.

But there is a more simple solution to deal with that, at least when then publishing-feature is activated for the site (what is usually the case if one want to be able to change the masterpage).

Just add below code to the corresponding action of the feature receiver (in my case, the feature-receiver is targeting a Web, but it should also work for feature-receiver targeting the site, then you have to use the RootWeb of the site for the below code)

private const string defaultMasterUrl = "~/_catalogs/masterpage/v4.master";
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPWeb web = properties.Feature.Parent as SPWeb;

            if (web != null && PublishingWeb.IsPublishingWeb(web))
            {
                PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(web);
                publishingWeb.CustomMasterUrl.SetValue(customizedMasterUrl, true);
                publishingWeb.MasterUrl.SetValue(customizedMasterUrl, true);
                publishingWeb.AlternateCssUrl.SetValue(CustomCssUrl, true);
                publishingWeb.Update();
            }
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPWeb web = properties.Feature.Parent as SPWeb;
            
                 if (web != null && PublishingWeb.IsPublishingWeb(web))
                {
                    PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(web);
                    publishingWeb.CustomMasterUrl.SetValue(defaultMasterUrl, true);
                    publishingWeb.MasterUrl.SetValue(defaultMasterUrl, true);
                    publishingWeb.AlternateCssUrl.SetValue("", true);
                    publishingWeb.Update();
                }
        }
 You don´t have to set all the properties. Usually you just have to set the CustomMasterUrl-property, as the MasterUrl-Property is only used for non-publishing-pages. I just did it to make sure the masterpage is set. Also setting the AlternateCssUrl is optional. The only thing to reminde with the AlternateCssUrl is that the default-Value is an empty string (not a real url as with the masterpage). So if you want to set the CSS-Class back to the default one, set this propety to "". If you want to switch back to the default Masterpage, you have to set the url stated above.

Keine Kommentare:

Kommentar veröffentlichen