Tuesday, March 3, 2009

How to set Item Level Permission in to Sharepoint List

Hi,

Today I will discuss how to revoke Item level permission and how to grant Item Level permission on a sharepoint list to a user.

Before discussing the code, I would like to tell you something about some properties used in the code:

SPList.RoleAssignments Property :
Gets the collection of role assignments for the list.
Namespace: Microsoft.SharePoint
Assembly: Microsoft.SharePoint (in microsoft.sharepoint.dll)

SPRoleAssignment.RoleDefinitionBindings Property : Gets the collection of role definition bindings for the role assignment.
Namespace: Microsoft.SharePoint
Assembly: Microsoft.SharePoint (in microsoft.sharepoint.dll)

SPPrincipal Class :
Represents a user or group that can be assigned permissions in Windows SharePoint Services to control security.
Namespace: Microsoft.SharePoint
Assembly: Microsoft.SharePoint (in microsoft.sharepoint.dll)

I have written a function that will take the following parameters:

1. string Site url
2. string Library name
3. string Old user name (format : <domainname>\<username>
4. string new user name (format : <domainname>\<username>

My whole intension of function is to revoke permission of the item from old user and assign it to new user. You may or may not require the new user parameter if you are only revoking access.

public static void SetItemPermission(string SitePath, string LibName, string OldUser, string NewUser)
{

SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite WebApp = new SPSite(SitePath))
{
using (SPWeb Site = WebApp.OpenWeb())
{
SPList list = Site.Lists[LibName];
SPQuery newSPQuery = new SPQuery();
newSPQuery.Query = "<where><contains><fieldref name="\">" +
"<value type="\">" + OldUser + "</value>" + "</contains></where>";
try{
SPListItemCollection listItemCol = list.GetItems(newSPQuery);
if (listItemCol.Count > 0)
{
SPUser user = null, _newUser = null;
SPRoleAssignment role = null;
foreach (SPListItem item in listItemCol)
{
user = Site.Users[OldUser];
SPPrincipal principal = (SPPrincipal)user;
item.RoleAssignments.Remove(principal);
role = new SPRoleAssignment(NewUser, "", "", "");
role.RoleDefinitionBindings.Add(Site.RoleDefinitions["Contribute"]);
item.RoleAssignments.Add(role);
}
item.SystemUpdate(false);
}
}}catch(Exception ex){}
}
}
});


}
#endregion

1 comment:

Term Papers said...

I have been visiting various blogs for my term papers writing research. I have found your blog to be quite useful. Keep updating your blog with valuable information... Regards