1

I am uploading a spreadsheet to a task list using visual studio - the sheet will usually have users that are misspelled or incomplete and SharePoint throws a not a user error. I have to go back fix the name and then restart the 1000+ row import.

I see a lot of code to find out who the current user is - what i need is a simple routine to test if a name is a valid user in SharePoint. Preference is CSOM- but REST would be ok...

Goal is to pop up a dialog to correct the name and let the import continue...

2

I currently use this:

 var ctx = new ClientContext(site);
 var rootWeb = ctx.Site.RootWeb;
 var usr = rootWeb.EnsureUser(userName);
 ctx.Load(usr);
 ctx.ExecuteQuery();

usr will have the value for the SharePoint.

SharePoint tries to resolve the user by e-mail, UPN and Name

  • I may be wrong but I think it will throw exception if username is wrong? – Nadeem Yousuf Feb 4 '15 at 11:19
  • Ensure user does usually throw an exception on server side code and so that is likely, yes. – Choggo Feb 4 '15 at 11:21
3

EnsureUser will throw error if the username is incorrect. However, if the username is correct and is not in the site, it will make sure to add it in the site. There doesn't seem to be an elegant way of handling the EnsureUser error but to catch it. Example:

try
{       
    var rootWeb = ctx.Site.RootWeb;
    var user = rootWeb.EnsureUser("adam");
    ctx.Load(user);
    ctx.ExecuteQuery();
    Console.WriteLine("User: {0} Login name: {1} Email: {2}",
            user.Title, user.LoginName, user.Email);
}
catch (Exception ex)
{

}

However, if it is known that all users are already added to the site, then other alternative is to first load UserCollection of all users in the site and then compare the username with that collection. Example:

using (var ctx = new ClientContext("http://aissp2013/sites/Team"))
{
    UserCollection collUser = ctx.Web.SiteUsers;
    ctx.Load(collUser);
    ctx.ExecuteQuery();
    var user = collUser.Cast<User>().FirstOrDefault(u => u.LoginName == "adam");
    if (null != user)
    {           
        Console.WriteLine("User: {0} Login name: {1} Email: {2}",
                user.Title, user.LoginName, user.Email);
    }                               
}
  • 1
    our o365 site had >50000 users - i am affraid that to get all users would be quite the strain - i am investigating a Rest query that could be the answer – user1176574 Feb 5 '15 at 12:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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