Friday, March 20, 2009

How to create a new user for an SPWeb

It seems that if a user needs to be added to a SPWeb object one should just call SPWeb.Users.Add. Unfortunately, this does not work and you will get an exception.  To add a user correctly you need to define the users access rights. This is most easily done using the predefined roles.  Here is a small foreign method that does the job correctly.

private void AddUser(SPWeb web, SPRoleType roleType, string login, string email, string name, string notes)
{
    SPRoleDefinition roleDefinition = web.RoleDefinitions.GetByType(roleType);
    SPRoleAssignment roleAssignment = new SPRoleAssignment(login, email, name, notes);
    roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
    web.RoleAssignments.Add(roleAssignment);
}

Remember to always get SPRoleDefinition objects using the SPRoleDefinitionCollection.GetByType method and never using the [string] indexer.  The indexer takes the localized name of the role. Using a string like “Viewer” will work in English but will not in any other language. SPRoleType is an enumeration that is locale independent.

No comments:

Post a Comment