Skip to content

Instantly share code, notes, and snippets.

@kitmenke
Created April 9, 2012 14:50
Show Gist options
  • Save kitmenke/2344008 to your computer and use it in GitHub Desktop.
Save kitmenke/2344008 to your computer and use it in GitHub Desktop.
Code to give one role (Read, Contribute, etc) to an SPPrincipal
public static void GivePrincipalRoleToItem(SPWeb web, SPListItem item, SPPrincipal principal, string roleDefinitionName)
{
if (null == principal)
{
throw new ArgumentException(string.Format("Unable to give role '{0}'; passed principal is null.", roleDefinitionName));
}
bool exists = false;
SPRoleAssignment roleAssignment = null;
try
{
roleAssignment = item.RoleAssignments.GetAssignmentByPrincipal(principal);
exists = true;
}
catch (Exception)
{
// not found in role assignment
}
if (null == roleAssignment)
{
roleAssignment = new SPRoleAssignment(principal);
}
if (exists)
{
// the group should only have the role that was specified
// if we don't remove them all, it will do an "append"
// ex: if it has Read and we are adding Contribute, will have
// Read AND Contribute
roleAssignment.RoleDefinitionBindings.RemoveAll();
}
SPRoleDefinition roleDefinition = web.RoleDefinitions[roleDefinitionName];
roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
if (exists)
{
roleAssignment.Update();
}
else
{
item.RoleAssignments.Add(roleAssignment);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment