Assigning Item Level Priviliges to SPListItem
Posted by zieglers on October 6, 2009
Sometimes you might wanna assign item level permissions to a list item instead of using Elevated Priviliges block throughout the whole code. This might happen in case you need to temporarily give a user higher priviliges than she has.
Typical example would be to provide a site reader exceptional functionality on a specific list item. In this case you break role inheritance and give the permissions you want. Here is a little snippet for that:
======================================================================
RunWithElevatedPriv
…using SPSite…
…using SPWeb…
// Get current user obj
SPUser user = SPContext.Current.Web.CurrentUser;
// Get current user token
SPUserToken token = user.UserToken;
// Get current user principal
SPPrincipal principal = (SPPrincipal)SPContext.Current.Web.CurrentUser;
// Get current user role assignment
SPRoleAssignment RoleAssignment = new SPRoleAssignment(principal);
// Get Your Custom Role definition
int SiteContributorId = -1;
SPRoleDefinition RoleDefSiteContributor = new SPRoleDefinition();
foreach (SPRoleDefinition roleDef in web.RoleDefinitions)
// Find Your Custom Role Definition id
if (roleDef.Name == “Your Custom Role Name”)
SiteContributorId = roleDef.Id;
if (SiteContributorId != -1) {
RoleDefSiteContributor = web.RoleDefinitions.GetById(SiteContributorId);
// Add Your Custom Role to role assignments
RoleAssignment.RoleDefinitionBindings.Add(RoleDefSiteContributor);
}
if (!impersonatedListItem.HasUniqueRoleAssignments)
// Break role inheritance
impersonatedListItem.BreakRoleInheritance(true);
// Add Your Custom Role assignment to list item
impersonatedListItem.RoleAssignments.Add(RoleAssignment);
// Update changes
impersonatedListItem.Update();
…close using SPWeb…
…close using SPSite…
======================================================================
zieglers
