Through this article I am demonstrating how to create groups once you activate the feature.
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</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 its ready. Please let me know if you have any doubt or need clarification.
hi
ReplyDeletei want to create multiple groups in one feature, would please tell me.
Thanks
Hi,
DeleteUse this method for group creation:
CreateSubSiteGroup(web, groupName, premissionLevel, groupDescription);
It upto you that how many groupName you are passing.On feature activationmcall this method with groupName for group creation.
Please let me know if you have any issue.
Thanks
Ravi