Set a SharePoint MasterPage thru code

This code is based on SharePoint 2010

Feature receiver code

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            properties.SetMasterPage("/_catalogs/masterpage/custom.master", true, false);
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            properties.SetMasterPage();
        }

Extention Method code

   public static class MasterPageMethods
    {
        public static void SetMasterPage(this SPFeatureReceiverProperties properties)
        {
            properties.SetMasterPage("/_catalogs/masterpage/v4.master");
        }

        public static void SetMasterPage(this SPFeatureReceiverProperties properties, string url)
        {
            properties.SetMasterPage(url, true, true);
        }

        [SPDisposeCheck.SPDisposeCheckIgnore(SPDisposeCheck.SPDisposeCheckID.SPDisposeCheckID_140, "Rootweb should not be disposed")]
        [SPDisposeCheck.SPDisposeCheckIgnore(SPDisposeCheck.SPDisposeCheckID.SPDisposeCheckID_630, "SPFeatureReceiverProperties.Feature.Parent not be disposed")]
        public static void SetMasterPage(this SPFeatureReceiverProperties properties, string url, bool recursive, bool setSystemMasterUrl)
        {
            var curSite = (SPSite)properties.Feature.Parent;
            var curWeb = curSite.RootWeb;
            var masterUri = new Uri(curWeb.Url + url);

            if (recursive)
            {
                foreach (SPWeb innerWeb in curSite.AllWebs)
                {
                    try
                    {
                        innerWeb.CustomMasterUrl = masterUri.AbsolutePath;
                        if (setSystemMasterUrl)
                        {
                            innerWeb.MasterUrl = masterUri.AbsolutePath;
                        }
                        innerWeb.Update();
                    }
                    finally
                    {
                        if (innerWeb != null)
                            innerWeb.Dispose();
                    }
                }
            }
            else
            {
                curWeb.CustomMasterUrl = masterUri.AbsolutePath;
                if (setSystemMasterUrl)
                {
                    curWeb.MasterUrl = masterUri.AbsolutePath;
                }

                curWeb.Update();
            }
        }
    }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s