Sunday, October 6, 2013

SharePoint 2013: CSOM List Permissions in C#

Intro: I'm building a SharePoint 2013 provided hosted app. I had a requirement to retrieve permissions for the current user to a particular list. I want to enable/disable a checkbox depending on their ability to add/edit items in a particular SharePoint list. So I search around and find this:
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.list.effectivebasepermissions.aspx
Unfortunately there's no sample in the above article and aren't any examples of how to use it anywhere on the web.

Issue: The EffectiveBasePermissions isn't loaded unless you specifically ask for it. This is the CSOM way.

Solution:
using (var clientContext = new ClientContext(hostWeb))
{
    Site site = clientContext.Site;
    clientContext.Load(site);
    clientContext.ExecuteQuery();

    Web web = site.OpenWeb("Name of spweb");
    clientContext.Load(web);
    clientContext.ExecuteQuery();

    List list = web.Lists.GetByTitle("Name of List");
    clientContext.Load(list, l => l.EffectiveBasePermissions); 
    clientContext.ExecuteQuery();

    bool myAddPermission = list.EffectiveBasePermissions.Has(PermissionKind.AddListItems);
    bool myEditPermission = list.EffectiveBasePermissions.Has(PermissionKind.EditListItems);
}

The code above will more than likely get the permission of the IIS App pool running your app. You may need to change the credentials in which the clientContext is running:
clientContext.Credentials = new NetworkCredential();

Explanation:
When writing server side code we can get all the data for the Web or list. Because we can afford to. But when we use CSOM we want to minimise the amount of data going back and forth. So the clientContext won't have the "EffectiveBasePermissions" unless you tell it to.

No comments:

Post a Comment