Custom master page deployment in SharePoint 2010

Today I am going to show you that how easily you can deploy your custom master page as a SharePoint feature and it automatically change the site default master page when you activate this feature.

For this you need to create new empty SharePoint project.

Add a new item to the project and select module and call is “Module1”.

Once the module is created it contains “element.xml” and “sample.txt” file, rename the “sample.txt” file to “customMaster.master” as shown in below image.

             

Now you can copy code from your custom master page which you want to deploy(If you don’t have your custom code then you can use SharePoint 2010 designer and copy the contents of v4.master and past them in your customMaster.master file in Visual Studio. Make the changes you want to.

Copy the following code and replace your “element.xml” file.

<?xmlversion="1.0" encoding="utf-8"?>
<Elementsxmlns="http://schemas.microsoft.com/sharepoint/">
  <ModuleName="Module1" Url="_catalogs/masterpage">
    <FilePath="Module1\customMaster.master" Url="customMaster.master" />
  </Module>
</Elements>

Now you have to add feature event receiver, so on feature activation this custom master page will be your default master page.

To do this, right click on your feature1 and select “Add event receiver”

Replace the “FeatureActivated” and “featureDeactivating” method with the followings

public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSite site = (SPSite)properties.Feature.Parent;
            SPWeb web = site.RootWeb;
            Uri masterUri = new Uri(web.Url + "/_catalogs/masterpage/custommaster.master");
            web.MasterUrl = masterUri.AbsolutePath;
            web.CustomMasterUrl = masterUri.AbsolutePath;
            web.Update();
        }
 public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPSite site = (SPSite)properties.Feature.Parent;
            SPWeb web = site.RootWeb;
            Uri masterUri = new Uri(web.Url + "/_catalogs/masterpage/v4.master");
            web.MasterUrl = masterUri.AbsolutePath;
            web.CustomMasterUrl = masterUri.AbsolutePath;
            web.Update();
        }

Now deploy the feature, when you will activate the feature it will replace you default master page with “customMaster.master” , and when you deactivatethe feature it will replace  to default master page which is V4.master.

Blogs

See More Articles

Contact us

To begin your digital transformation, get in touch.

We’re pleased to address any inquiries you might have and assist you in selecting the service that best suits your requirements.

Your benefits:
Speak To Us