Tuesday, 10 September 2013

Applying customer Master Page if it exists

Apply a custom master page to SharePoint web after checking if it exists in the master page gallery.

string masterPage = "_catalogs/masterpage/CustomMasterPage.master";
        string defaultMasterPage = "_catalogs/masterpage/seattle.master";
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            try
            {
                using (SPWeb currentWeb = properties.Feature.Parent as SPWeb)
                {
                    var file = currentWeb.Site.RootWeb.GetFile(masterPage);
                    if (file.Exists)

                    {
                        currentWeb.AllowUnsafeUpdates = true;
                        currentWeb.MasterUrl = currentWeb.Site.RootWeb.ServerRelativeUrl + "/" + masterPage;
                        currentWeb.CustomMasterUrl = currentWeb.Site.RootWeb.ServerRelativeUrl + "/" + masterPage;
                        currentWeb.Update();
                        currentWeb.AllowUnsafeUpdates = false;
                    }
                }
            }
            catch (Exception ex)
            {
               
            }
        }


Setting the master page to default in Feature Deactivation.

public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            try
            {
                using (SPWeb currentWeb = properties.Feature.Parent as SPWeb)
                {
                        currentWeb.AllowUnsafeUpdates = true;
                        currentWeb.MasterUrl = currentWeb.Site.RootWeb.ServerRelativeUrl + "/" + defaultMasterPage;
                        currentWeb.CustomMasterUrl = currentWeb.Site.RootWeb.ServerRelativeUrl + "/" + defaultMasterPage;
                        currentWeb.Update();
                        currentWeb.AllowUnsafeUpdates = false;
                }
            }
            catch (Exception ex)
            {
              
            }
        }
 

No comments:

Post a Comment