UserProfile.GetManagers : “An error was encountered while retrieving the user profile”

I was trying to get the managers of a SharePoint user, and I kept getting the error:

An error was encountered while retrieving the user profile

This was from a custom workflow step in an automatically started workflow. If I ran the workflow manually, it worked – but auto-started workflows failed.

My code was inside an elevated privileges block:

SPServiceContext context = SPServiceContext.GetContext(site);
UserProfileManager upm = new UserProfileManager(context);
UserProfile up = upm.GetUserProfile(user);
UserProfile[] managers = up.GetManagers();

I thought permissions was the issue at first, but it was weird – permissions are rarely an issue inside elevated privileges, and why was the problem with GetManagers specifically? I could get the user’s profile okay.

Eventually, I found this helpful post by Paul Ewert. Just in case that goes offline, here’s the important bit:

Turns out, deep down in this routine a stored procedure is called in the User Profile Service Profile DB that is also used for finding two users’ first common manager. Only, GetManagers() doesn’t care about the common manager data that is returned. Still, it is required that both users (the user executing the method and the user being looked up) have profiles in order to execute the stored procedure.

Lord knows how Paul figured that out, but kudos.

When running automatically, my workflows don’t have a user’s profile – they’re using a system account, which lacks a UserProfile, so the call to GetManagers() fails. Instead, I used GetManager() and looped myself, which seemed to work.

UserProfile manager = up.GetManager();
List processedManagers = new List();
while ((manager != null) && (!processedManagers.Contains(manager.ID)))
{
SetItemPerms(web, item, manager, "Read");
processedManagers.Add(manager.ID);
manager = manager.GetManager();
}

Advertisements
UserProfile.GetManagers : “An error was encountered while retrieving the user profile”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s