Through this article I am demonstrating how to create groups after activating the feature.
The following are the steps:
Step 1: Create a new Sharepoint solution using VS 2010. Set the feature scope to "Web".
Step 2: Right-click on the feature then add FeatureEventreciever.cs.
Step 3: Add the following code to the 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 following code:
string groupName = "Custom Group";
/// <summary>
/// Method to Attach Event receiver on feature activation.
/// </summary>
/// <param name="properties">SPFeatureReceiverProperties Properties</param>
///
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</param>
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.
Now it's ready. Please let me know if you have any doubt or need clarification.