Monday, March 15, 2010

SharePoint SPWeb.EnsureUser

MSDN Definition: 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.

This method can not be called by everyone, as it requires some high level permissions. Your solution is to wrap the EnsureUser within RunWithElevatedPrivileges call.

According to the SharePoint SDK it should be enough to call in your code:

using (SPSite site = new SPSite(""))
using (SPWeb web = site.OpenWeb())
string login = "MyUserName";
string groupName = "MyGroup";
SPUser user = web.EnsureUser(login);
SPGroup group = web.Groups[groupName];

The above code works correctly: the EnsureUser method returns a valid SPUser object which can be added to the MyGroup group.

If you run the above piece of code with Forms Based Authentication (FBA), all you see is an SPException: SharePoint cannot find the user.

Surprisingly the same piece of code executed from a control or an Application Page runs correctly.

At some point the Roles class tries to retrieve the system.web/roleManager configuration section. Because that section is available in the web.config of a Web Application with FBA configured, the code works properly. But for Console Applications it doesn't. What you can do is to create a config file like ConsoleApplication1.exe.config (assuming that ConsoleApplication1.exe is the name of your executable after building) and copy there that particular piece of configuration from your web.config. If you run your Console Application now, it should work perfectly.


To add an User to SharePoint Group, we need to add the User to the Site Collection. For instance if we write the following lines of code to add user to a group, if will throw error is user does not exist.


To resolve this, we can easily use the following line of code:

SPUser userTemp = web.EnsureUser(item);

If the user is known on the site collection there are three ways to get it:

1. 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.

SPUserCollection users = portalSite.RootWeb.AllUsers;

2. Gets the collection of all users that belong to the site collection.

SPUserCollection users = portalSite.RootWeb.SiteUsers;

3. Gets the collection of user objects that are explicitly assigned permissions on the Web site.

SPUserCollection users = portalSite.RootWeb.Users;

Additional References: