in

SharePoint Blogs

The Best Place for SharePoint-related Blogs

Mirjam's blog

Blogging about SharePoint related stuff

Using SPWeb.EnsureUser(loginName) to add a new SPUser to a web

It happens quite often that I have to write a piece of code to set user permissions on a SharePoint site. One of the challenges you encounter when doing so is that you need to have a valid SPUser object, that is known in the site collection to be able to do this.

If you want to create a new subsite or web you can start out like this:

   // Open an existing site collection
   SPSite portalSite = new SPSite("
http://portal");
   // Create a new subsite (web)
   SPWeb newWeb =
    portalSite.AllWebs.Add("
http://portal/newweb", "My New WebSite", "This is my new web site", 1033, "STS#0", true,
                           false);
   // Get the default roledefinitions known on the new web
   SPRoleDefinitionCollection roleDefinitions = newWeb.RoleDefinitions;
   // Get the roleassignments collections of the new web
   SPRoleAssignmentCollection roleAssignments = newWeb.RoleAssignments;

Next you want to get an SPUser object, so you can give this person the right permissions on the site. Unfortunately there is no way of telling whether you can get this user from the site collection. If the user is known on the site collection there are three ways to get it:

   SPUserCollection users = portalSite.RootWeb.AllUsers;

The description in the SDK for this function is:
"Gets the collection of user objects that represents all users who are either members of the site or who have browsed to the site as authenticated members of a domain group in the site."
This means that if you have a site collection where you have authenticated all domain users by using an Active Directory group and the user we want to give the permissions to has never browsed to the site before this function won't return our user.

Next try:

   SPUserCollection users = portalSite.RootWeb.SiteUsers;

The SDK about this one:
"Gets the collection of all users that belong to the site collection."
Which means users explicitly added to the site collection.

And the last one:

   SPUserCollection users = portalSite.RootWeb.Users;

The SDK about this one:
"Gets the collection of user objects that are explicitly assigned permissions on the Web site."
So this only gets us the users that are explicitly to the web. And since we are actually trying to assign our user to the web we won't find him in this collection.

The way to solve this problem is to user SPWeb.EnsureUser(loginName) (I have to thank Donald for finding the solution!). The description in the SDK for EnsureUser is:
"Checks whether the specified login name belongs to a valid user of the Web site, and if the login name does not already exist, adds it to the Web site." Which happens to be exactly what we want!
Now we can finish our code:

   SPUser newUser = newWeb.EnsureUser(@"domain\username");
   newWeb.AllowUnsafeUpdates = true;

   // Create the new roleassignment that we want to add to the collection of roleassignments of the new web
   SPRoleAssignment roleAssignment = new SPRoleAssignment(newUser);
   SPRoleDefinitionBindingCollection roleDefBindings = roleAssignment.RoleDefinitionBindings;
   // Add the binding to the correct roledefinition to the roleassignment
   // This can also be Contribute for contributor rights.
   // Keep in mind that in sites in other languages this needs to be translated
   roleDefBindings.Add(roleDefinitions["Read"]);
   roleAssignments.Add(roleAssignment);
   
   newWeb.AllowUnsafeUpdates = false;

   newWeb.Dispose();
   portalSite.Dispose();

 Happy programming!

Published Dec 20 2007, 04:30 PM by Mirjam
Filed under: ,

Comments

 

Donald Hessing said:

Excellent spoken!

December 20, 2007 10:41 AM
 

Links (12/20/2007) « Steve Pietrek’s SharePoint Stuff said:

Pingback from  Links (12/20/2007) « Steve Pietrek’s SharePoint Stuff

December 20, 2007 8:08 PM
 

Blog del CIIN said:

Una vez más, en esta nueva entrega recogemos el recopilatorio de enlaces, recursos y diferentes elementos

December 23, 2007 4:06 PM
 

David M. Sterling said:

Good job! I happened across a little problem while converting some code - was getting "Operation is not valid due to the current state of the object." when adding a user to a SharePoint web (as in Web.Users.Add()). I'd forgotten about the EnsureUser option which eliminated the problem.

February 8, 2008 8:10 AM
 

Adarsh Nair said:

Mirjam, that was a great help for me in finding the groups collection for a logged in user. Thanks.

May 21, 2008 1:38 AM
 

Taras said:

Very useful article.

Thanks, Mirjam.

July 2, 2008 10:53 AM
 

DkmS's блог said:

Попытался использовать в форме стандартный контрол UserField. Нашлась неплохая статеечка на эту тему....

August 19, 2008 8:59 AM

Leave a Comment

(required )  
(optional )
(required )  
Add

About Mirjam

Mirjam van Olst works as a lead SharePoint developer at Macaw in the Netherlands. She started working for Macaw in April 2004. Before that she had her own company (Van Olst Websolutions) with which she build web applications. Mirjam has specialized in SharePoint development since June 2004. She started working with the 2007 Office system in may 2006. She has implemented several world-wide intranet environments based on SharePoint. She also gives presentations about MOSS 2007 on a regular basis and occasionally writes articles about MOSS related subjects.

Need SharePoint Training? Attend a SharePoint Bootcamp!

Posts (c) their respective authors. Everything else (c) 2007 SharePoint Experts