Archive

Posts Tagged ‘EnsureUser’

SharePoint: Wrapper over EnsureUser

May 3rd, 2011 No comments

     When I needed to get SPUser-object I always utilized SPWeb.EnsureUser method. EnsureUser looks for the specified user login inside SPWeb.SiteUsers collection, and if the login isn’t found, turns to ActiveDirectory for the purpose of retrieving the user information from there. If such information is found, it will be added to SPWeb.SiteUsers and for the next time it will be returned directly from SPWeb.SiteUsers.

So, we have the fact that when EnsureUser is called, SPWeb-object potentially can be changed (changes affect SPWeb.SiteUsers collection, to be more precise). Each time we change SPWeb-object, it’s highly recommended to make sure that SPWeb.AllowUnsafeUpdates = true. It’s especially topical, when EnsureUser is called from Page during GET-request (Page.IsPostback = false). Otherwise, “Updates are currently disallowed on GET requests. To allow updates on a GET, set the ‘AllowUnsafeUpdates’ property on SPWeb” is thrown.

I’ve implemented some wrapper over the standard SPWeb.EnsureUser:

public static SPUser SafeEnsureUser(SPWeb web, string loginName)
{
    SPUser res = null;
    if (!web.AllowUnsafeUpdates)
    {
        bool oldAllowUnsafeUpdate = web.AllowUnsafeUpdates;
        try
        {
            web.AllowUnsafeUpdates = true;
            res = web.EnsureUser(loginName);
        }
        catch (Exception ex)
        {
            // write to log
        }
        finally
        {
            web.AllowUnsafeUpdates = oldAllowUnsafeUpdate;
        }
    }
    else
        try
        {
            res = web.EnsureUser(loginName);
        }
        catch(Exception ex)
        {
           // write to log
        }

    return res;
}

SafeEnsureUser checks whether web.AllowUnsafeUpdates is true. If yes, it just invoke standard EnsureUser. Otherwise, it preset web.AllowUnsafeUpdates to true and then invoke standard EnsureUser. Nowadays, everywhere I use this method instead of standard one.

If you need an extension for SPWeb-object, try this

public static SPUser SafeEnsureUser(this SPWeb web, string loginName)
{
	// the same method body
}
Related posts: