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


Sathish Nadarajan
SharePoint MVP
Published On :   10 Sep 2016
Visit Count
Today :  5    Total :   4449
Plan, Migrate, Secure, Report
SharePoint & Office 365 Tool. Simple & Easy to Use. 15-Day Trial!

Sharegate: Kick-Ass Tool
Think Your SharePoint & Office 365 Are Secure ? Find Out Now!


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.

SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Categories

KWizCom Forms App