sharepointcsomsharepoint-apps

How to check if user with a specific ID exists?


I have to loop through all Rows in a table that contain a user field. I have to retrieve those users and do nasty stuff with them:

private void GetUsrInfo(FieldUserValue user, ClientContext clientContext) {
    int id=user.LookupId;

    Web web = clientContext.Web;
    User spuser = web.GetUserById(id);
    clientContext.Load(spuser);
    clientContext.ExecuteQuery();
    Mail = spuser.Email;
}

This works. However these are "old" entries and a lot of these persons do not even exist anymore. The user-field still contains the data of that now abandoned user, but when I try to retrieve the userdata by GetUserById() I retrieve the following exception:

Microsoft.SharePoint.Client.ServerException: User cannot be found.
at Microsoft.SharePoint.Client.ClientRequest.ProcessResponseStream(Stream responseStream) at Microsoft.SharePoint.Client.ClientRequest.ProcessResponse()

Currently I just catch these Exceptions and proceed to the next user. But this is bad and very slow. Is there a more smart way? Anything like "if web.UserExists(id)..."?


Solution

  • EDIT

    One possible way to check whether or not the user exists, without throwing an error or creating a new user (as result of the web.EnsureUser(@"domain\username") method) is to load the complete collection of users locally and use a LINQ statement to lookup the user by Id.

    For example:

    UserCollection collUser = ctx.Web.SiteUsers;
    ctx.Load(collUser);
    ctx.ExecuteQuery();
    var user = collUser.Cast<User>().FirstOrDefault(u => u.Id == 1);
    if (null != user)
    {           
        Console.WriteLine("User: {0} Login name: {1} Email: {2}",
                user.Title, user.LoginName, user.Email);
    }       
    

    If there is a record where the ID == 1, it will be returned, if not the return value will be null.

    Depending on the number of users in the site, this may have performance concerns, however, based on the number of exceptions you expect to generate checking the user ID, this solution may be feasible.

    Reference: Csom or rest to verify user