Set ListItem Permission Using Client Object Model on Sharepoint 2010

This sample code is use to set permission on sharepoint ListItem using Client Object Model. This code only available for sharepoint 2010, since Client Object Model only available for sharepoint 2010.

First retrieve the list item

   1: //retrieve the list item
   2: var clientContext = new ClientContext("http://mysite.com");
   3: var list = clientContext.Web.Lists.GetByTitle("My Document Lib");
   4: var camlQuery = new CamlQuery
   5:                     {
   6:                         FolderServerRelativeUrl = "/My Document Lib/My Documents/",
   7:                         ViewXml =
   8:                             "<View><Query><Where><Eq><FieldRef Name='FileRef' /><Value Type='Text'>My Document Lib/My Documents/Document.docx</Value></Eq></Where></Query></View>"
   9:                     };
  10: var listItems = list.GetItems(camlQuery);
  11: clientContext.Load(list);
  12: clientContext.Load(listItems);
  13: clientContext.Load(listItems,
  14:                    items =>
  15:                    items.Include(item => item.Id, item => item.DisplayName,
  16:                                  item => item.HasUniqueRoleAssignments,
  17:                                  item => item.EffectiveBasePermissions,
  18:                                  item =>
  19:                                  item.RoleAssignments.Include(roleAss => roleAss.Member,
  20:                                                               roleAss => roleAss.RoleDefinitionBindings)));
  21: clientContext.ExecuteQuery();

Then iterate the list item and set the permission, in this sample code we set the permission as a contributor.

   1: //set as a user domain\user
   2: var user = (Principal)clientContext.Web.EnsureUser("domain\\user");
   3:  
   4: //set permission as a contributor
   5: var contributor = clientContext.Web.RoleDefinitions.GetByType(RoleType.Contributor);
   6: var roleDefinitionBindingCollection = new RoleDefinitionBindingCollection(clientContext) { contributor };
   7:  
   8: foreach (var listItem in listItems)
   9: {
  10:     listItem.RoleAssignments.Add(user, roleDefinitionBindingCollection);
  11:     listItem.Update();
  12: }
  13:  
  14: clientContext.ExecuteQuery();

To reset the permission we can use this code.

   1: listItem.ResetRoleInheritance();
Share this post: | | | |
Published Monday, November 21, 2011 11:56 AM by ekasinggih

Comments

No Comments
Powered by Community Server (Commercial Edition), by Telligent Systems