Tuesday, November 12, 2013

Add new role to SPgroup


Sometimes, you will need to programmatically add new roles and permissions to groups on your website.
Here is a sample of code I used : 


Code:
using (SPSite freshsite = new SPSite("http://siteUrl"))
{
    using (SPWeb freshweb = freshsite.OpenWeb())
    {
        SPGroup visitorsGroup = freshweb.SiteGroups["Group Name"];
        SPRoleAssignment visitorsRoleAssignment = new SPRoleAssignment(visitorsGroup);
        SPRoleDefinition readRoleDefinition = freshweb.RoleDefinitions["Read"];

        visitorsRoleAssignment.RoleDefinitionBindings.Add(readRoleDefinition);

        freshweb.RoleAssignments.Add(visitorsRoleAssignment);

        freshweb.Update();
     }
}

The default values of SPRoleDefinitions are : Limited Access, Design, Read, Contribute and Full Control.

Note that you may need to break role inheritance before adding the new SPRoleAssignment to your SPWeb


Code:
if (!freshweb.HasUniqueRoleAssignments)
{
    freshweb.BreakRoleInheritance(true);
}

No comments:

Post a Comment