SharePoint Blogs / SharePoint University
SharePoint Blogs and SharePoint University - all in one place!
Need SharePoint Training? Attend a SharePoint Bootcamp!

Please delete cookies related to sharepointblogs.com and sharepointu.com to resolve login issues!

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!


Posted 12-20-2007 4:30 PM by Mirjam

Comments

Donald Hessing wrote re: Using SPWeb.EnsureUser(loginName) to add a new SPUser to a web
on 12-20-2007 10:41 AM

Excellent spoken!

Links (12/20/2007) « Steve Pietrek’s SharePoint Stuff wrote Links (12/20/2007) « Steve Pietrek’s SharePoint Stuff
on 12-20-2007 8:08 PM

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

Blog del CIIN wrote WSS 3.0 & MOSS: Recopilación de enlaces interesantes (XII)
on 12-23-2007 4:06 PM

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

David M. Sterling wrote re: Using SPWeb.EnsureUser(loginName) to add a new SPUser to a web
on 02-08-2008 8:10 AM

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.

Adarsh Nair wrote re: Using SPWeb.EnsureUser(loginName) to add a new SPUser to a web
on 05-21-2008 1:38 AM

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

Taras wrote re: Using SPWeb.EnsureUser(loginName) to add a new SPUser to a web
on 07-02-2008 10:53 AM

Very useful article.

Thanks, Mirjam.

DkmS's блог wrote Опять сюрприз...
on 08-19-2008 8:59 AM

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

DkmS's блог wrote Опять сюрприз...
on 12-16-2008 5:58 AM

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

Adding a new SPUser to a Web « Alex’s SharePoint Blog wrote Adding a new SPUser to a Web « Alex’s SharePoint Blog
on 01-06-2009 3:35 AM

Pingback from  Adding a new SPUser to a Web « Alex’s SharePoint Blog

Jeffrey wrote re: Using SPWeb.EnsureUser(loginName) to add a new SPUser to a web
on 01-21-2009 8:34 PM

great job, i solved a hard issue after read your article

Add a Comment

(required)  
(optional)
(required)  
Remember Me?
Need SharePoint Training? Attend a SharePoint Bootcamp!
Posts (c) their respective authors. Everything else (c) 2009 SharePoint Experts, Inc.