To add item level permission in an SharePoint List or Library, you need to keep three things in mind:
You have a valid SPUser object in your hand
You have to break the role assignment inheritance for the list
You have to add Role Definition and Role Assignment to the targeted list item
Though above statements looks complicated, don't think much about them – just use following two functions wisely and you are done :)
Assumption:
1. You have SPListItem object in your hand
2. You have a valid SPUser in your hand
Working:
First call the below method and pass the SPListItem as the input parameter:
- private static void RemoveAllPermissions(SPListItem CurrentlistItem)
- {
- //The below function Breaks the role assignment inheritance for the list and gives the current list its own copy of the role assignments
- CurrentlistItem.BreakRoleInheritance(true);
- //Get the list of Role Assignments to list item and remove one by one.
- SPRoleAssignmentCollection SPRoleAssColn = CurrentlistItem.RoleAssignments;
- for (int i = SPRoleAssColn.Count - 1; i >= 0; i--)
- {
- SPRoleAssColn.Remove(i);
- }
- }
Next call the below method and pass the desired parameters:
- private static void GrantPermission(SPListItem CurrentListItem, SPWeb oSPWeb, SPRoleType SPRoleType, SPPrincipal SPPrincipal)
- {
- try
- {
- //Create one Role Definition i.e Full Controls, Contribute rights or Read rights etc.
- SPRoleDefinition oSPRoleDefinition = oSPWeb.RoleDefinitions.GetByType(SPRoleType);
- //Create one Role Assignment for the specified SP user or group.
- SPRoleAssignment oSPRoleAssignment = new SPRoleAssignment(SPPrincipal);
- //Bind the role definition to the role assignment object created for the user or group.
- oSPRoleAssignment.RoleDefinitionBindings.Add(oSPRoleDefinition);
- //Add it to the specified list item.
- CurrentListItem.RoleAssignments.Add(oSPRoleAssignment);
- //update the list item so that specified user assignment will have the access.
- CurrentListItem.Update();
- }
- catch (Exception ex)
- {
- EventLog.WriteEntry("Error in UAR Initiation Workflow", "GrantPermission() : " + ex.Message);
- }
- }
For your easy reference I am including the code block from where I used to call these functions:
- if (validUsername)
- {
- if (rdr["Manager Logon"] != null)
- {
- SPUser CurrentUser = mySite.EnsureUser(rdr["Manager Logon"].ToString());
- RemoveAllPermissions(item);
- GrantPermission(item, mySite, SPRoleType.Contributor, CurrentUser);
- SPGroup oGroup = mySite.SiteGroups["UARAdministrators"];
- GrantPermission(item, mySite, SPRoleType.Administrator, oGroup);
- }
- }
- else
- {
- //Admin need to resolve this issue in the list
- RemoveAllPermissions(item);
- SPGroup oGroup = mySite.SiteGroups["UARAdministrators"];
- GrantPermission(item, mySite, SPRoleType.Administrator, oGroup);
- }
Cheers,
Avik