Thursday, December 13, 2012

Adding SP Group Programatically and adding users to the group

 protected void btnCreateGroup_Click(object sender, EventArgs e)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite selectedSubSite = new SPSite(ddlSubsite.SelectedValue))
                using (SPWeb selectedWeb = selectedSubSite.OpenWeb())
                {
                    SPUser owner=null;
                    if(selectedWeb.SiteAdministrators.Count>0)
                    {
                        owner = selectedWeb.SiteAdministrators[0];
                    }

                    else
                    {
                        owner = selectedSubSite.SystemAccount;
                    }

                    SPMember member =owner;
                    string[] gropuArray = new string[1];
                    gropuArray[0] = txtGroupName.Text;
                    SPGroupCollection groupCollection = selectedWeb.SiteGroups.GetCollection(gropuArray);
                    SPGroupCollection groups = selectedWeb.SiteGroups;
                    if (groupCollection.Count == 0)
                    {
                        groups.Add(txtGroupName.Text, member, owner, "test");
                    }
                    SPGroup newSPGroup = groups[txtGroupName.Text];
                    //Associate the group to the SPWeb.
                    //This will add the SPGroup to left side quicklaunch of Manage Groups page 
                    selectedWeb.AssociatedGroups.Add(newSPGroup);
                    selectedWeb.Update();
                    SPRoleDefinition role = selectedWeb.RoleDefinitions["Contribute"];
                    SPRoleAssignment roleAssignment = new SPRoleAssignment(newSPGroup);
                    roleAssignment.RoleDefinitionBindings.RemoveAll(); 

                    roleAssignment.RoleDefinitionBindings.Add(role);
                    //  selectedWeb.RoleAssignments.Add(roleAssignment); // this is applicable only for unique permission sites.
                    newSPGroup.Update();
                 selectedWeb.Update();
 
                      
                    }
                
            });

        }

No comments:

Post a Comment