I need to assign unique permission to a SharePoint list. I have the SP group created in the site and the list permission inheritance is broken. Now I would like to assign permission to the group for this list by adding this group in the list permission. Below is the code I am trying but it says the specified name already exists. Kindly help.
public static void AddPermission(ClientContext cpx,List list, string groupName, string permissionName)
{
Web web = cpx.Web;
Site site = cpx.Site;
RoleDefinitionBindingCollection collRoleDefinitionBinding = new RoleDefinitionBindingCollection(cpx);
Principal userGroup = FindUSerorSiteGroup(groupName,cpx,site, groupName);
RoleAssignment spRoleAssign = list.RoleAssignments.GetByPrincipal(userGroup);
// RoleDefinition role = web.RoleDefinitions.GetByName("Contribute");
collRoleDefinitionBinding.Add(cpx.Web.RoleDefinitions.GetByType(RoleType.Reader));
// spRoleAssign.RoleDefinitionBindings.Add(role);
list.RoleAssignments.Add(userGroup, collRoleDefinitionBinding);
spRoleAssign.Update();
list.Update();
// cpx.Load(list);
cpx.ExecuteQuery();
}
private static Principal FindUSerorSiteGroup(string groupname,ClientContext coj,Site site, string userOrGroup)
{
Principal myuser = null;
Web web = coj.Web;
if (userOrGroup != null)
{
Microsoft.SharePoint.Client.GroupCollection gs = coj.Web.SiteGroups;
coj.Load(gs, groupitems => groupitems.Include(groupitem => groupitem.Title, groupitem => groupitem.Description).Where(groupitem => groupitem.Title == groupname));
coj.Load(gs);
coj.Load(site.RootWeb.SiteGroups);
coj.ExecuteQuery();
//might be a group
foreach (Microsoft.SharePoint.Client.Group g in site.RootWeb.SiteGroups)
{
if (g.Title.ToUpper() == userOrGroup.ToUpper())
{
myuser = g;
Microsoft.SharePoint.Client.Group group = web.SiteGroups.GetByName(userOrGroup);
User owner = web.EnsureUser("Ankit Kumar");
GroupCreationInformation objCreateInfo = new GroupCreationInformation();
objCreateInfo.Title = userOrGroup;
web.SiteGroups.Add(objCreateInfo);
break;
}
}
}
return myuser;
}