Enterprise software development and consulting for various organizations, industries and domains.

Saturday, August 28, 2010

Sharepoint: Create Visitors group programmatically

I noticed interesting thing, when you use unique permissions for a site and want to set up permission groups, SharePoint offers to create Owners and Members group, but Visitors group is inherited from a parent site by default.


And even when I tried to do it programmatically using SPWeb.CreateDefaultAssociatedGroups, it still creates only two groups.

So I ended up with the following code snippet:

var primaryAdmin = web.SiteAdministrators[0];
var groupName = SPResource.GetString("DefaultVisitorGroupName", new object[] { SPHttpUtility.HtmlEncode(web.Title) });
var groupDescription = SPResource.GetString("DefaultVisitorGroupDescriptionRichText", new object[] { SPHttpUtility.HtmlEncode(web.Title), SPHttpUtility.HtmlUrlAttributeEncode(SPHttpUtility.UrlPathEncode(web.ServerRelativeUrl, false)) });
web.SiteGroups.Add(groupName, primaryAdmin, null, groupDescription);
web.AssociatedVisitorGroup = web.SiteGroups[groupName];

var roleAssignment = new SPRoleAssignment(web.AssociatedVisitorGroup);
web.RoleAssignments.Add(roleAssignment);
roleAssignment.RoleDefinitionBindings.Add(web.RoleDefinitions["Read"]);
web.AllowUnsafeUpdates = true;
roleAssignment.Update();

It creates Visitors group and gives it Read permissions.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.