Geeks With Blogs
Fringe SharePoint Continued
Adding a new user to a site looks like this:

public static void AddPrincipalRoleToSite(SPPrincipal entity, SPRoleType role, SPWeb web)
{
    SPRoleAssignment roleAssignment = new SPRoleAssignment(entity);
    SPRoleDefinition byType = web.RoleDefinitions.GetByType(role);
    roleAssignment.RoleDefinitionBindings.Add(byType);
    web.RoleAssignments.Add(roleAssignment);
}

Principle is the parent object to SPUser and SPGroup. Therefore you can use this method and send both user or group in and it will add it to the site.

In terms of the 'role'. If you send in an enum of the type SPRoleType.Contributor it will work. The SPRoleType has the typical permission levels that ships with MOSS or WSS 3.0. Administrator, Contributor, Guest, None, Reader, WebDesigner.

But what if you create a custom permission level? how do you add that? Well, you can do it like this:

private void AddCustomPermissionToSite(SPWeb web, SPPrincipal entity, string roleName)
        {

            SPRoleAssignment roleAssignment = new SPRoleAssignment(entity);
            SPRoleDefinition byType =web.ParentWeb.RoleDefinitions[roleName];
            roleAssignment.RoleDefinitionBindings.Add(byType);
            web.RoleAssignments.Add(roleAssignment);

        }

In this case you will add the name of your Permission name, be careful cause it is real finiky. If you created a permission level called , "My Custom Permission Level" , you will get an error if you send in "My Custom Permission Level ". Notice the space at the end?? It is not doing a 'Contains' for string match, it's really the name of the permission level it's matching , the exact one.

If you hare having issues, debug and see all the RoleDefinitions in that object. You will have access to the XML that includes the name, id, etc...

Good luck

Juan Posted on Friday, September 4, 2009 5:13 PM SharePoint | Back to top


Comments on this post: Giving user access to site with custom permission level

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © juanlarios | Powered by: GeeksWithBlogs.net