How To Add WebPart To Newly Provisioned Site (Or Subsite) Using CSOM – C# Programmatically

Ahamed Fazil Buhari
 
Senior Developer
March 25, 2019
 
Rate this article
 
Views
2201

Hi,

In the below article we will see how to provision Sub Site and add new Web part into the subsite using CSOM (Console Application). To add the webpart into the page, we need XML of that web part.

We can get XML of the webpart using Export option and save the file as .xml (if we need some links or content to be added in the web part then we can add those content and then export, so it will be available in the xml as well).

I have the Site URL and Client ID values in app.config file. Please refer this article if you are not familiar with Token based authentication

 

I hope the below code with comments explains everything.

using Microsoft.SharePoint.Client;
 using OfficeDevPnP.Core.Entities;
 using System;
 
 namespace SPpals.TemplateProvision
 {
     public static class SPpals
     {
         public static void ProvisionFunction()
         {
             string topRootSite = "https://fazildev.sharepoint.com/sites/sppals/";
             var siteUri = new Uri(topRootSite);
             var realm = TokenHelper.GetRealmFromTargetUrl(siteUri);
             // Client ID and Secrent Key will be taken from App.config file
             var accessToken = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal,
             siteUri.Authority, realm).AccessToken;
             using (var ctx = TokenHelper.GetClientContextWithAccessToken(siteUri.ToString(), accessToken))
             {
                 string subSite = "MyTest";
                 ProvisionSubSite(subSite, ctx);
             }
         }
 
         static void ProvisionSubSite(string subSiteInternalName, ClientContext ctx)
         {
             try
             {
                 // If the site is subsite of a subsite, then use OpenWeb as show below in comment
                 // ctx.Site.OpenWeb("top-subsite-url-name").WebExists(subSite);
                 // Check If Subsite existing
                 Web subSiteWeb = ctx.Site.RootWeb;
                 if (subSiteWeb.WebExists(subSiteInternalName))
                 {
                     Console.WriteLine("Already Exists");
                     subSiteWeb = ctx.Site.RootWeb.GetWeb(subSiteInternalName);
                 }
                 else
                 {
                     WebCreationInformation webCreationInformation = new WebCreationInformation()
                     {
                         // I create TeamSite as subsite - you can find different type of sites here
                         //  https://www.jasjitchopra.com/sharepoint-2013-site-templates-codes-for-powershell/
                         WebTemplate = "STS#0",
                         Title = subSiteInternalName,
                         Url = subSiteInternalName,
                         Language = 1033,
                         UseSamePermissionsAsParentSite = true
                     };
                     subSiteWeb = ctx.Web.Webs.Add(webCreationInformation);                    
                 }
                 ctx.Load(subSiteWeb);
                 ctx.ExecuteQuery();
                 string pageUrl = subSiteWeb.ServerRelativeUrl + "/SitePages/Home.aspx";
                 subSiteWeb.AddWebPartToWebPartPage(pageUrl, AddWebPart());
             }
             catch (Exception ex)
             {
                 Console.WriteLine("Something went wrong. " + ex.Message);
             }
         }
 
         static WebPartEntity AddWebPart()
         {
             // Give file path to the XML which we extracted
             string webPartXml = "C:\buh\WebPart\Content.xml";
             WebPartEntity webpart = new WebPartEntity
             {
                 WebPartXml = System.IO.File.ReadAllText(webPartXml),
                 WebPartZone = "Left"
             };
             return webpart;
         }
     }
 }
 

 

 

Please add the following reference from Nuget package and include TokenHelper.cs file into your project for Token authentication.

 

Happy Coding

Ahamed

Category : Office 365, SharePoint

Author Info

Ahamed Fazil Buhari
 
Senior Developer
 
Rate this article
 
Ahamed is a Senior Developer and he has very good experience in the field of Microsoft Technologies, especially SharePoint, Azure, M365, SPFx, .NET and client side scripting - JavaScript, TypeScript, ...read more
 

Leave a comment