I am trying to manipulate SPListItem permissions on folders in a document library but I can’t seem to add any new permissions, though removing security inheritance works beautifully.
I’ve done my best to create a slimmed down version of the code for testing purposes. The function GetListItem returns the SPListItem we are working with based on the URL. The item.BreakRoleInheritance(False) works great and I’ve verified properly breaks inheritance and clears out any permissions, I’ve also tried it with the True flag and verified that all original permissions are copied from the parent.
The code below throws no exceptions and as far as I can tell appears to work fine, until I check the actual permissions on the folder in my document library and see that “Viewers” is not listed.
Code:
Dim item As SPListItem = GetListItem(URL)
If item Is Nothing Then
Exit Sub
End If
Dim spGrp = SharePointWeb.SiteGroups("Viewers")
Dim spRole As SPRoleDefinition = SharePointWeb.RoleDefinitions("Read")
Dim roleAssignment As New SPRoleAssignment(spGrp)
roleAssignment.RoleDefinitionBindings.Add(spRole)
SharePointWeb.AllowUnsafeUpdates = True
item.BreakRoleInheritance(False)
item.RoleAssignments.Add(roleAssignment)
item.Update()
SharePointWeb.AllowUnsafeUpdates = False
I have tried wrapping this code in a call to SPSecurity.RunWithElevatedPrivileges but it didn’t make any difference. The creation of my SPSite/SPWeb objects is wrapped in a call to SPSecurity.RunWithElevatedPrivileges and I have other code that runs which finds/deletes/updates attributes on folders/etc… with this existing code; just permissions don’t want to work.
References:
– http://moldenco.blogspot.com/2007/05/spsecurityrunwithelevatedprivileges-to.html
– How to give an SPGroup permissions for an SPItem?
– http://blogs.msdn.com/b/joelo/archive/2007/10/05/sharepoint-roles-assignments.aspx
Through researching the issue and trying a veriety of different methods I happened across an exception, “Operation is not valid due to the current state of the object” which occured in SPWebEnsureSPControl.
I did some googling and found this forum post http://social.msdn.microsoft.com/forums/en-US/sharepointdevelopment/thread/32869ac6-4f47-46b8-accf-f56966ac9581 which lead me to modify my code. I made
System.Web.HttpContext.Current = Nothingthe first line of code after callingSPSecurity.RunWithElevatedPrivilegesand everything started working.So my code looks something like (using an anonomous delegate):
From what I read
System.Web.HttpContext.Currentstill has connections to your non-elevated account and by setting it to null it gets rid of the problem.