Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change permission level for groups programmatically in SharePoint 2010?

I want to loop through all the sites in a site collection and change the permission for a certain site.

My code is:

        SPSite oSiteCollection = SPContext.Current.Site;
        SPWebCollection collWebsite = oSiteCollection.AllWebs;
        foreach (SPWeb web in collWebsite)
        {
            web.AllowUnsafeUpdates = true;

            if (web.Name == "SiteName")
            {
                web.BreakRoleInheritance(true);

                string[] groups = new string[2] { "Group1", "Group2" };

                foreach (string item in groups)
                {
                    SPGroup removeGroup = web.SiteGroups[item];
                    web.RoleAssignments.Remove(removeGroup);

                    SPGroup addGroup = web.SiteGroups[item];
                    SPRoleDefinition roleDefinition = web.RoleDefinitions["Read"];
                    SPRoleAssignment roleAssignment = new SPRoleAssignment(addGroup);
                    roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
                    web.RoleAssignments.Add(roleAssignment);
                }
            }

        }

but it gives me an error

Error changing permissions, details: There are uncommitted changes on the SPWeb object, call SPWeb.Update() to commit the changes before calling this method.

The code works just fine if I want to do the same but for lists instead

            SPListCollection collList = web.Lists;

            foreach (SPList oList in collList)
            {
                //and so on

I have tried to put web.Update() in various places but without success. Any ideas?

Thanks in advance.

Edit:

I commented out most of the stuff and only left

        if (web.Name == "SiteName")
        {
            web.BreakRoleInheritance(true);
            web.Update();
        }

but it still throws the same error.

like image 636
Nick Avatar asked Apr 22 '26 17:04

Nick


1 Answers

I would try to do an SPWeb.Update and then

using(var newWeb = site.OpenWeb(web.ID))
{
    web.BreakRoleInheritance(true);
    web.Update();
}

Also, don't forget to do a SPWeb.Dispose on all the AllWebs opened in the foreach-loop.

like image 89
Marcus Rådell Avatar answered Apr 25 '26 09:04

Marcus Rådell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!