In the previous blog here, we looked at how to install apps on a SharePoint site. With SharePoint and Office Dev PnP CSOM, we could also add web parts to Modern Pages, both out of the box (OOB) web parts and custom web parts. For out of box web parts, refer to Chris O’Brien article here , where he has provided steps and also the web part IDs for the OOB webparts which is really helpful.

In this blog, we will look at steps to add a custom web part and set it properties.

For the below code, we will use OfficeDevPnP CSOM library. The high level steps for implementation are below:

  1. Find the page where to add the web part. For creating a modern page programmatically, refer to this link here.
  2. Find if the web part is added to the page, if not then add it using web part ID. We will read the web part ID from a JSON class where we have kept the details of the custom web part
  3. After the web part is added, then set the web part properties using JSON schema of the properties using NewtonSoft.Json.
Note: If the web part app is just installed, then it might take time for 
the web part to be ready for use. 
Hence put a wait state till the web part is loaded for use.

The below code has the steps for adding the web part programmatically using CSOM


private string appJsonInfo;
private AppDeclaration Apps;
// A class to hold JSON converted objects for Apps
private class AppDeclaration
{
public string appName;
public string appId;
public string clientsideId;
}
// Declare and create a Json Object for all Apps
public void DeclareAppIds
{
appJsonInfo = "[{appId: \"xxxxx-xxxx-xxxx-xxxx-xxxxxxxx\", appName: \"testApp\", clientsideId: \"xxxxxx-xxxx-xxxx-xxxx-xxxxxxxx\"}, " +
"{appId: \"xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxx\", appName: \"testApp1\", clientsideId: \"xxxxxx-xxxx-xxxx-xxxxx-xxxxxx\"}, " +
"{appId: \"xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxx\", appName: \"testApp2\", clientsideId: \"xxxxxx-xxxx-xxxx-xxxxx-xxxxxx\"}]";
Apps = JsonConvert.DeserializeObject<List<AppDeclaration>>(appJsonInfo);
}
public void AddWebPartsToPage(string pageName)
{
OfficeDevPnP.Core.AuthenticationManager am = new OfficeDevPnP.Core.AuthenticationManager();
using (var cc = am.GetSharePointOnlineAuthenticatedContextTenant(<site url>, UserName, SecurePass))
{
log.Info("Finding and Adding Webpart to page");
ClientSidePage page = ClientSidePage.Load(cc, pageName);
ClientSideComponent clientSideComponent = null;
AppDeclaration WP = Apps.Find(app => app.appName.Contains(<WPSearchString>));
bool controlPresent = false;
bool done = false;
int count = 0;
do
{
try
{
ClientSideComponent[] clientSideComponents = (ClientSideComponent[])page.AvailableClientSideComponents();
foreach (ClientSideComponent csc in clientSideComponents)
{
if (csc.Id.ToLower().Contains(WP.clientsideId))
{
clientSideComponent = csc;
continue;
}
}
foreach (var control in page.Controls)
{
ClientSideWebPart cpWP = control as ClientSideWebPart;
if (cpWP != null && cpWP.SpControlData.WebPartId.ToString() == WP.clientsideId.ToString())
{
controlPresent = true;
done = true;
}
}
if (!controlPresent)
{
ClientSideWebPart WebPart = new ClientSideWebPart(clientSideComponent);
JToken activeValueToken = true;
// Find the web part configuration string from the web part file or code debugging
string propertyJSONString = String.Format("[{{<WP Configuration string>}}]", <parameters>);
JToken propertyTermToken = JToken.Parse(propertyJSONString);
WebPart.Properties.Add("showOnlyActive", activeValueToken);
CanvasSection section = new CanvasSection(page, CanvasSectionTemplate.OneColumn, page.Sections.Count+1);
page.Sections.Add(section);
page.Save();
page.AddControl(WebPart, section.Columns[0]);
page.Save();
page.Publish();
done = true;
controlPresent = true;
}
}
catch(Exception ex)
{
log.Info("Catched exception while adding Capex web part.. Trying again" + ex.Message);
count++;
}
} while (!done && count <=5);
}
}

Conclusion

The above process could be used to add web part programmatically onto a page and set it’s properties.

Happy Coding !!

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 )

Connecting to %s