Tuesday, November 22, 2011

Programatically change Site and System Master Page in SharePoint 2010

Here is the code to change both Site and System Master Page in SharePoint 2010.

This code has been written in Event Receiver. When the feature is deactivated, automatically, v4.master is applied

 public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSite oSite = (SPSite)properties.Feature.Parent;

            using (SPWeb oWeb = oSite.OpenWeb())
            {
                oWeb.MasterUrl = oWeb.ServerRelativeUrl + "/_catalogs/masterpage/CustomMaster.master";
                oWeb.CustomMasterUrl = oWeb.ServerRelativeUrl + "/_catalogs/masterpage/CustomMaster.master";
                oWeb.Update();
            }
        }


        // Uncomment the method below to handle the event raised before a feature is deactivated.

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPSite oSite = (SPSite)properties.Feature.Parent;

            using (SPWeb oWeb = oSite.OpenWeb())
            {
                oWeb.MasterUrl = oWeb.ServerRelativeUrl + "/_catalogs/masterpage/v4.master";
                oWeb.CustomMasterUrl = oWeb.ServerRelativeUrl + "/_catalogs/masterpage/v4.master";
                oWeb.Update();
            }
        }


Here, oWeb.MasterUrl refers to System Master Page and oWeb.CustomMasterUrl refers to Site Master Page.

Cheers !

6 comments:

  1. Thanks it worked....

    ReplyDelete
  2. hi!,I love your writing so a lot! proportion we be in contact extra approximately your post
    on AOL? I need an expert in this space to unravel my problem.

    Maybe that's you! Looking forward to peer you.
    My web page Online Casino Spiele

    ReplyDelete
  3. Hi, this will work in Sharepoint 2013?

    ReplyDelete
    Replies
    1. This should work in 2013 as well. Only change i would see is to change master page name from v4.master to seattle.master. Didnt try this but let me know if this doesn't work.

      Delete
  4. It worked for me, but it thrown an error while deploying the soulution:
    Error: Error occurred in deployment step 'Activate Features' master page contains illegal character '/'

    Resolved :

    Got resolved by the following code:

    Uri masterUri = new Uri(oWeb.Url + "/_catalogs/masterpage/v4.master");
    oWeb.MasterUrl = masterUri.AbsolutePath;
    oWeb.CustomMasterUrl = masterUri.AbsolutePath;
    oWeb.Update();

    Here i added Uri class to get the absolute path of the custom or default master pages
    It may be help full to others.... :-)

    Thanks dude.

    ReplyDelete