Wednesday, March 28, 2007

Create Groups Programmatically

Reza Alirezaei has posted a helpful article on creating SharePoint sites with unique role assignments. The following simple demo class puts some of these ideas together. Like Reza's example, the code below changes the built in associated groups by using the spWeb property bag directly, rather than the properties exposed by spWeb - e.g. spWeb.AssociatedGroups.Add(group), or spWeb.AssociatedOwnerGroup = group.

using Microsoft.SharePoint;
 
namespace DevHoleDemo
{
    public static class GroupsHelper
    {
        public enum AssociatedGroupTypeEnum { Owners, Members, Vistors };
 
        public static void AddGroups(SPWeb spWeb, bool copyUsersFromParent)
        {
            spWeb.BreakRoleInheritance(false);
            SPGroup owners = AddGroup(spWeb, AssociatedGroupTypeEnum.Owners, copyUsersFromParent);
            SPGroup members = AddGroup(spWeb, AssociatedGroupTypeEnum.Members, copyUsersFromParent);
            SPGroup vistors = AddGroup(spWeb, AssociatedGroupTypeEnum.Vistors, copyUsersFromParent);
            SPGroup myGroup = AddGroup(spWeb, "My Group", "An example group.", null, null, null, false);
            SetAssociatedGroups(spWeb, new SPGroup[] { owners, members, vistors, myGroup });
        }
 
        public static void SetAssociatedGroups(SPWeb spWeb, SPGroup[] groups)
        {
            string formatString = "";
            object[] ids = new object[groups.Length];
            for (int i = 0; i < groups.Length; i++)
            {
                formatString += string.Format("{{{0}}};", i);
                ids[i] = groups[i].ID;
            }
            spWeb.Properties["vti_associategroups"] = string.Format(formatString.TrimEnd(new char[] { ';' }), ids);
            spWeb.Properties.Update();
        }
 
        public static SPGroup AddGroup(SPWeb spWeb, AssociatedGroupTypeEnum associateGroupType, bool copyUsersFromParent)
        {
            switch (associateGroupType)
            {
                case AssociatedGroupTypeEnum.Owners:
                    return AddGroup(spWeb, spWeb.Name + " Owners", "Use this group to give people full control permissions to the SharePoint site: {0}", "Full Control", "vti_associateownergroup", spWeb.ParentWeb.AssociatedOwnerGroup, copyUsersFromParent);
                case AssociatedGroupTypeEnum.Members:
                    return AddGroup(spWeb, spWeb.Name + " Members", "Use this group to give people contribute permissions to the SharePoint site: {0}", "Contribute", "vti_associatemembergroup", spWeb.ParentWeb.AssociatedMemberGroup, copyUsersFromParent);
                case AssociatedGroupTypeEnum.Vistors:
                    return AddGroup(spWeb, spWeb.Name + " Vistors", "Use this group to give people read permissions to the SharePoint site: {0}", "Read", "vti_associatevisitorgroup", spWeb.ParentWeb.AssociatedVisitorGroup, copyUsersFromParent);
                default:
                    return null;
            }
        }
 
        public static SPGroup AddGroup(SPWeb spWeb, string groupName, string descriptionFormatString, string roleDefinitionName, string associatedGroupName, SPGroup parentAssociatedGroup, bool copyUsersFromParent)
        {
            SPGroup owner = parentAssociatedGroup;
            if (associatedGroupName != "vti_associateownergroup")
                owner = spWeb.SiteGroups.GetByID(int.Parse(spWeb.Properties["vti_associateownergroup"]));
            spWeb.SiteGroups.Add(groupName, owner, null, string.Format(descriptionFormatString, spWeb.Name));
            SPGroup group = spWeb.SiteGroups[groupName];
            if (descriptionFormatString.IndexOf("{0}") != -1)
            {
                SPListItem item = spWeb.SiteUserInfoList.GetItemById(group.ID);
                item["Notes"] = string.Format(descriptionFormatString, string.Format("<a href=\"{0}\">{1}</a>", spWeb.Url, spWeb.Name));
                item.Update();
            }
            if (roleDefinitionName != null)
            {
                SPRoleAssignment roleAssignment = new SPRoleAssignment(group);
                SPRoleDefinition roleDefinition = spWeb.RoleDefinitions[roleDefinitionName];
                roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
                spWeb.RoleAssignments.Add(roleAssignment);
            }
            if (copyUsersFromParent && parentAssociatedGroup != null)
                foreach (SPUser user in parentAssociatedGroup.Users)
                    group.AddUser(user);
            if (associatedGroupName != null)
            {
                spWeb.Properties[associatedGroupName] = group.ID.ToString();
                spWeb.Properties.Update();
            }
            spWeb.Update();
            return group;
        }
    }
}