简体   繁体   中英

Cannot add a role assignment with empty role definition binding collection

I am trying to give a permission to user using ClientContext in SharePoint 2013. I have done all exactly the same as in the Microsoft web site http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.roledefinitionbindingcollection.add.aspx

But at the end, this part of code always returns exception "Cannot add a role assignment with empty role definition binding collection":

RoleAssignment oRoleAssignment = w.RoleAssignments.Add(oUser, roleDefBinding);                            
clientContext.ExecuteQuery();

I haves searched web, found similar problems to some other users but without responses. Any ideas?

My Code:

clientContext.Load(w.RoleDefinitions);
clientContext.ExecuteQuery();
var role = w.RoleDefinitions.Where(r => r.Name == roleName);
if (role.Count() > 0)
{
       RoleDefinition roleMSP = role.First();
       clientContext.Load(w.SiteUsers);
       clientContext.ExecuteQuery();
       var user = w.SiteUsers.Where(u=> u.LoginName == "c:0+.w|s-1-5-21-3493872076-3631449775-1555872641-1347");
       if (user.Count() > 0)
       {
             // Create a new RoleDefinitionBindingCollection object.
             RoleDefinitionBindingCollection roleDefBinding = new RoleDefinitionBindingCollection(clientContext);
             roleDefBinding.Add(roleMSP);
             User oUser = user.First() as User;

             clientContext.Load(w.RoleAssignments);
             clientContext.ExecuteQuery();

             RoleAssignment oRoleAssignment = w.RoleAssignments.Add(oUser, roleDefBinding);                            
             clientContext.ExecuteQuery();//Here I get an exception
        }
}

Resolved! Removed the following lines of code:

clientContext.Load(w.RoleAssignments);
clientContext.ExecuteQuery();

Looks like you don`t need to retrieve the list of Assignements and after add your one.

Working code for me:

 RoleDefinitionCollection roleDefs = web.RoleDefinitions;
 var query = projectCtx.LoadQuery(roleDefs.Where(p => p.RoleTypeKind == RoleType.Contributor));
 projectCtx.ExecuteQuery();
 RoleDefinition roledefObj = query.FirstOrDefault();

 RoleDefinitionBindingCollection collRoleDefinitionBinding = new RoleDefinitionBindingCollection(projectCtx) { roledefObj };
 var roleAssignments = web.RoleAssignments;
 roleAssignments.Add(principalTest, collRoleDefinitionBinding);

 projectCtx.ExecuteQuery();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM