Forum Discussion

StevenDavisBridgeall's avatar
StevenDavisBridgeall
Copper Contributor
Jun 21, 2024

Accessed Denied error when deleting Classic WebPart via code (C# and/or PowerShell)

Hi guys,

 

We have an Azure (C#) Function that is used to build Subsites within a Classic Site Collection, that has been in use for many years. As part of building the sub site, the function manipulates the WebParts held within the default.aspx page, deleting OOTB supplied ones, and adding custom ones.

When we last tried to create a new subsite (on 13th June) the call to delete the WebPart failed with "Access Denied". The run prior to that, on 5th June worked perfectly and there have been no code changes or updates in that period.

The C# Function connects to SharePoint using a ClientId/Secret created via the AppRegNew.aspx mechanism (since the application that the subsite belongs to is an AddOn app and the function is using the same Id/secret combination) with "Site Collection Full Control" permission, and the secret doesn't expire until 11-Aug-2024.


The code in question is:

var homepage = web.GetFileByServerRelativeUrl(web.ServerRelativeUrl + "/default.aspx");

web.Context.Load(homepage);
web.Context.ExecuteQuery();

LimitedWebPartManager wpm = homepage.GetLimitedWebPartManager(PersonalizationScope.Shared);

web.Context.Load(wpm);
web.Context.ExecuteQuery();

IEnumerable<WebPartDefinition> webPartDef = web.Context.LoadQuery(wpm.WebParts.Include(wp => wp.Id, wp => wp.WebPart.Title));

web.Context.ExecuteQuery();

if (webPartDef.Count() > 0)
{
    foreach (var wpd in webPartDef)
    {
    if (wpd.WebPart.Title.ToLower().Equals(name.ToLower())) // If matched, remove.
      wpd.DeleteWebPart();   // <=== This is now generating "Access Denied"
    }
    web.Context.ExecuteQuery();
}

Have tried raising Microsoft tickets, since we have Premier support, but the final one directed me to raise the issue here.
So really wondering what changed? NB: Deleting the web part using PowerShell (PnP.PowerShell module) under my Site Collection Admin credentials also fails.

Regards

Steve

No RepliesBe the first to reply

Resources