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
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