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:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  3. <Module Name="CustomMasterPage" List="116" Url="_catalogs/masterpage">
  4. <File Path="CustomMasterPage\Custom.master" Url="Custom.master" Type="GhostableInLibrary" IgnoreIfAlreadyExists="FALSE" />
  5. </Module>
  6. </Elements>
Event receiver .cs add below code in Feature activated method.
  1. public override void FeatureActivated(SPFeatureReceiverProperties properties)
  2. {
  3. var parentSite = properties.Feature.Parent as SPSite;
  4. if (parentSite != null)
  5. {
  6. SPSecurity.RunWithElevatedPrivileges(delegate
  7. {
  8. using (var site = new SPSite(parentSite.RootWeb.Url))
  9. {
  10. using (var web = site.OpenWeb())
  11. {
  12. web.AllowUnsafeUpdates = true;
  13. string masterPage="CustomMasterPage.master";
  14. var masterUri = new Uri(web.Url + "/_catalogs/masterpage/" + masterPage);
  15. web.MasterUrl = masterUri.AbsolutePath;
  16. web.CustomMasterUrl = masterUri.AbsolutePath;
  17. web.Update();
  18. }
  19. }
  20. });
Feature Deactivate method:
  1. public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
  2. {
  3. var parentSite = properties.Feature.Parent as SPSite;
  4. if (parentSite != null)
  5. {
  6. SPSecurity.RunWithElevatedPrivileges(delegate
  7. {
  8. using (var site = new SPSite(parentSite.RootWeb.Url))
  9. {
  10. using (var web = site.OpenWeb())
  11. {
  12. web.AllowUnsafeUpdates = true;
  13. string masterPage="V4.master";
  14. var masterUri = new Uri(web.Url + "/_catalogs/masterpage/" + masterPage);
  15. web.MasterUrl = masterUri.AbsolutePath;
  16. web.CustomMasterUrl = masterUri.AbsolutePath;
  17. web.Update();
  18. }
  19. }
  20. });
  21. }