Responsive Ads Here

Wednesday, October 29, 2014

Programmatically applying Master Page to site in SharePoint

I have a requirement to apply custom master page to site on feature activation and in feature deactivation i need to apply the default master page to site.

Please find the below code snippet which will give a complete idea about that.   
 public override void FeatureActivated(SPFeatureReceiverProperties properties)
 {
     if (properties != null)
     {
         SPSite site = properties.Feature.Parent as SPSite;
         string url = "{0}/_catalogs/masterpage/CustomPublishing.master";
         if (site != null)
         {

            try
            {                      
               using (SPWeb web = site.RootWeb)
               {
                   ApplyMasterPage(site, url);                              
               }
             }                     
         }
         catch (Exception ex)
         {                       
            throw ex;
         }
         finally
         {
            if (site != null)
            {
               site.Dispose();
            }
         }
       }
    }
 }
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
 {
    if (properties != null)
    {
       SPSite site = properties.Feature.Parent as SPSite;
       string url = "{0}/_catalogs/masterpage/seattle.master";
       if (site != null)
       {
          try
          {
              ApplyMasterPage(site, url);
          }
          catch (Exception ex)
          {                       
             throw ex;
          }
          finally
          {
             if (site != null)
             {
                            site.Dispose();
             }
          }
       }
    }
 }

private static void ApplyMasterPage(SPSite site, string url)
 {
    try
    {
      using (SPWeb rootWeb = site.RootWeb)
      {
          Uri masterUri = new Uri(string.Format(url, rootWeb.Url));
          rootWeb.CustomMasterUrl = masterUri.AbsolutePath;
          rootWeb.Update();
       }
    }
    catch (Exception)
    {                
        throw;
    }           
 }

Basically i am calling the ApplyMasterPage method both in feature activation and deactivation. I am passing the site and url to the method based upon that it will apply either custom master page or default master page to the site. If we want to apply system master page we need to use MasterUrl instead of CustomMasterUrl.
 foreach(SPWeb child in site.AllWebs) 
    {
        if (child.Url != rootWeb.Url) 
        {
            child.AllProperties["__InheritsCustomMasterUrl"] = true;
            child.AllProperties["__InheritsMasterUrl"] = true;
            child.Update()
        }
        child.Dispose();
    }

No comments:

Post a Comment