Unfortunatly, projects aren’t always that fancy. In this case I’m still doing a bit of SP2010. Luckaly we do use CSOM to make it a bit interesting.
CSOM has a lot of functionality, and theoretically you can say “it does everything the old-fashioned SPSite model does”. However, it can be a struggle.
In this case, we needed to add a AD Group/User to sharepoint directly. Don’t ask, it’s a customer requirement. So, no SharePoint groups used.
In the end, this MSDN article was hugely useful.
Also note the usage of EnsureUsers which seems to work for groups as well!?
The permission parameter are the “Full Control” or “Read” permissions which are called “Permission Levels” in SharePoint itself. There’s a “level” below that called BasePermissions, for if you want to make it more complex for yourself :)
Here’s the bit of code that works for me:
public static void AddSecurityGroup(string url, string loginName, string permission)
using (ClientContext context = new ClientContext(url))
context.Load(context.Web, w => w.RoleAssignments);
context.Load(context.Web, w => w.HasUniqueRoleAssignments);
throw new ArgumentException("URL provided is not root for permissions. Did you break inheritence correctly? Because that's needed.");
User u = context.Web.EnsureUser(loginName); //This also seems to work for groups.
context.Load(u); // important as this actually loads the properties etc.
RoleDefinition oRoleDefinition = context.Web.RoleDefinitions.GetByName(permission);
RoleDefinitionBindingCollection collRoleDefinitionBinding = new RoleDefinitionBindingCollection(context);
RoleAssignment oRoleAssignment = context.Web.RoleAssignments.Add(u, collRoleDefinitionBinding);