Wednesday, January 7, 2015

Enable site publishing feature and apply master page on SharePoint sub sites including Office 365

In this blog I will go over how to create a sandboxed event receiver which will activate the "Publishing Feature" and inherit master page from parent. (Thanks to Anvesh Kunati and Alex Mayer)

This sandboxed solution will work on SharePoint 2013 and SharePoint Online/365

Steps

1. Fire up a visual studio, if you are using VS 2012 then you may have to download Office 365 Tools for VS 2012. Create a new SharePoint 2013 projects
2. Name the solution accordingly
3. Point to the SharePoint Site(has to be a local site)later on we can copy this WSP to SharePoint Online.
4. Click on the validate and choose "Sandbox Solution" as the option
5. On the VS Project right click on the solution and add a new item choose "Event Receiver" 



6. Name it accordingly because changing it later can become frustrating.
7. From the popup choose Web Events and choose A Site was provisioned

8. In the event receiver code add the following code within public override void WebProvisioned(SPWebEventProperties properties)

 base.WebProvisioned(properties);
            SPWeb web = properties.Web;

            web.AllowUnsafeUpdates = true;
            //activating Publishing feature. If you need any other features to be activated the put those GUID's
            web.Features.Add(new Guid("{94c94ca6-b32f-4da9-a9e3-1f3d343d7ecb}"), true);
            web.Update();
            // add a description toshow that its running/to check if this worked
            // web.Description = "Feature activated log";
            //   web.Update();



            SPWeb rootWeb = web.Site.RootWeb;

            //Inherit the master and custom master page from root site
            web.MasterUrl = rootWeb.MasterUrl;
            web.CustomMasterUrl = rootWeb.CustomMasterUrl;

            //Set navigation

            web.Navigation.UseShared = true;

            web.Update();

            web.AllowUnsafeUpdates = false;

            web.Dispose();
            rootWeb.Dispose();

9. Compile/Build and deploy to the local site. In the properties make sure it is selected as sandbox solution.
10. Go to the site features and activate this new feature
11. This is a reusable solution and the WSP can be uploaded to any site collection or Office 365 SharePoint sites.. Just download the WSP from the local SharePoint site solution gallery and upload to any new site collection.

Alternatively you can also get the latest WSP by right clicking the VS solution and opening the solution in "file explorer", bin folder Debug/Release folder









No comments:

Post a Comment