Thursday, July 28, 2011

The Mystery of SPWeb.SiteGroups and SPWeb.Groups

I've spend two days to find out how to create groups which is partaining just to Subsite. Everytime I created a group using SPWeb.SiteGroups.Add the group is associated with the parent site rather than subsite.

From documentation I realize
SPWeb.SiteGroups is associated with SiteCollection
SPWeb.Groups is associated with Web

So I attempted SPWeb.Groups.Add. And I encounter the following error message.

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

Damn!

To create a group for subsite, you have to create site groups first. After creating site group you have to add association of the group with sub site.

Someone from MSDN forum kind enough to give me this solution. I am just sharing it again to save the headache of others.

Pay attention to web.AssociatedGroups.Add. Without this function the group will not be associated to the subsite. :)

//Add the group to the SPWeb web
//This will add the SPGroup to SiteCollection
web.SiteGroups.Add(groupName, owner, defaultuser, description);

//Associate de group to the SPWeb.
//This will add the SPGroup to left side quicklaunch of Manage Groups page
web.AssociatedGroups.Add(web.SiteGroups[groupName]);
web.Update();

//Assignment of the roles.
//This is the actual permission/role assignment of SPGroup
SPRoleAssignment assignment = new SPRoleAssignment(web.SiteGroups[groupName]);
SPRoleDefinition roleApp = web.RoleDefinitions["Contribute"];
assignment.RoleDefinitionBindings.Add(roleApp);
web.RoleAssignments.Add(assignment);
web.Update();

http://social.technet.microsoft.com/Forums/en-US/sharepoint2010programming/thread/b6a7edda-e5fd-4a58-9273-e12705bec727

1 comment:

Larreeh said...

You're a life saver thanks