Introduction

Web parts are the building blocks of the pages by which you can modify the content, appearance and behavior of pages of a SharePoint site.
In this blog we are going to discuss how to Add, Update and Remove the web part using csom. Here I have used Content Editor Web Part in Wiki page.

Adding the web part in a wikipage

Step 1
First set the credentials by providing the user credentials.
Step 2
Using the client context, load the web.
Step 3
Get the object of the file using server relative url of the wiki page in which you want to add the web part. Example (/sites/Team Site/Site Pages/wikiPage.aspx).
Step 4
Get the 'limitedWebPartManager' by using object file.
Step 5
Design the Xml string for importing the web part as definition of web part in 'limitedWebPartManager'. In xml I have added the Title of web part as 'My Web Part'.
Step 6
Then add the web part order and left zone of the page.
Follow the below code snippet,
  1. using System;
  2. using Microsoft.SharePoint.Client;
  3. using Microsoft.SharePoint.Client.WebParts;
  4. using System.Security;
  5. namespace webpartadd {
  6. class Program {
  7. static void Main(string[] args) {
  8. string userName = "[email protected]";
  9. string password = "PassWord";
  10. string siteUrl = "https://tenantName.sharepoint.com/sites/TeamSite";
  11. SecureString securePassword = new SecureString();
  12. foreach(char c in password) {
  13. securePassword.AppendChar(c);
  14. }
  15. var credentials = new SharePointOnlineCredentials(userName, securePassword);
  16. using(ClientContext clientContext = new ClientContext(siteUrl)) {
  17. try {
  18. clientContext.Credentials = credentials;
  19. clientContext.Load(clientContext.Web);
  20. clientContext.ExecuteQuery();
  21. File oFile = clientContext.Web.GetFileByServerRelativeUrl("/sites/TeamSite/SitePages/wikiPage.aspx");
  22. LimitedWebPartManager limitedWebPartManager = oFile.GetLimitedWebPartManager(PersonalizationScope.Shared);
  23. string xmlWebPart = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<WebPart xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" + " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"" + " xmlns=\"http://schemas.microsoft.com/WebPart/v2\">" + "<Title>My Web Part</Title><FrameType>Default</FrameType>" + "<Description>Use for formatted text, tables, and images.</Description>" + "<IsIncluded>true</IsIncluded><ZoneID></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/images/mscontl.gif</PartImageLarge><IsIncludedFilter />" + "<Assembly>Microsoft.SharePoint, Version=13.0.0.0, Culture=neutral, " + "PublicKeyToken=94de0004b6e3fcc5</Assembly>" + "<TypeName>Microsoft.SharePoint.WebPartPages.ContentEditorWebPart</TypeName>" + "<ContentLink xmlns=\"http://schemas.microsoft.com/WebPart/v2/ContentEditor\" />" + "<Content xmlns=\"http://schemas.microsoft.com/WebPart/v2/ContentEditor\">" + "<![CDATA[This is a first paragraph!<DIV> </DIV>And this is a second paragraph.]]></Content>" + "<PartStorage xmlns=\"http://schemas.microsoft.com/WebPart/v2/ContentEditor\" /></WebPart>";
  24. WebPartDefinition oWebPartDefinition = limitedWebPartManager.ImportWebPart(xmlWebPart);
  25. limitedWebPartManager.AddWebPart(oWebPartDefinition.WebPart, "Left", 1);
  26. clientContext.ExecuteQuery();
  27. } catch (Exception e) {
  28. Console.WriteLine(e);
  29. }
  30. }
  31. Console.WriteLine("Succcesfully added webpart");
  32. }
  33. }
  34. }
In the below image webpat is added in a wikipage,
Add, Update And Remove Web Part Using CSOM

Updating the web part in a wikipage

