Question

I need to apply my custom master page to site collection and subsites while activating the feature,I am using publishing site template(site collection), subsites are using blog and Search center template so I tried

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

            if (site != null)
            {
                SPWeb topLevelSite = site.RootWeb;
                string webAppRelativePath = topLevelSite.ServerRelativeUrl;
                if (!webAppRelativePath.EndsWith("/"))
                {
                    webAppRelativePath += "/";
                }

                // Activate publishing infrastructure
                site.Features.Add(new Guid("f6924d36-2fa8-4f0b-b16d-06b7250180fa"), true);

                foreach (SPWeb web in site.AllWebs)
                {
                    // Activate the publishing feature for all webs.
                    web.Features.Add(new Guid("e9d74a2b-dd09-45aa-a095-9c528aa1de83"), true);
                    web.MasterUrl = webAppRelativePath + "_catalogs/masterpage/Playbook.master";
                    web.CustomMasterUrl = webAppRelativePath + "_catalogs/masterpage/Playbook.master";

                    web.Update();
                }
            }
        }

But I can't, Solution deployed and feature activated sucessfully but no change in master page

Was it helpful?

Solution

Try with web.AllowUnsafeUpdate=true;

following is the working code

public override void FeatureActivated(SPFeatureReceiverProperties properties)  
{    
var parentSite =  properties.Feature.Parent as SPSite;    
if (parentSite != null)    
{    
    SPSecurity.RunWithElevatedPrivileges(delegate    
    {    
        using (var site = new SPSite(parentSite.RootWeb.Url))    
        {    
            using (var web = site.OpenWeb())    
            {    
                web.AllowUnsafeUpdates = true;                          
                string masterPage="CustomMasterPage.master";  
                var masterUri = new Uri(web.Url + "/_catalogs/masterpage/" + masterPage);  
                web.MasterUrl = masterUri.AbsolutePath;    
                web.CustomMasterUrl = masterUri.AbsolutePath;   
                web.Update();    
            }    
        }    
    });  
 }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top