Search code examples
sharepointsharepoint-2010

EnsureUser not returning valid User


I am trying to get a user back in SharePoint Client OM using EnsureUser. My code is:

ClientContext clientContext = new ClientContext(siteUrl);
User spUser = clientContext.Web.EnsureUser(user);

Where siteUrl and user are both strings set as appropriate.

The result is spUser is the shell of a User object but all its properties (for example Email, Title, etc.) are not initialized. In VS they are showing {"The property or field has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested."}

What would be causing this? I thought EnsureUser would create the user if it is not already there. I know in Server OM sometimes you need to use "AllowUnsafeUpdates", is there something like that for Client OM?


Solution

  • It is almost a year late, but just in case someone else is searching for the same answer. After getting a reference to the user object you need to do the following before accessing the properties of the user.

    clientContext.Load(spUser);
    clientContext.ExecuteQuery();
    

    or if you want to get the email and title only to reduce the pay load.

    clientContext.Load(spUser, u => u.Email, u => u.Title);
    clientContext.ExecuteQuery();
    

    Basically, it establishs a request to the SharePoint Web and ask for the properties of the spUser. The request will be send when ExecuteQuery() is called.