Add an existing site collection Group to sub site with modified Roles


Add an existing site collection Group to sub site with modified Roles

 OBJECTIVE
The site collection contains a group named “All Members” with “Contributor” privilege.
I want to add this group programmatically to a sub site and modify its roles from “Contributor” to “Read” without modifying the original group.
The following are the variables used in the code:
 –         site: the SPSite object of the site collection being used
–          web: the SPWeb object of the sub site you want to add the group to.
SOLUTION:
SPGroup group = site.RootWeb.SiteGroups[“All Members”]; SPRoleAssignment roleAssignment = new SPRoleAssignment(group); SPRoleDefinition roleDefinition = site.RootWeb.RoleDefinitions[“Read”]; roleAssignment.RoleDefinitionBindings.Add(roleDefinition); if (!web.HasUniqueRoleAssignments)      web.BreakRoleInheritance(true); web.RoleAssignments.Add(roleAssignment);
—————————————————————————
Working with Group: quick review:
  1)       BREAK INHERITANCE                                              2)       ADD NEW GROUP TO SITE COLLECTION
  3)       ASSOCIATE THE NEW GROUP TO A WEB          4)       ASSIGNMENT OF THE ROLES
 5)       ADD USERS TO THE GROUP                                    6)       REMOVE ALL ROLES
1) BREAK INHERITANCE
if (!web.HasUniqueRoleAssignments)
            web.BreakRoleInheritance(true);
2) ADD NEW GROUP TO SITE COLLECTION:
web.SiteGroups.Add(“MyNewGroup”, web.AssociatedOwnerGroup, null, “MyNewGroup description”);
3) ASSOCIATE THE NEW GROUP TO A WEB:
web.AssociatedGroups.Add(group);
web.Update();
4) ASSIGNMENT OF THE ROLES:
SPGroup group = web.SiteGroups[“MyNewGroup”];
SPRoleAssignment roleAssignment = new SPRoleAssignment(group);
SPRoleDefinition roleDefinition = site.RootWeb.RoleDefinitions[“Read”];
roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
web.RoleAssignments.Add(roleAssignment);
5) ADD USERS TO THE GROUP:
SPUser user = web.EnsureUser(“domain\MyUser”); SPGroup group = web.Groups[“MyNewGroup”];                        if(user!=null && group!=null)      group.AddUser(user);
6) REMOVE ALL ROLES:
SPRoleAssignmentCollection SPRoleAssColn = web.RoleAssignments; for (int i = SPRoleAssColn.Count – 1; i >= 0; i–) {       SPRoleAssColn.Remove(i); }
Advertisements

About sharepointsriram

9+ Yrs of IT experience
This entry was posted in Sharepoint 2010 Site Collection. Bookmark the permalink.

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