There are some cases where you want to create a group pro grammatically and want to assign permission. e.g. on the Feature receiver (Feature Activated) code.
In this post i am going to explain you how to create group and to assign permissions to this group.
First get the collection of site groups.
SPGroupCollection groups = web.SiteGroups;
web.BreakRoleInheritance(false);
Add the group to this collection. I have created "Test Group" in this example.
groups.Add("Test Group", web.CurrentUser, null, "");
SPGroup grp= web.SiteGroups["Test Group"];
AllowMembersViewMembership property of this group to false.
This Gets or sets a Boolean value that specifies whether only group members are allowed to view the list of members in the group.
grp .OnlyAllowMembersViewMembership = false;
grp .Update();
Now create a Role Assignment object of this group.
SPRoleAssignment asgn = new SPRoleAssignment(web.SiteGroups[ "Test Group"]);
Create a Role Definition, Here i have used the "Administrator" role, other available roles are
1) None
2) Guest
3) Reader
4) Contributor
5) WebDesigner
6) Administrator
SPRoleDefinition role = web.RoleDefinitions.GetByType(SPRoleType.Administrator);
Now assign the Role to the Role Assignment and add the Role Assignment to the web and update the web
asgn.RoleDefinitionBindings.Add(role);
web.RoleAssignments.Add(asgn);
web.Update();
Now deploy the solution and check the group and its permissions.
I have used this code on the feature activated code that creates group and assign permissions to this.