Adding Web Part To A SharePoint Online Page Using PnP Core CSOM Library

Introduction
 
In this article, you will learn how to add a web part to a page using PnP Core CSOM library on SharePoint online sites.
 
The main advantage of using PnP Core libraries is the reduced code to get/set the required information. The required object can be retrieved/created/updated with a very small piece of code, once the client context is set.
 
Prerequisite
  • PnP Core CSOM documentation can be found on the official site here.
  • PnP Core CSOM library packages can be downloaded here.
The code, given below, is being tested, using Visual Studio console application. Once the console application is created, the packages can be installed, using "Install-Package SharePointPnPCoreOnline" command on Package Manager console of Visual Studio. Once installed, the references and packages will be imported to the solution.
 
The references used in the sample are given below.
  • Microsoft.SharePoint.Client
  • OfficeDevPnP.Core 
Connect to SharePoint Online site
 
The Authentication Manager is used to retrieve the client context of the site. To connect to SharePoint Online site, the token, given below is used.
  • GetSharePointOnlineAuthenticatedContextToken 
The parameters required are.
  • SharePoint Online site URL
  • Tenant UserId
  • Tenant Password (or secured string)
Add Web Part To Page
 
The web parts can be added to a page with the help of web part XML. The following steps explain the process in detail.
  • Input the site detail, user details for authentication, page details and web part info.
  • Authenticate and get the client context of the site and then the necessary Web object.
  • Using Web object, add the web part to a page using AddWebPartToWebPartPage method. The required parameters are given below.

    • Page URL
    • Web part entity object which contains web part XML and web part zone.

  • Display the results.
Web Part XML 
 
The web part XML needs to be saved and placed in a local folder for this operation. Each and every web part present on a SharePoint site is defined by XML. The web part XML contains the basic information about the web part. Some of the properties include web part title, description, assembly information, web part type, etc. The web part XML differs from each and every web part type. The web part XML of existing web part can be taken by the following steps.
  • Navigate to respective page
  • Edit the page
  • From the drop down of a web part, click on export  
The following snippet shows the content editor web part XML. Similarly other web part XML can also be identified by above steps.
  1. <?xml version="1.0" encoding="utf-8"?>    
  2. <WebPart xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/WebPart/v2">    
  3.   <Title>Content Editor Custom WebPart</Title>    
  4.   <FrameType>Default</FrameType>    
  5.   <Description>Allows authors to enter rich text content.</Description>    
  6.   <IsIncluded>true</IsIncluded>    
  7.   <ZoneID>Header</ZoneID>    
  8.   <PartOrder>0</PartOrder>    
  9.   <FrameState>Normal</FrameState>    
  10.   <Height />    
  11.   <Width />    
  12.   <AllowRemove>true</AllowRemove>    
  13.   <AllowZoneChange>true</AllowZoneChange>    
  14.   <AllowMinimize>true</AllowMinimize>    
  15.   <AllowConnect>true</AllowConnect>    
  16.   <AllowEdit>true</AllowEdit>    
  17.   <AllowHide>true</AllowHide>    
  18.   <IsVisible>true</IsVisible>    
  19.   <DetailLink />    
  20.   <HelpLink />    
  21.   <HelpMode>Modeless</HelpMode>    
  22.   <Dir>Default</Dir>    
  23.   <PartImageSmall />    
  24.   <MissingAssembly>Cannot import this Web Part.</MissingAssembly>    
  25.   <PartImageLarge>/_layouts/15/images/mscontl.gif</PartImageLarge>    
  26.   <IsIncludedFilter />    
  27.   <Assembly>Microsoft.SharePoint, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c</Assembly>    
  28.   <TypeName>Microsoft.SharePoint.WebPartPages.ContentEditorWebPart</TypeName>    
  29.   <ContentLink xmlns="http://schemas.microsoft.com/WebPart/v2/ContentEditor" />    
  30.   <Content xmlns="http://schemas.microsoft.com/WebPart/v2/ContentEditor" />    
  31.   <PartStorage xmlns="http://schemas.microsoft.com/WebPart/v2/ContentEditor" />    
  32. </WebPart>     
The following code snippet shows you the way to add a web part to a page.
  1. // Input Parameters      
  2. string siteUrl = "https://abc.sharepoint.com";  
  3. string userName = "[email protected]";  
  4. string password = "***";  
  5.   
  6. AuthenticationManager authManager = new AuthenticationManager();  
  7. try  
  8. {  
  9.     using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))  
  10.     {  
  11.         // Input Parameters  
  12.         string webPartXml = @"C:\ContentEditorWP.xml";  
  13.         string pageUrl = "/Pages/TestPage1.aspx";  
  14.   
  15.         WebPartEntity webpart = new WebPartEntity();  
  16.         webpart.WebPartXml = System.IO.File.ReadAllText(webPartXml); // Web Part XML  
  17.         webpart.WebPartZone = "Right"// Web Part Zone  
  18.                       
  19.         // Adds web part  
  20.         clientContext.Site.RootWeb.AddWebPartToWebPartPage(pageUrl, webpart);  
  21.   
  22.         Console.ReadKey();  
  23.     }  
  24. }  
  25. catch (Exception ex)  
  26. {  
  27.     Console.WriteLine("Error Message: " + ex.Message);  
  28.     Console.ReadKey();  
  29. }  
The following snapshot shows the web part added to the right side. The placement of the web part is decided using web part zone property.

Summary
 
Thus you have learned how to add a web part to a page using PnP Core CSOM library. The operation is compatible for SharePoint online site. For on premise site, the authentication mechanism needs to be changed.

Next Recommended Readings