Thursday, June 21, 2012

Set Item level permission programmatically in SharePoint 2010


When I work in a SharePoint 2010 project, it is required to set the item level permission for libraries programmatically. I thought to share this piece of code in this article. Programmatically item level permission can be given to individual users and groups. 

The permission is set when the item is created, in ItemAdded event receiver.

Following code set item level permission for the individual users.

public override void ItemAdded(SPItemEventProperties properties)
       {
           SPSecurity.RunWithElevatedPrivileges(delegate()
           {
               try
               {
                   using (SPSite site = new SPSite(properties.SiteId))
                   {
                       using (SPWeb web = site.OpenWeb(properties.RelativeWebUrl))
                       {
                           //SPList list = properties.List;
                           //SPListItem item = properties.ListItem;
                           SPListItem item = web.Lists[properties.ListId].GetItemById(properties.ListItem.ID);  

                           web.AllowUnsafeUpdates = true;
                          
                           string email = "t-ictdev05@xxxxx.com";
                           SPUser user = web.SiteUsers.GetByEmail(email);

                           item.BreakRoleInheritance(false);
                           SPRoleDefinitionCollection webroledefinitions = web.RoleDefinitions;
                           SPRoleAssignment roleassignment = new SPRoleAssignment(user);
                           roleassignment.RoleDefinitionBindings.Add(webroledefinitions["Contribute"]);
                           item.RoleAssignments.Add(roleassignment);

                           item.Update();
                       }
                   }
               }
               catch (Exception ex)
               {
                   properties.Status = SPEventReceiverStatus.CancelWithError;
                   properties.ErrorMessage = ex.Message;
                   properties.Cancel = true;
               }
           });
       }

All the SharePoint users have no permission to set the permission. Only administrators can do. To avoid this, the code block is written in side SPSecurity.RunWithElevatedPrivileges scope. So that the code run with the administrator privilege. 

A new set of SPSite and SPWeb objects created in side SPSecurity.RunWithElevatedPrivileges scope. If you use the existing objects the system throws exception. And also if you use
SPList list = properties.List;
SPListItem item = properties.ListItem;
it throws exception.

For each item created, the event receiver set ‘Contribute’ permission to the user identified by the email address. You can set Read, Full Control, etc.. permissions as required.

Following code set ‘Read’ permission to the group named ‘CXOs’.

string cxosGroup = "CXOs";
SPPrincipal cxosGroupUserGroup = FindUserOrSiteGroup(site, cxosGroup);
SPRoleDefinitionCollection cxosGroupRole = web.RoleDefinitions;
SPRoleAssignment cxosGroupRoleAssign = new SPRoleAssignment(cxosGroupUserGroup);                               cxosGroupRoleAssign.RoleDefinitionBindings.Add(cxosGroupRole["Read"]);
item.RoleAssignments.Add(cxosGroupRoleAssign);

The following method return the SPPrincipal object for the specified site and the group.

private static SPPrincipal FindUserOrSiteGroup(SPSite site, string userOrGroup)
       {
           SPPrincipal myUser = null;

           if (SPUtility.IsLoginValid(site, userOrGroup))
           {
               myUser = site.RootWeb.EnsureUser(userOrGroup);
           }
           else
           { 
              foreach (SPGroup g in site.RootWeb.SiteGroups)
               {
                   if (g.Name.ToUpper(System.Globalization.CultureInfo.InvariantCulture) == userOrGroup.ToUpper(System.Globalization.CultureInfo.InvariantCulture))
                   {
                       myUser = g;
                       break;
                   }
               }
           }
           return myUser;

       }

Done. :)

1 comment: