1
votes

Currently we are using modern team site and trying to add the add the object on the modern team site in SharePoint online

However we observed that we get Access denied error

We tried by setting the site property denyandaddcustomizedpages to false from powershell and it is working fine

However we are not able to get the code which can help us achieve the same using csom client side object model SharePoint online c#

Few articles mention try using pnp nugget but no code was able to find for the same

1
You should post a MCVE. - Sach

1 Answers

6
votes

You can do that using the below sample code.

Do note, executing this code requires SharePoint admin privileges, do make the necessary modifications as per your requirements:

var tenantAdminSiteUrl = "https://tenant-admin.sharepoint.com";
var siteCollectionUrl = "https://tenant.sharepoint.com/sites/Test";

var userName = "[email protected]";
var password = "password";

using (ClientContext clientContext = new ClientContext(tenantAdminSiteUrl))
{
    SecureString securePassword = new SecureString();
    foreach (char c in password.ToCharArray())
    {
        securePassword.AppendChar(c);
    }

    clientContext.AuthenticationMode = ClientAuthenticationMode.Default;
    clientContext.Credentials = new SharePointOnlineCredentials(userName, securePassword);

    var tenant = new Tenant(clientContext);
    var siteProperties = tenant.GetSitePropertiesByUrl(siteCollectionUrl, true);
    tenant.Context.Load(siteProperties);
    tenant.Context.ExecuteQuery();

    siteProperties.DenyAddAndCustomizePages = DenyAddAndCustomizePagesStatus.Disabled;
    var operation = siteProperties.Update();
    tenant.Context.Load(operation, op => op.IsComplete, op => op.PollingInterval);
    tenant.Context.ExecuteQuery();

    // this is necessary, because the setting is not immediately reflected after ExecuteQuery
    while (!operation.IsComplete)
    {
        Thread.Sleep(operation.PollingInterval);
        operation.RefreshLoad();
        if (!operation.IsComplete)
        {
            try
            {
                tenant.Context.ExecuteQuery();
            }
            catch (WebException webEx)
            {
                // catch the error, something went wrong
            }
        }
    }
}