Ads

Thursday, 28 March 2013

C# to create custom sharepoint group through feature in SharePoint2010

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: Now we can deploy this in your server.

No comments:

Post a Comment

Ads