Programmatically Create SharePoint Group Using Feature

Posted By:Jayasankar Kesarla    Posted Date: May 05, 2014       Category: SharePoint    URL: http://www.dotnetspark.com


This article will demonstrate how to create custom group in sharepoint2010 on feature activation.






Hi All,
Through this article I am just going to demonstrate how to create a feature for creating group.
Below are the steps:
Step 1. Create a new sharepoint solution using VS2010.Set you feature scope as "Web".
step 2. Right Click on feature,Add FeatureEventreciever.cs.
Step 3: Add the below code in FeatureEventreciever.cs class
For Creating group:

/// <summary>

/// Create group

/// </summary>

public static void CreateSubSiteGroup(SPWeb web, string groupName, string PermissionLevel,string groupDescription)

{

    SPUserCollection users = web.AllUsers;

    SPUser owner = web.SiteAdministrators[0];

    SPMember member = web.SiteAdministrators[0];

    SPGroupCollection groups = web.SiteGroups;

    groups.Add(groupName, member, owner, groupDescription);

    SPGroup newSPGroup = groups[groupName];

    SPRoleDefinition role = web.RoleDefinitions[PermissionLevel];

    SPRoleAssignment roleAssignment = new SPRoleAssignment(newSPGroup);

    roleAssignment.RoleDefinitionBindings.Add(role);

    web.RoleAssignments.Add(roleAssignment);

    web.Update();

 

}

For Deleting Group

/// <summary>

/// Delete group for subsite

/// </summary>

public static void DeleteSubSiteGroup(SPWeb web, string groupName)

{

    SPGroupCollection groups = web.SiteGroups;

    groups.Remove(groupName);

    web.Update();

 

}

Step 4: Add the below code

string groupName="Custom Group";

 

/// <summary>

/// Method to Attach Event receiver on feature activation.
 /// </summary>

/// <param name="properties">SPFeatureReceiverProperties Properties

///

public static void FeatureActivated(SPFeatureReceiverProperties properties)

{

              string groupDescription="My Custom Group";

   try

    {

        using (SPWeb web = properties.Feature.Parent as SPWeb)

        {

             CreateSubSiteGroup(web, groupName, premissionLevel,groupDescription);

                           }

       

         

    }

    catch (Exception ex)

    {

       ex.Message;

    }

}

 

/// <summary>

/// Method to Remove Event receiver on feature deactivation.

/// </summary>

/// <param name="properties">SPFeatureReceiverProperties Properties

public static void FeatureDeactivating(SPFeatureReceiverProperties properties)

{

       try

    {

                        using (SPWeb web = properties.Feature.Parent as SPWeb)

        {

            

                DeleteSubSiteGroup(web, groupName);

                           }

    }

    catch (Exception ex)

    {

        ex.Message;

    }

}

Step 5: That's it.Deploy this in your server.

Comments