Step 1
First set the credentials by providing the user credentials.
Step 2
Using the client context, load the web.
Step 3
Get the object of the file using the server relative URL of the wiki page in which you want to add the web part. Example (/sites/team Site/Site Pages/wikiPage.aspx).
Step 4
Get the 'limitedWebPartManager' by using object file.
Step 5
Load the web part using LINQ query expression to return only the title of each Web Part.
Step 6
Check the page having at least one web part for updating.
Step 7
Get the web part definition by using the order value.
Step 8
Change the web part Title then save the web part by calling 'SaveWebPartChanges()'.
Follow the below code snippet,
  1. using System;
  2. using Microsoft.SharePoint.Client;
  3. using Microsoft.SharePoint.Client.WebParts;
  4. using System.Security;
  5. namespace UpdateWebpart {
  6. class Program {
  7. static void Main(string[] args) {
  8. string userName = "[email protected]";
  9. string password = "PassWord";
  10. string siteUrl = "https://tenantName.sharepoint.com/sites/TeamSite";
  11. SecureString securePassword = new SecureString();
  12. foreach(char c in password) {
  13. securePassword.AppendChar(c);
  14. }
  15. var cred = new SharePointOnlineCredentials(userName, securePassword);
  16. using(ClientContext clientContext = new ClientContext(siteUrl)) {
  17. try {
  18. clientContext.Credentials = cred;
  19. clientContext.Load(clientContext.Web);
  20. clientContext.ExecuteQuery();
  21. File oFile = clientContext.Web.GetFileByServerRelativeUrl("/sites/TeamSite/SitePages/wikiPage.aspx");
  22. LimitedWebPartManager limitedWebPartManager = oFile.GetLimitedWebPartManager(PersonalizationScope.Shared);
  23. clientContext.Load(limitedWebPartManager.WebParts, wps => wps.Include(wp => wp.WebPart.Title));
  24. clientContext.ExecuteQuery();
  25. if (limitedWebPartManager.WebParts.Count == 0) {
  26. throw new Exception("No Web Parts on this page.");
  27. }
  28. WebPartDefinition oWebPartDef = limitedWebPartManager.WebParts[0];
  29. WebPart oWebPart = oWebPartDef.WebPart;
  30. oWebPart.Title = "New WebPart Title";
  31. oWebPartDef.SaveWebPartChanges();
  32. clientContext.ExecuteQuery();
  33. } catch (Exception e) {
  34. Console.WriteLine(e);
  35. }
  36. }
  37. Console.WriteLine("Succcesfully updated webpart");
  38. }
  39. }
  40. }
In the below image web pat title is update in a wikipage,
Add, Update And Remove Web Part Using CSOM

Removing the web part from a wikipage

Step 1
First set the credentials by providing the user credentials.
Step 2
Using the client context and, load the web.
Step 3
Get the object of the file using server relative URL of the wiki page in which you want to add the web part. Example (/sites/team Site/Site Pages/wikiPage.aspx).
Step 4
Get the 'limitedWebPartManager' by using object file.
Step 5
Load the web part.
Step 6
Check the page having at least one web part for deleting.
Step 7
Get the web part definition by using the order value.
Step 8
Delete the web part by calling ‘DeleteWebPart ()'.
Follow the below code snippet,
  1. using System;
  2. using Microsoft.SharePoint.Client;
  3. using Microsoft.SharePoint.Client.WebParts;
  4. using System.Security;
  5. namespace RemoveWebpart {
  6. class Program {
  7. static void Main(string[] args) {
  8. string userName = "[email protected]";
  9. string password = "PassWord";
  10. string siteUrl = "https://tenantName.sharepoint.com/sites/TeamSite";
  11. SecureString securePassword = new SecureString();
  12. foreach(char c in password) {
  13. securePassword.AppendChar(c);
  14. }
  15. var cred = new SharePointOnlineCredentials(userName, securePassword);
  16. using(ClientContext clientContext = new ClientContext(siteUrl)) {
  17. try {
  18. clientContext.Credentials = cred;
  19. clientContext.Load(clientContext.Web);
  20. clientContext.ExecuteQuery();
  21. File oFile = clientContext.Web.GetFileByServerRelativeUrl("/sites/TeamSite/SitePages/wikiPage.aspx");
  22. LimitedWebPartManager ltdWebPartManager = oFile.GetLimitedWebPartManager(PersonalizationScope.Shared);
  23. clientContext.Load(ltdWebPartManager.WebParts);
  24. clientContext.ExecuteQuery();
  25. if (ltdWebPartManager.WebParts.Count == 0) {
  26. throw new Exception("No Web Parts to delete.");
  27. }
  28. WebPartDefinition webPartDef = ltdWebPartManager.WebParts[0];
  29. webPartDef.DeleteWebPart();
  30. clientContext.ExecuteQuery();
  31. } catch (Exception e) {
  32. Console.WriteLine(e);
  33. }
  34. Console.WriteLine("Succcesfully deleted webpart");
  35. }
  36. }
  37. }
  38. }
In the below image web pat is deleted from the wikipage,
Add, Update And Remove Web Part Using CSOM