Tuesday, 26 April 2016

Set List Item Level Permission using CSOM - C# in SharePoint

In this post, I am going to explain how to add SharePoint listitem level permissions programmatically by CSOM (Client Object Model) in C#. Sometimes we may have a business requirement to grant or set explicit permission for a particular list item. To add explicit permission, we need to first break the inheritance (stop inheriting permissions) of the particular document item, then we need to create Role Definition object (i.e Full Controls, Contribute or Read rights etc...), then need to add new RoleAssignment for user or group object and finally we need to update the ListItem object to finish the work.

You can use the following C# code to set sharepoint list item level permission for a particular user or group with csom (client object model).
public static void SetItemLevelPermissions()
{
    string sitrUrl = "https://sptenant.sharepoint.com/sites/contosobeta";
    using (var ctx = new ClientContext(sitrUrl))
    {
        var web = ctx.Web;
        ctx.Load(ctx.Web, a => a.Lists);
        ctx.ExecuteQuery();

        List list = ctx.Web.Lists.GetByTitle("TestDocLibrary");
        string documentName = "TextFile.txt";
        CamlQuery camlQuery = new CamlQuery();
        camlQuery.ViewXml = "" +documentName +
            "";
        var items = list.GetItems(camlQuery);
        ctx.Load(items, a => a.Include(i => i.HasUniqueRoleAssignments));
        ctx.ExecuteQuery();

        foreach (var listItem in items)
        {
            if (!listItem.HasUniqueRoleAssignments)
            {
                listItem.BreakRoleInheritance(false, false);
                ctx.ExecuteQuery();
            }

            var roleAssignments = listItem.RoleAssignments;
            //Use below line, if you want to give access to a Group
            //var user_group = web.SiteGroups.GetByName("Site Members");
            var user_group = web.SiteUsers.GetByLoginName("i:0#.f|membership|admin@sptenant.onmicrosoft.com");

            var roleDefBindCol = new RoleDefinitionBindingCollection(ctx);
            // Add Role Definition i.e Full Controls, Contribute or Read rights etc..
            roleDefBindCol.Add(web.RoleDefinitions.GetByType(RoleType.Contributor));
            roleAssignments.Add(user_group, roleDefBindCol);
            ctx.Load(roleAssignments);
            listItem.Update();                    
            ctx.ExecuteQuery();
        }
    }
}

Advertisements
Advertisements

1 comment: