Geeks With Blogs
Dennis Bottjer | MVP

SPWeb.Groups and SPWeb.SiteGroups

WSS 3.0 deprecates the site group concept used in WSS 2.0.  As a result manipulating groups and security objects through the object model can be less than obvious.

For Example, a developer may try to add a group to a sub site (SPWeb) using this syntax SPWeb.Groups.Add(Group Name). However, in WSS 3.0 and MOSS 2007 this code will result in the following error:

“You cannot add a group directly to the Groups collection. You can add a group to the SiteGroups collection.”

To resolve this error and create a group use the following object model syntax:  SPWeb.SiteGroups.Add().  This code will create a new group at the site collection level. Groups created at the site collection level are basically the same as “Cross Site Groups” from WSS 2.0. 

Note: All sub sites that are inheriting permissions from a parent site will see the groups added using SPWeb.SiteGroups.Add() when iterating through the SPWeb.Groups collection.

Ref: http://msdn.microsoft.com/en-us/library/ms469194.aspx

Associating a Group with a Site

It is important to realize that groups are never really “Added” to sites (SPWebs) but are instead associated. For example, if you have created a sub site that does not inherit permissions from its parent and you would like to “Add” a project manager group to that site you would use the following code.

   1: // Get a reference a group by name.
   2: SPGroup oGroup = webSite.SiteGroups[groupName];
   3:  
   4: // Get the role definition to assign ex: Full Control
   5: SPRoleDefinition oRole = webSite.RoleDefinitions[roleDefinition];
   6:  
   7: // Create the role assignment object
   8: SPRoleAssignment oRoleAssignment = new SPRoleAssignment(oGroup);
   9:  
  10: // Add the role definition to the role assignemnt. 
  11:  
  12: // Assign the specific permission to the security principal for this role assignemnt.
  13: oRoleAssignment.RoleDefinitionBindings.Add(oRole);
  14:  
  15: // Add the role assignment to the web
  16: webSite.RoleAssignments.Add(oRoleAssignment);
  17:  
  18: webSite.Update();

This code associates a site collection (Cross Site) Group with a SPWeb and assigns a role definition such as “Full Control.” With the code discussed in this post we could create a group, then give that group full control to a sub site.

Posted on Thursday, October 9, 2008 3:05 AM SharePoint | Back to top


Comments on this post: Manipulating SharePoint Groups With Code

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © DennisBottjer | Powered by: GeeksWithBlogs.net