How to Add WebPart to a Page in SharePoint Office 365 Programmatically using C# Client Side Object Model (CSOM)


Sathish Nadarajan
SharePoint MVP
Published On :   04 Apr 2017
Visit Count
Today :  7    Total :   1344
Plan, Migrate, Secure, Report
SharePoint & Office 365 Tool. Simple & Easy to Use. 15-Day Trial!

SharePoint Office 365 Tool
Simple & Powerful Tool for Migration, Security & Reporting. Free Trial


Sometime back in an article, we saw how to create pages programmatically in SharePoint Office 365. Now, as an extend, after creating the Page, we need to Add WebParts to the pages. That can be either the OOB webpart, or the custom webpart. Let us see, how to create them step by step. In the below sample, let us see how to Add a Content Editor Webpart to the Page Programmatically.

1. In our Solution Add a Folder.

clip_image002

2. Add the below XML under the Folder WebParts.

 <?xml version="1.0" encoding="utf-8"?>
 <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">
   <Title>CSOM Content Editor</Title>
   <FrameType>None</FrameType>
   <Description>Allows authors to enter rich text content.</Description>
   <IsIncluded>true</IsIncluded>
   <ZoneID>Header</ZoneID>
   <PartOrder>0</PartOrder>
   <FrameState>Normal</FrameState>
   <Height />
   <Width />
   <AllowRemove>true</AllowRemove>
   <AllowZoneChange>true</AllowZoneChange>
   <AllowMinimize>true</AllowMinimize>
   <AllowConnect>true</AllowConnect>
   <AllowEdit>true</AllowEdit>
   <AllowHide>true</AllowHide>
   <IsVisible>true</IsVisible>
   <DetailLink />
   <HelpLink />
   <HelpMode>Modeless</HelpMode>
   <Dir>Default</Dir>
   <PartImageSmall />
   <MissingAssembly>Cannot import this Web Part.</MissingAssembly>
   <PartImageLarge>/_layouts/15/images/mscontl.gif</PartImageLarge>
   <IsIncludedFilter />
   <Assembly>Microsoft.SharePoint, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c</Assembly>
   <TypeName>Microsoft.SharePoint.WebPartPages.ContentEditorWebPart</TypeName>
   <ContentLink xmlns="http://schemas.microsoft.com/WebPart/v2/ContentEditor"></ContentLink>>
   <Content xmlns="http://schemas.microsoft.com/WebPart/v2/ContentEditor">
     <![CDATA[
    <div id='MyDiv'> Test WebPart
   </div>
   <script src='https://sppalsmvp.sharepoint.com/sites/AssetSiteCollection/SiteAssets/JS/MyJS.js'></script>
     
   
 ]]>
   </Content>
   <PartStorage xmlns="http://schemas.microsoft.com/WebPart/v2/ContentEditor" />
 </WebPart>
 

3. The solution will looks like below.

clip_image004

4. Select the XML and Click on Properties.

clip_image006

5. Make the Build Action as Embedded Resource.

clip_image008

6. Now, let us come back to our Method.

 namespace Console.Office365
 {
     using Microsoft.SharePoint.Client;
     using Microsoft.SharePoint.Client.Taxonomy;
     using Newtonsoft.Json.Linq;
     using OfficeDevPnP.Core.Entities;
     using System;
     using System.Collections.Generic;
     using System.IO;
     using System.Linq;
     using System.Reflection;
     using System.Threading.Tasks;
 
     class Program
     {
         static void Main(string[] args)
         {
             AddWebParts();
            
         }
 
         public static void AddWebParts()
         {
             OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager();
 
             string siteUrl = "https://******.sharepoint.com/sites/communitysite";
             string userName = "Sathish@*********.onmicrosoft.com";
             string password = "*************";
 
 
             using (var clientContext = authMgr.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
             {
                 Web web = clientContext.Web;
                 clientContext.Load(web);
                 clientContext.Load(web.AllProperties);
                 clientContext.ExecuteQueryRetry();
 
                 WebPartEntity myWebPart = new WebPartEntity();
 
                 myWebPart = new WebPartEntity { WebPartXml = MyWebPart_O365_WebPartSchemaXML };
 
                 myWebPart.WebPartTitle = "My WebPart";
                 myWebPart.WebPartIndex = 2;
 
                 clientContext.Web.AddWebPartToWikiPage("/sites/CommunitySite/SitePages/WikiPage1.aspx", myWebPart, 1, 1, false);
 
                 clientContext.ExecuteQuery();
             }
         }
 
         private static string myWebPart_O365_WebPartSchemaXML = string.Empty;
         public static string MyWebPart_O365_WebPartSchemaXML
         {
             get
             {
                 if (string.IsNullOrEmpty(myWebPart_O365_WebPartSchemaXML))
                 {
                     using (var stream = Assembly.GetAssembly(typeof(Program)).GetManifestResourceStream("Console.Office365.WebPart.MyWebPart.WebPartSchema.xml"))
                     {
                         using (var reader = new StreamReader(stream))
                         {
                             myWebPart_O365_WebPartSchemaXML = reader.ReadToEnd();
                         }
                     }
                 }
 
                 return myWebPart_O365_WebPartSchemaXML;
             }
         }
     }
 }
 

7. Now, after executing this code, let us come back to the screen and refresh.

8. We should be able to see the Content Editor Webpart on the page.

clip_image010

Happy Coding,

Sathish Nadarajan.

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

Migratiin Tools for SharePoint