Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add specific SharePoint Group to List permission

using (SPSite site = (SPSite)properties.Feature.Parent)
{
   using (SPWeb web = site.OpenWeb())
   {
        if (web != null)
        {
              web.AllowUnsafeUpdates = true;
              SPList list = web.Lists["Alert Status v1.0"];

              //Creates a new role assignment for a group
              SPGroup myGroup = web.SiteGroups["IKM Manager"];
              SPRoleAssignmentCollection roleAssignments = web.RoleAssignments;

              // SPRoleAssignment accepts a SPPrincipal which can be a SPUser or SPGroup
              SPRoleAssignment roleAssignment = new SPRoleAssignment(myGroup);

              //Add the new role assignment to the collection of role assignments for the site.
              roleAssignments.Add(roleAssignment);

              // Stop inheriting permissions
              list.BreakRoleInheritance(true);
              list.RoleAssignments.Add(roleAssignment);
              list.Update();

I have error on RoleAssignments.Add(roleAssignment) like "Cannot add a role assignment with empty role definition binding collection". I want to stop inheriting permissions and add specific group to List permissions. Can you help me? please..

Thanks

like image 588
mkacar Avatar asked Nov 30 '22 23:11

mkacar


2 Answers

You need to add a role definition binding to the role assignment, for example to add a contributor role definition

roleAssignment.RoleDefinitionBindings.Add(web.RoleDefinitions.GetByType(SPRoleType.Contributor));
like image 24
Aquila Sands Avatar answered Dec 05 '22 08:12

Aquila Sands


This should work.

list.BreakRoleInheritance(true);
SPGroup groupAdmin = web.SiteGroups["IKM Manager"];
SPRoleAssignment roleAssignmentAdmin = new SPRoleAssignment((SPPrincipal)groupAdmin);
SPRoleDefinition roleAdmin = web.RoleDefinitions.GetByType(SPRoleType.Administrator);
roleAssignmentAdmin.RoleDefinitionBindings.Add(roleAdmin);
list.RoleAssignments.Add(roleAssignmentAdmin);
list.Update();
like image 86
Raheel Avatar answered Dec 05 '22 10:12

Raheel