How to set Property Bag values in SharePoint Modern Sites using SharePoint Online .Net CSOM

Posted by

If you consider setting Property Bag values programmatically for Modern SharePoint sites using CSOM, thinking it would be as straight forward as in the Old Classic SharePoint sites, then there is a surprise waiting for you. The code for the setting Property Bag values earlier in old C# CSOM was as follows:

context.Web.AllProperties[“PropertyBagValue1”] = “Property”
context.Web.Update()
context.Web.ExecuteQuery()

The challenge with the above method is that the PropertyBag values are not persisted after saving. So, if you load the context object again, the values are back to initial i.e. without “PropertyBagValue1” property.

The cause of the issue is that Modern Sites have IsNoScript = false, which prevents us to update the Object model through script. Below is the screenshot of the documentation from MS docs – https://docs.microsoft.com/en-us/sharepoint/dev/solution-guidance/modern-experience-customizations-customize-sites

However, it is quite easy to reset using PowerShell, by setting the -DenyAddAndCustomizePages to 0. The same however doesn’t work with the CSOM model. Hence below is the way to get it done.

Set-SPOsite  -DenyAddAndCustomizePages 0

ModernTeamSitesPropertyBag_Limitation

Resolution:

We must use SharePoint PnP Online CSOM for this, so either download it from Nuget or Package Manager in Visual Studio. Later add the below code. Going through the code, we are first initializing Tenant Administration and then accessing the Site Collection using the SiteUrl property. Then use the SetSiteProperties method to set the noScriptSite to false. After that, we can use the above code to set the property bags or using the code below to set values.

After done, then reset the value of the above site back to noScriptSite to true, as you would want to implications on the modern site because of this property as specified in here – https://support.office.com/en-us/article/security-considerations-of-allowing-custom-script-b0420ab0-aff2-4bbc-bf5e-03de9719627c

Advertisements

6 comments

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 )

Google+ photo

You are commenting using your Google+ 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