Steps
OPen your visual studio and add a Event receiver class under the features tab.
And Replace the below code in Visual studio.
Create a sharepoint project. Add a Module to it. I named it as "MasterModule". By default the module will be created with 2 files, Elemnts.xml and Sample.txt.
You can add / create a Custom Masterpage file as per your requirment. For my purpose, i am trying to reuse the existing V4.Master.
Elements XML replace the below code:
- <?xml version="1.0" encoding="utf-8"?>
- <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
- <Module Name="CustomMasterPage" List="116" Url="_catalogs/masterpage">
- <File Path="CustomMasterPage\Custom.master" Url="Custom.master" Type="GhostableInLibrary" IgnoreIfAlreadyExists="FALSE" />
- </Module>
- </Elements>
Event receiver .cs add below code in Feature activated method.
- 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();
-
- }
-
- }
-
- });
Feature Deactivate method:
- public override void FeatureDeactivating(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="V4.master";
- var masterUri = new Uri(web.Url + "/_catalogs/masterpage/" + masterPage);
-
-
-
- web.MasterUrl = masterUri.AbsolutePath;
-
- web.CustomMasterUrl = masterUri.AbsolutePath;
-
- web.Update();
-
- }
-
- }
-
- });
-
- }