Posted By

blackf0rk on 12/18/09


Tagged

collection site role group assignment Definition sharepoint RoleDefinition RoleAssignment


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

jlaws0n


Add a new group to SharePoint Site Collection; Add Role Definition and Assignment


 / Published in: C#
 

An important thing to keep in mind about adding groups is that you add groups to site collections and not webs. To do this, we access the SiteGroups collection rather than the Groups collection.

In order to assign permissions, each group you add needs a role definition (i.e. Read, Contribute, Design, or Full Control). It's best practice to assign role definitions to a group and assign users to the group, rather than assign definitions to individual users.

  1. //get a handle on our sites and web(s)
  2. SPSite Site = new SPSite("<sharepoint url>");
  3. SPWeb Web = Site.OpenWeb();
  4.  
  5. //get a handle on our users (we need an owner and a member to add a group). Se my snippet on adding users to SharePoint if you don't have the user in SharePoint that you'd like to add.
  6. SPUserCollection users = Web.AllUsers;
  7. SPUser owner = users["DOMAIN\username"];
  8. SPMember member = users["DOMAIN\username"];
  9.  
  10. //get a handle on all our sites' groups
  11. SPGroupCollection groups = Web.SiteGroups;
  12.  
  13. //add the new group
  14. groups.Add("<group name>", member, owner, "<group description>");
  15.  
  16. //add the role definition and assignment
  17. SPGroup <group name> = groups["<group name>"];
  18. //You can change "Full Control" to Read, Design, or Contribute:
  19. SPRoleDefinition role = Web.RoleDefinitions["Full Control"];
  20. SPRoleAssignment roleAssignment = new SPRoleAssignment(<group name>);
  21. roleAssignment.RoleDefinitionBindings.Add(role);
  22. Web.RoleAssignments.Add(roleAssignment);
  23. Web.Update();

Report this snippet  

You need to login to post a comment.