Get all the WebParts of a SharePoint WebPage using Client Object Model C#

CSOM doesn’t have much to do with WebParts. However, you can modify certain properties like, Title. Below, I have demonstrated a simple way to get the WebParts of the page, Home, from the List, SitePages, of a TeamSite.
ClientContext ctx = new ClientContext(weburl);
ctx.Credentials = new SharePointOnlineCredentials(userName, passWord);

SP.List list = ctx.Web.Lists.GetByTitle("Site Pages");
ctx.Load(list);
CamlQuery cQuery = new CamlQuery();
ListItemCollection ltItemCollection = list.GetItems(cQuery);

ctx.Load(ltItemCollection);
ctx.ExecuteQuery();

ListItem ltItemHome = ltItemCollection.FirstOrDefault(p => p.DisplayName == "Home");

LimitedWebPartManager lwpmShared = ltItemHome.File.GetLimitedWebPartManager(PersonalizationScope.Shared);
LimitedWebPartManager lwpmUser = ltItemHome.File.GetLimitedWebPartManager(PersonalizationScope.User);

WebPartDefinitionCollection webPartDefinitionCollectionShared = lwpmShared.WebParts;
WebPartDefinitionCollection webPartDefinitionCollectionUser = lwpmUser.WebParts;

ctx.Load(webPartDefinitionCollectionShared, w => w.Include(wp => wp.WebPart, wp => wp.Id));
ctx.Load(webPartDefinitionCollectionUser, w => w.Include(wp => wp.WebPart, wp => wp.Id));
ctx.Load(ltItemHome.File);
ctx.Load(ctx.Web, p => p.Url);
ctx.ExecuteQuery();
 
foreach (WebPartDefinition webPartDefinition in webPartDefinitionCollectionShared)
{
    WebPart webPart = webPartDefinition.WebPart;
    ctx.Load(webPart, wp => wp.ZoneIndex, wp => wp.Properties, wp => wp.Title, wp => wp.Subtitle, wp => wp.TitleUrl);
    ctx.ExecuteQuery();
    
    //Once the webPart is loaded, you can do your modification as follows
    webPart.Title = "My New Web Part Title";
    webPartDefinition.SaveWebPartChanges();
    ctx.ExecuteQuery();
}

To get the SchemaXml of a particular WebPart of a SharePoint Page using Web Services, visit the following link,
https://realmpksharepoint.wordpress.com/2014/04/03/get-the-schemaxml-of-a-particular-webpart-of-a-sharepoint-page-using-web-services-c/

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s