Ok, so one of the jobs I needed to do was automatically create a Site Collection and then create the members, owners and visitors groups.
The first job is to get hold of the web application
SPWebApplication spWA= SPWebApplication.Lookup(new Uri(http://mySite));
Next you can use the Sites collection to create the appropriate Site Collection
The new site collections URL can either be in the format mySiteCollection or managedpath/mySiteCollection
int32 lcid=1033;
string template="STS#2" //Get the one you want here
SPSite spS=spWA.Sites.Add(url,"SiteName","SiteDescription",lcid,template,"\\domain\ownerloginname","Owner Name", myemail@here.com)
There are a number of Add methods allowing you to configure owners, secondary owners, and config databases. Full list here
Once you have done this you will need to add the groups.
This is quite straight forward using the new site collections rootweb property and inturn the SiteGrpups collection
SPWeb spW=spS.rootWeb;
The trick now is to add the group. The issue here is that you will need an SPMember object which is either SPGroup or SPUser for the owner object.
The problem I encountered is that unless the user is part of the Root Web then they can’t be added as a Group owner. The group will half create and the API will not throw an Exception. What you will end up with is a Link in the Site Groups area of teh Site Collection, that errors when clicked. Also the SiteGroups count property will not reflect the new group, but you will not be able to add a group with the same name without receiving a name already exists exception
There are several ways to get a user object. One involves a straight spW.SiteUsers.Add(…… lots of data)
the other uses the Microsoft.Office.Workflow.Utility and generates a Contact, then uses this to get the actual user object.
Contact contact=Contact.FromName(userloginname,spW);
if(contact.PrincipalID < 0){
//this actually adds the user to the site collection users list
SPPrincipal p=contact.GetPrincipal(spW);
}
SPUser owner=spW.SiteUsers[contact.LoginName];
spW.SiteGroups.Add(spW.Title + " Owners",owner,null,"This is the default owners group")
SPGroup grpOwner=spW.SiteGroups[spW.Title + " Owners"];
spW.AssociatedOwnerGroup=grpOwner
//Repeat for other groups
Finally set the group permissions
SPRoleDefinitionCollection roleDef=spW.RoleDefinitions;
SPRoleAssignmentCollection roleAssigns=spW.RoleAssignments;
SPRoleAssignment roleAssign = new SPRoleAssignment(grpOwner);
SPRoleDefinitionBindingCollection definitions=roleAssign.RoleDefinitionBindings;
definitions.Add(roleDef["Full Control"]); //Could be Contribute or Read
roleAssigns.Add(roleAssign);
//Repeat for other groups
spW.Update();