How can I efficiently grab users (with their properties) from a SharePoint web using CSOM? The code below results in multiple calls to the server (one for each user). It's ridiculously inefficient.
Also, is it possible to perform a Filter on the server?
public static List<Contact> GetUsers(Uri requestUri, string Filter = "")
{
ClientContext context;
var users = new List<Contact>();
if (ClientContextUtilities.TryResolveClientContext(requestUri, out context, null))
{
using (context)
{
var web = context.Web;
var peopleManager = new PeopleManager(context);
context.Load(web, w => w.Title, w => w.Description, w => w.SiteUsers);
var siteUsers = web.SiteUsers;
context.ExecuteQuery();
foreach (var user in siteUsers)
if (user.PrincipalType == Microsoft.SharePoint.Client.Utilities.PrincipalType.User)
if (user.Title.ToLower().Contains(Filter.ToLower()) && !users.Any(x => x.FullName == user.Title))
{
var userProfile = peopleManager.GetPropertiesFor(user.LoginName);
context.Load(userProfile);
context.ExecuteQuery();
var contact = new Contact() { FullName = user.Title, EmailAddress = user.Email };
if (userProfile.IsPropertyAvailable("Title"))
contact.Position = userProfile.Title;
if (userProfile.IsPropertyAvailable("UserProfileProperties") && userProfile.UserProfileProperties.ContainsKey("WorkPhone"))
contact.PhoneNumber = userProfile.UserProfileProperties["WorkPhone"];
users.Add(contact);
}
}
}
return users;
}