0

How can handle null exception while copying item from source to destination list as MGR and Account may have users which are not available in organization

var employee = contextDestination.Web.EnsureUser(((FieldUserValue)SourcelistItem["Account"]).LookupValue);
                    var supervisor = contextDestination.Web.EnsureUser(((FieldUserValue)SourcelistItem["Functional_x0020_Manager0"]).LookupValue);

                    contextDestination.Load(supervisor, user => user.Id);

                    contextDestination.Load(employee, user => user.Id);
                    contextDestination.ExecuteQuery();

1 Answer 1

1

By Default EnsureUser method will throw an exception only if user is not found so you need to handle it via try and catch.

You can create one extension method in your solution as shown below:

    static class ExntesionMethods 
    {
        public static User EnsureUserWithNullHandle(this Web web,string userName)
        {
            User user = null;
            try
            {
                user =  web.EnsureUser(userName);
                web.Context.Load(user, u => user.Id);
                web.Context.ExecuteQuery();
            }
            catch 
            {
                // User Is Not found
                user = null;
               
            }
            return user;
        }
    }

Now you can use this method with Web object throughout your application which will always return null if user is not exist.

var employee = contextDestination.Web.EnsureUserWithNullHandle(((FieldUserValue)SourcelistItem["Account"]).LookupValue);            
var supervisor = contextDestination.Web.EnsureUserWithNullHandle(((FieldUserValue)SourcelistItem["Functional_x0020_Manager0"]).LookupValue);

// Now here before using it you can check whether user object is null or not.
// And you don't need to load User Id here as we have already loaded it in Extended method            
//contextDestination.Load(supervisor, user => user.Id);
//contextDestination.Load(employee, user => user.Id);
//contextDestination.ExecuteQuery();

Hope it will helpful to you and you can mark this as answer if it works for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.