UserProfileManager.Count – Don’t Count On It!

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.

blog comments powered by Disqus

About

Surinder Bhomra is a Web Developer.

He has achieved a BSc in Information Systems in 2006 and since then has been working in the IT industry.

Prior to working in the Web Development industry I have spent 1.5 years working as an IT Systems Analyst providing support for internal company systems.

Working in the Web Development industry has given me the opportunity to expand my current skills and allowing me to work on website projects using ASP, ASP.NET, CSS, HTML and SQL.

StackOverflow Flair

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.

>