UserProfileManager.Count – Don’t Count On It!

Published on
-
1 min read

In ASP.NET you would think when you use the “.Count” method that it would be able to simply return the total number of elements within a collection. In majority of cases this is right. Well, apart from when you use the “.Count” method against a collection of profiles within SharePoint. For example:

UserProfileManager profileManager = new UserProfileManager(myContext);

//Get total number of profiles
int numberOfProfiles = profileManager.Count;

I found that I came across two issues when using the code above:

  1. The incorrect number of profiles was returned.
  2. For some reason, when I deployed the code to a live server environment I kept on getting errors from the line where the count was being returned.

From researching this issue on various blog posts and forums, it seems that UserProfileManager.Count does indeed have issues in returning the count correctly. The only way to get around this is to enumerate through the UserProfileManager:

UserProfileManager profileManager = new UserProfileManager(myContext);

int counter = 0;

IEnumerator profileEnumerator = profileManager.GetEnumerator();
while (profileEnumerator.MoveNext())
{
    counter++;
}

//Number of profiles
int totalNumberOfProfiles = counter;

This will give us an accurate number of profiles that are stored within SharePoint and without any silly errors.

Before you go...

If you've found this post helpful, you can buy me a coffee. It's certainly not necessary but much appreciated!

Buy Me A Coffee

Leave A Comment

If you have any questions or suggestions, feel free to leave a comment. I do get inundated with messages regarding my posts via LinkedIn and leaving a comment below is a better place to have an open discussion. Your comment will not only help others, but also myself.