A user asked the following question:
I have SharePoint List with unique permissions. I need to retrieve the SharePoint Groups which don't have Full Control permissions on the List. Then need to remove them from the List Permissions only.
Since I was free I thought to give it a try. Following is the code:
But it gives follwoing
error: Invalid usage of query execution. The query should be executed by using
ExecuteQuery method on the client context object. Anyone having idea why this
error comes up?
I have SharePoint List with unique permissions. I need to retrieve the SharePoint Groups which don't have Full Control permissions on the List. Then need to remove them from the List Permissions only.
Since I was free I thought to give it a try. Following is the code:
ClientContext clientContext = new ClientContext("http://demo2010a:90");
Web site = clientContext.Web;
List list = clientContext.Web.Lists.GetByTitle("TestList");
clientContext.Load(site, s => s.RoleDefinitions);
clientContext.ExecuteQuery();
clientContext.Load(list, l => l.HasUniqueRoleAssignments);
clientContext.ExecuteQuery();
List<Principal> groupsToRemove = new List<Principal>();
if (list.HasUniqueRoleAssignments)
{
RoleDefinition role = site.RoleDefinitions.GetByName("Full Control");
clientContext.Load(role);
clientContext.ExecuteQuery();
RoleAssignmentCollection oRoleAssignments = list.RoleAssignments;
clientContext.Load(oRoleAssignments);
clientContext.ExecuteQuery();
List<RoleDefinition> rolesToRemove = new List<RoleDefinition>();
foreach (RoleAssignment oRoleAssignment in oRoleAssignments)
{
clientContext.Load(oRoleAssignment, r => r.Member, r => r.RoleDefinitionBindings);
clientContext.ExecuteQuery();
Principal oPrincipal = oRoleAssignment.Member;
if (oPrincipal.PrincipalType == Microsoft.SharePoint.Client.Utilities.PrincipalType.SharePointGroup)
{
int roleDefCount = 0;
foreach (RoleDefinition def in oRoleAssignment.RoleDefinitionBindings)
{
if (def.Id == role.Id)
{
break;
}
else
{
roleDefCount++;
if (roleDefCount == oRoleAssignment.RoleDefinitionBindings.Count)
groupsToRemove.Add(oPrincipal);
}
}
}
}
foreach (Principal group in groupsToRemove)
{
list.RoleAssignments.GetByPrincipal(group).DeleteObject();
}
list.Update();
}
clientContext.ExecuteQuery();
I actually tried to use a simpler statement i.e.if (!oRoleAssignment.RoleDefinitionBindings.Contains(role))
{
groupsToRemove.Add(oPrincipal);
}