7

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?

6

The 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) };
}
  • 2
    im getting the following exception "Value does not fall within the expected range." – Dan Hastings Sep 17 '15 at 11:28
  • Same issue m getting – Savan Gupta Feb 23 '17 at 14:01
  • use this- var pageUrl = "/sites/your site name/Pages/SearchResults.aspx"; this issue will get resolved. – Savan Gupta Feb 23 '17 at 14:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.