Share a SharePoint File with different Office365 users using Client Object Model C#

In my previous post, Get a list of all the Shared users for a ListItem/Document of SharePoint List, I had described how to get the list of all the SharePoint users with whom a given Document Library item, has been shared. Now, in this post, I am going to Share an existing ListItem with a different SP user using CSOM.This works in the following 2 simple steps:

  1. Get the user(principal) with whom the item has to be shared.
  2. Next, get/create the RoleDefinition which will have various Permission Rights for the user.

The 2nd point is important. SP has already defined various RoleDefinitions that we can use for our purpose like, Administrator, ContentEditior, Read, etc. So we can either use any one of them or can even create our own custom RoleDefinition. I am going to demonstrate both the functionalities here.

First get the User and the ListItem which is to be shared


ClientContext ctx = new ClientContext("targetURL");
ctx.Credentials = new SharePointOnlineCredentials(userName, passWord);

ctx.Load(ctx.Web);
SP.ListCollection listCol = web.Lists;
ctx.Load(listCol);

SP.List list = listCollection.GetByTitle("ListTitle");

SP.CamlQuery camlQuery = new SP.CamlQuery();
camlQuery.ViewXml = "";

SP.ListItemCollection listItemCollection = list.GetItems(camlQuery);
ctx.Load(listItemCollection);

ctx.ExecuteQuery();

//get the user you want to share the current item
User currentUser = ctx.Web.EnsureWeb("memberLoginName")
SP.ListItem listItem = listItemCollection.FirstOrDefault(t => t.DisplayName == "WordFile");
ctx.Load(listItem,
    li => li.HasUniqueRoleAssignments,
    li => li.RoleAssignments.Include(
        p => p.Member,
        p => p.RoleDefinitionBindings.Include(
            s => s.Name)));
ctx.Load(currentUser);
            
ctx.ExecuteQuery(); 

Share with User with Existing RoleDefinition

RoleDefinitionCollection roleDefCol = ctx.Web.RoleDefinitions;

ctx.Load(roleDefCol, r => r.Include(p => p.Name));
ctx.ExecuteQuery();

RoleDefinitionBindingCollection rDefBindCol = new RoleDefinitionBindingCollection(ctx);

//Could be Edit, Read, Contribute, etc.
string roleDefName = "Edit";
RoleDefinition rDef = roleDefCol.FirstOrDefault(p => p.Name == roleDefName);

if(rDef != null)
{
    //Add the current binding to the seleted listItems RoleAssignments
    rDefBindCol.Add(rDef);
}

ctx.ExecuteQuery();

Console.WriteLine("SharePoint Role Assigned successfully.");

Share with User with new Custom RoleDefinition

Site collSite = ctx.Site;

// Set up permissions.
BasePermissions permissions = new BasePermissions();
permissions.Set(PermissionKind.ViewListItems);
permissions.Set(PermissionKind.AddListItems);
permissions.Set(PermissionKind.EditListItems);
permissions.Set(PermissionKind.DeleteListItems);

// Create a new role definition.
RoleDefinitionCreationInformation rdcInfo = new RoleDefinitionCreationInformation();
rdcInfo.Name = "Manage List Items";
rdcInfo.Description = "Allows a user to manage this list items";
rdcInfo.BasePermissions = permissions;
RoleDefinition roleDef = collSite.RootWeb.RoleDefinitions.Add(rdcInfo);

// Create a new RoleDefinitionBindingCollection object.
RoleDefinitionBindingCollection collRDB = new RoleDefinitionBindingCollection(ctx);
// Add the role to the collection.
collRDB.Add(roleDef);

// Break permissions so its permissions can be managed directly.
listItem.BreakRoleInheritance(true, false);

// Get the RoleAssignmentCollection for the target listItem.
RoleAssignmentCollection collRoleAssign = listItem.RoleAssignments;
// Add the user to the target listItem and assign the user to the new //RoleDefinitionBindingCollection.
RoleAssignment rollAssign = collRoleAssign.Add(currentUser, collRDB);

ctx.ExecuteQuery();

Console.WriteLine("Custom Role Assigned successfully."); 

Get a list of all the Shared users for a ListItem/Document of SharePoint List using Client Object Model C#

In SharePoint, users have the option to share a document or a folder with another user with either Read or Edit permissions. So you can have a document or may be a folder that you have shared with a person, or many person, or even a group. So now the endevaour is to get a list of all the users with whom a given document is shared with their corresponding permission levels.

To do this, we’re take the help of Role Assignment class.
SharePoint stores this information in the ListItem’s RoleAssignments property. So have a look at the following code:


ClientContext ctx = new ClientContext(targetURL);
ctx.Credentials = new SharePointOnlineCredentials(userName, passWord);

ctx.Load(ctx.Web);
SP.ListCollection listCol = web.Lists;
ctx.Load(listCol);

SP.List list = listCollection.GetByTitle("ListTitle");

SP.CamlQuery camlQuery = new SP.CamlQuery();
camlQuery.ViewXml = "";

SP.ListItemCollection listItemCollection = list.GetItems(camlQuery);
ctx.Load(listItemCollection);

//Execute Query 
ctx.ExecuteQuery();

 
SP.ListItem listItem = listItemCollection.FirstOrDefault(t => t.DisplayName == "WordFileName");

ctx.Load(listItem,
    li => li.HasUniqueRoleAssignments,
    li => li.RoleAssignments.Include(
        p => p.Member,
        p => p.RoleDefinitionBindings.Include(
            s => s.Name)));
ctx.ExecuteQuery();

if (listItem.HasUniqueRoleAssignments)
{
    //Get all the RoleAssignments for this document
    foreach (RoleAssignment rAssignment in listItem.RoleAssignments)
    {
        //A single RA can have multiple bindings
        foreach (RoleDefinition rDef in rAssignment.RoleDefinitionBindings)
        {
            Console.WriteLine(String.Concat("Role assigned to the member, ", rAssignment.Member.LoginName, " is ", rDef.Name));
        }
    }
}
else
    Console.WriteLine("The current ListItem has no unique roles assigned to it.");

Here, what I am doing is that for a given SharePoint site, I am connecting to a Document Library named, “ListTitle”. Then I am trying to get an item, “WordFileName”  from that list as this item has got some unique roles.

The important things to note down here is:

  1. A single item can have multiple Role Assignments i.e., different types of roles can be assigned to it. Say, a given user, A, might be assigned with “Edit” permission while another user, B, can have only “Read” permissions. Each of this variations will come down as a single Role Assignment(RA).
  2. A single Role Assignment can have multiple bindings.

Following are the roles defined for the user, that you can get for an item:

  • Full Control
  • Design
  • Edit
  • Contribute
  • Read
  • Limited Access
  • View Only
  • Records Center Web Service Submitters

The above List may vary if there are some custom Role Definitions.

You might want to have a look about the Limited Access permission here, https://realmpksharepoint.wordpress.com/2014/07/29/you-cannot-grant-a-user-the-limited-access-permission-level/

Similarly, here’s the link to the blog where I have described how, through code, we can share Office365 file, https://realmpksharepoint.wordpress.com/2014/08/04/share-a-sharepoint-file-with-different-office365-users-using-client-object-model-c/
That’s it.