Add SharePoint Group to Library (Break Permissions)

I’ve had some back and forth hiccups when getting some security provisioning for a SharePoint library.

The basic premise was to break-inheritance – and only allow the “OWNERS” group to have permission (full control).

Seems easy enough – but I was getting errors like :

The collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.

Or this one, which was annoying, and tripping me up :

Cannot add a role assignment with empty role definition binding collection.

It turns out that I was actually doing “too many” of the ExecuteQuery statements – which I didn’t actually need.   

So – I had success, using this code – and through I’d share it in case you have the same problem – or for my own future reference :

// ==================================================================
// set the OWNERS group to have permissions to the [submitted work] library
// ==================================================================
List submittedWorkLib = clientCtx.Web.Lists.GetByTitle('Submitted Work');
clientCtx.Load(submittedWorkLib);
clientCtx.ExecuteQuery();

//break security/permissions for the library
submittedWorkLib.BreakRoleInheritance(false, false);
clientCtx.Load(submittedWorkLib);
clientCtx.ExecuteQuery();

//add the owners group
string workspaceOwnersGroup = web.Title + " Owners";
LogHelper.WriteToLog(log, "Add the workspace owners group to library : " + workspaceOwnersGroup);

clientCtx.Load(web.RoleDefinitions);
clientCtx.ExecuteQuery();

var role = web.RoleDefinitions.FirstOrDefault(r => r.Name == "Full Control");
clientCtx.Load(role);
clientCtx.ExecuteQuery();

clientCtx.Load(web.SiteGroups);
clientCtx.ExecuteQuery();

var group = web.SiteGroups.FirstOrDefault(g => g.Title == workspaceOwnersGroup);
clientCtx.Load(web.SiteGroups);
clientCtx.Load(group);
clientCtx.ExecuteQuery();

var roleDefBinding = new RoleDefinitionBindingCollection(clientCtx);
roleDefBinding.Add(role);
submittedWorkLib.RoleAssignments.Add(group, roleDefBinding);

clientCtx.ExecuteQuery();

Let me know if that helps – thanks !

Other references :

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s