For a custom functionality I’m developing for my customer I needed to retrieve the user profile logged on the application. To accomplish this task SharePoint object model provides the class UserProfileManager which allows you to query user profile properties.
There is only a tip when you write your code to access the user profile properties, in fact you can use two different piece of code to accomplish that:
- if you instance a new UserProfileManager (see the commented code below on 7th row) you could have problem and receive the following error:
“You must have manage user profiles administrator rights to use administrator mode.”
This is due to the fact that to instance a UserProfileManager you need administration right on SharePoint Shared Service.
- Instead of the creation of a new instance of UserProfileManager class, you can get an already present instance using ProfileLoader class (see row 8, 9 and 10 below). In this way you can access to a read-only version of UserProfileManager class which permits you to query every properties of the user profile you have requested (see all the example below).
1: public UserProfile GetUserProfile(string loginName)
3: UserProfile userProfile;
4: using (var Site = new SPSite(SiteId))
6: var ctx = ServerContext.GetContext(Site);
7: //var upm = new UserProfileManager(ctx, true);
8: var profile = ProfileLoader.GetProfileLoader(ctx);
9: var upm = profile.GetUserProfileManager();
10: var spUserProfile = upm.GetUserProfile(loginName);
12: userProfile = new UserProfile(spUserProfile.ID)
14: Login = loginName,
15: PreferredName = spUserProfile["PreferredName"] != null ?
16: spUserProfile["PreferredName"].Value as string : string.Empty,
18: Manager = spUserProfile["Manager"] != null ?
19: spUserProfile["Manager"].Value as string : string.Empty,
21: Name = spUserProfile["FirstName"] != null ?
22: spUserProfile["FirstName"].Value as string : string.Empty,
24: Surname = spUserProfile["LastName"] != null ?
25: spUserProfile["LastName"].Value as string : string.Empty
30: return userProfile;
Particular thanks to my friend Michele who supported and suggested me on how to resolve this problem.