Many times we are into a situation like we need to manage the Item Level Permissions programmatically.
Below is the code snippet by which we can manage Item Level Permissions programmatically.
SPSite objSPSite = new SPSite("<Site URL>");
SPWeb objSPWeb = objSPSite.OpenWeb();
SPList oSPList = objSPWeb.Lists["<List NAme>"];
//Create new user to grant access
/***************************/
SPUserCollection users = objSPWeb.Users;
SPUser CurrentUser = users[@"SHAREPOINT\system"];
/***************************/
foreach (SPListItem objSPListItem in oSPList.Items)
{
//Remove all Permissions
RemoveAllPermissions(objSPListItem);
//Grant permissions to List Items
AddNewPermission(objSPListItem, objSPWeb, SPRoleType.Contributor, CurrentUser);
}
/*************************************************************************/
Function to remove all Permissions from a List Item
private static void RemoveAllPermissions(SPListItem CurrentlistItem)
{
CurrentlistItem.BreakRoleInheritance(true);
SPRoleAssignmentCollection objSPRoleAssColn = CurrentlistItem.RoleAssignments;
for (int i = objSPRoleAssColn.Count - 1; i >=0 ; i--)
{
objSPRoleAssColn.Remove(i);
}
}
/*************************************************************************/
Function To add new permission to a List Item
private static void AddNewPermission(SPListItem ListItem, SPWeb objSPWeb, SPRoleType objSPRoleType, SPPrincipal objSPPrincipal)
{
SPRoleDefinition objSPRoleDefinition = objSPWeb.RoleDefinitions.GetByType(objSPRoleType);
SPRoleAssignment objSPRoleAssignment = new SPRoleAssignment(objSPPrincipal);
objSPRoleAssignment.RoleDefinitionBindings.Add(objSPRoleDefinition);
ListItem.RoleAssignments.Add(objSPRoleAssignment);
ListItem.Update();
}
}
No comments:
Post a Comment