I want to create a SharePoint 2013 app that will add a web part (and an app part) to a page programmatically. I will be using SharePoint online.
I cant seem to find any code that does this.
Is this even possible?
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It only takes a minute to sign up.
Sign up to join this communityThe following example demonstrates how to add Content Search Web Part
using SharePoint 2013/Online CSOM API
Prerequisites: SharePoint Online Client Components SDK
var pageUrl = "/Pages/SearchResults.aspx";
var webPartSchemaXml = @"<?xml version='1.0' encoding='utf-8'?>
<webParts>
<webPart xmlns='http://schemas.microsoft.com/WebPart/v3'>
<metaData>
<type name='Microsoft.Office.Server.Search.WebControls.ContentBySearchWebPart, Microsoft.Office.Server.Search,Version=16.0.0.0,Culture=neutral,PublicKeyToken=71e9bce111e9429c' />
<importErrorMessage>$Resources:core,ImportErrorMessage;</importErrorMessage>
</metaData>
<data>
<properties>
<property name='Title' type='string'>$Resources:Microsoft.Office.Server.Search,CBS_Title;</property>
<property name='Description' type='string'>$Resources:Microsoft.Office.Server.Search,CBS_Description;</property>
<property name='ChromeType'>None</property>
<property name='AllowMinimize' type='bool'>true</property>
<property name='AllowClose' type='bool'>true</property>
<property name='Hidden' type='bool'>false</property>
<property name='DataProviderJSON' type='string'>{'Properties':{'TryCache':true,'Scope':'{Site.URL}'},'PropertiesJson':'{\'TryCache\':true,\'Scope\':\'{Site.URL}\'}'}</property>
</properties>
</data>
</webPart>
</webParts>";
var zoneid = "Header";
var zoneIndex = 1;
using (var ctx = GetContext(webUri, userName, password))
{
var page = ctx.Web.GetFileByServerRelativeUrl(pageUrl);
var wpm= page.GetLimitedWebPartManager(PersonalizationScope.Shared);
var importedWebPart = wpm.ImportWebPart(webPartSchemaXml);
var webPart = wpm.AddWebPart(importedWebPart.WebPart,zoneid, zoneIndex);
ctx.ExecuteQuery();
}
where
public static ClientContext GetContext(Uri webUri, string userName, string password)
{
var securePassword = new SecureString();
foreach (var ch in password) securePassword.AppendChar(ch);
return new ClientContext(webUri) { Credentials = new SharePointOnlineCredentials(userName, securePassword) };
}