Introduction
On regular SharePoint sites development, we need to fetch the SharePoint user-profiles to grid or some other operations. Recently, We had faced an performance issue for retrieval of SharePoint user-profiles. I tried to address the issue and resolution what we did.
Issue:
We have 2000+ users in Active Directory group and AD group is mapped to a SharePoint group. We need to fetch all the user-profile information for the SharePoint group and show them to a grid. Initially we had written the code as
List<UserProfile> uspList = new List<UserProfile>();
SPSecurity.RunWithElevatedPrivileges(delegate()
{
var serviceContext = SPServiceContext.GetContext(site);
var upm = new UserProfileManager(serviceContext );
List<string> listUsers = (users account name from SharePoint Group);
foreach (var userAccountName in listUsers)
{
UserProfile profile = null;
try
{
profile = upm.GetUserProfile(userAccountName);
}
catch (UserNotFoundException ex)
{
continue;
}
if (profile != null)
{
uspList.Add(profile);
}
}
});
retutn uspList;
The code was fetching all user profile information for each SharePoint group user using GetUserProfile method. The operation was taking about 4-5 minutes. We tried to optimize the performance and look for solution then we found UserProfileManager context object has already have the all user-profiles in it. Just we need to loop through the context object user-profile list (with a check of whether user belongs to group) instead of calling GetUserProfile for each user.
Solution:
SPSecurity.RunWithElevatedPrivileges(delegate()
{
List<string> lstUsers = (users account name from SharePoint Group);
lstUsers = lstUsers.Select(x => x.ToLower()).ToList();
lstUsers = lstUsers.Where(x => x.Contains("|")).Select(x => x.Split('|')[1]).ToList();
foreach (UserProfile userProfile in upm)
{
UserProfileValueCollection profileValue = userProfile[PropertyConstants.AccountName];
if (profileValue != null && profileValue.Value != null && lstUsers.Contains(profileValue.Value.ToString().ToLower()))
{
uspList.Add(userProfile);
}
}
});
After the optimization, the execution time reduced to seconds.
Conclusion
Calling GetUserProfile method for bulk users is costly operation so use the above code. If we need only single user profile information, use GetUserProfile method.
Note: Here we have not covered, how to fetch list of account names from SharePoint group. Out intention is to improvise the performance on getting user profiles.