Wednesday, December 23, 2015

Using SPWeb.EnsureUser in SharePoint

I faced this scenario many times and when I Googled, there are many who have faced the same. I had added an Active Directory group to the site members group. Then I asked them to log in and make requests for a particular business scenario that triggered workflows. I had a scenario that another user could make a request on behalf of another. Simply someone is asking to reset an AD account of a person who lost his password. Given that there is a need to add a new list column called 'On Behalf Of' which is a person or group column, I simply used code to create an SPUser object through C# code using the people picker value where people picker was available in the request form to select the on behalf of user. 

I got the username from the people picker comma separated values and used the following code to get the user.

SPUser onBehalfOfUser = web.AllUsers[onBehalfOfuserLoginName];

Some worked well and suddenly an error occurred saying the on behalf of user is null. I had the AD user group in the site members group. But the user who was selected has not accessed the site under any circumstances. Therefore the user was not added to the site users. Simply was not in the User Information List.

Then after doing some research, I used the SPWeb.EnsureUser method in order to create the SPUser object. 

Behind the scene the EnsureUser method adds the user to the particular site and then add to the list column for storing. Therefore the time the SPUser object is initialized, the user was in the site already. Since then I thought of using EnsureUser method all the time as it is safer than finding nulls unexpectedly. 

No comments:

Post a Comment