If you create web site in Sharepoint and choose “Use unique permissions” option then after site template will be applied to the newly created site you will be redirected to the standard page “Set Up Groups for this Site” (_layouts/permsetup.aspx page):
Using this page you are able to create 3 standard groups for new site: Visitors, Members and Owners. But how these groups can be created programmatically? Suppose that we have customized process of site creation (e.g. use custom site creation page) with custom site template and want to create mentioned groups automatically without additional manual steps required from administrator.
In object model mentioned groups correspond to the following SPWeb properties: AssociatedOwnerGroup, AssociatedMemberGroup and AssociatedVisitorGroup. First of all we need to know what permissions have these groups on associated site. Here they are:
Now we can create associated groups programmatically using the following code:
First of all we need get names of associated groups. In order to get them we use the same approach which is used in OTB permsetup.aspx page, e.g.:
Also if we want to do things like they done in OTB page, we need to set SPGroup.Owner property to AssociatedOwnerGroup (you can check it after creation of site using OTB create page). AssociatedOwnerGroup will be owner of itself.
After that we need to assign permissions to created site groups using table mentioned above. We do it using the following code:
Here is the code of SecurityHelper utility class:
And last step – associate created groups with SPWeb:
Remaining question is where should we call this setupSecurity(…) method in our customized site creation process? One obvious place – feature receiver in some feature which is activated in our site automatically (this feature should be added into onet.xml of our custom site template). Unfortunately if you create custom portal based on OTB publishing site template, it is not suitable place – because Sharepoint will override associated groups somewhere in later execution steps (you will have null in SPWeb properties which correspond to associated groups, except Visitors group). One suitable place I found for this – is custom portal provisioning provider:
But this approach has own problem: code will be executed using language of site in context of which site creation process was started, i.e. not in context of newly created site. It means that if for example you opened custom site creation page under English site and create Swedish subsite, associated groups names will still have English titles (Owners, Members, Visitors). In order to make group titles on the language of created site we need temporary change locale of current thread. In one of my previous posts I already showed how to make it:
Now if you will create Swedish site, associated groups will have Swedish titles: Ägare av test, Medlemmar på test, Besökare på test (test is web site title).