How to apply Master Pages Programmatically by Client Side Object Model – CSOM in SharePoint Office 365

Sathish Nadarajan
 
Solution Architect
September 10, 2016
 
Rate this article
 
Views
7043

A small piece of code snippet to update the master pages of the Site in SharePoint Office 365 – Thought of sharing with the community.

The code is very straight forward and it can be reused as it is.

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;
 
 using Microsoft.SharePoint.Client;
 using System.Security;
 using Microsoft.Online.SharePoint.TenantAdministration;
 using OfficeDevPnP.Core;
 using Microsoft.SharePoint.Client.Publishing;
 
 namespace Console.Office365
 {
     class Program
     {
         static void Main(string[] args)
         {
             ApplyMasterPage();
         }
 
 
         public static void ApplyMasterPage()
         {
             OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager();
 
             string siteUrl = "https://********.sharepoint.com/sites/PublishingSite/";
             string userName = "sathish@******.onmicrosoft.com";
             string password = "*******";
 
             using (var ctx = authMgr.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
             {
                 Web web = ctx.Web;
 
                 ctx.Load(web);
                 ctx.ExecuteQueryRetry();
 
                 web.MasterUrl = web.ServerRelativeUrl + "/_catalogs/masterpage/oslo.master";
                 web.CustomMasterUrl = web.ServerRelativeUrl + "/_catalogs/masterpage/oslo.master";
 
                 web.Update();
 
                 ctx.ExecuteQueryRetry();
             }
         }
     }
     
 }
 

Happy Coding,

Sathish Nadarajan.

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

Leave a comment