Create Groups Programmatically and Assigning Permissions

Leave a Comment
The following example will demonstrate how to create Groups Programatically and Assign Permission to them in SharePoint.

public static void CreateGroups()
        {
            try
            {
                BClass obj = new BClass();
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite oSite = new SPSite(SPContext.Current.Site.Url))
                    {
                        using (SPWeb oWeb = oSite.OpenWeb())
                        {
//Get the groups from the another method
                            List<string> groups = obj.GetGroups();
                            if (groups.Count > 0)
                            {
                                foreach (string groupName in groups)
                                {
                                    oWeb.AllowUnsafeUpdates = true;
                                    string sGroup = string.Empty;
                                    SPGroup group = oWeb.SiteGroups.Cast<SPGroup>().FirstOrDefault(x =>                                                                                                                            x.Name == sGroup);
if(group==null)
{
                                     // creating new group to site
                                            oWeb.SiteGroups.Add(sGroup, oWeb.CurrentUser,                                                                                                      oWeb.CurrentUser,"Description of the group ");
}
                                    group = oWeb.SiteGroups[sGroup];
                                    SPRoleDefinition roleDefinition = oWeb.RoleDefinitions["Read"];
                                    SPRoleAssignment roleAssigment = new SPRoleAssignment(group);
                                    // Assigning roles to the group
                                    roleAssigment.RoleDefinitionBindings.Add(roleDefinition);
                                    oWeb.RoleAssignments.Add(roleAssigment);
                                    oWeb.Update();
                                    oWeb.AllowUnsafeUpdates = false;
                                }
                            }
                        }
                    }
                });
            }
            catch (Exception ex)
            {
               //Error logging
            }
        }

Related Post

0 comments:

Post a Comment