In CMOS, we can get the web parts from a page using 'Microsoft.SharePoint.Client.WebParts.LimitedWebPartManager' object. We can get all the web parts' information by using 'LimitedWebPartManager' except for the modern/client site pages.
We can get modern page web parts by using OfficeDevPnP.Core. In this blog, I am going to share all codes on how we can get all the web parts information by using OfficeDevPnP.Core.
First of all, we have installed OfficeDevPnP.Core DLLs by using the NuGet package. Go to the Solution Explorer and click on 'Manage Nuget Package'. Then, navigate to the 'Browse' panel and paste 'SharePointPnPCoreOnline' in the search box.
You can see 'SharePointPnPCoreOnline'. Please select that and click on the "Install" button present on the right side of that page. I have added the necessary screenshots for better understanding.
I am using a simple console application to iterate all client-side web parts information.
Please follow the below code.
- using System;
- using OfficeDevPnP.Core;
- using OfficeDevPnP.Core.Pages;
- using Microsoft.SharePoint.Client;
- namespace ConsoleApp4 {
- class Program {
- static void Main(string[] args) {
- Web web = null;
- File file = null;
- ListItem item = null;
- List sitePagesList = null;
- ClientContext ctx = null;
- ClientSideWebPart clientSideWebPart = null;
- string siteUrl = string.Empty;
- string userName = string.Empty;
- string password = string.Empty;
-
- AuthenticationManager authMgr = new AuthenticationManager();
-
- siteUrl = "SiteUrlToScan";
-
- userName = "UserName";
-
- password = "Password";
-
- using(ctx = authMgr.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password)) {
- try {
- web = ctx.Web;
-
- ctx.Load(web);
- ctx.ExecuteQueryRetry();
-
- sitePagesList = web.Lists.GetByTitle("Site Pages");
-
- item = sitePagesList.GetItemById(1);
- ctx.Load(item, I => I.File, I => I.DisplayName);
- ctx.ExecuteQueryRetry();
- file = item.File;
- var page = ClientSidePage.Load(ctx, file.Name);
- var webParts = page.Controls.FindAll(c => c.Type.Name == "ClientSideWebPart");
- if (webParts != null && webParts.Count > 0) {
- foreach(var webpart in webParts) {
- try {
- clientSideWebPart = (ClientSideWebPart) webpart;
- Console.WriteLine(clientSideWebPart.Title);
- } catch (Exception ex) {}
- }
- }
- Console.ReadLine();
- } catch (Exception ex) {}
- }
- }
- }
- }
In my code example, I have three webparts in Home.aspx page as mentioned in the below screen-shots and also after running the above code you can find all three client-side webparts in my result screen-shot.