Friday, 7 May 2010

Work around ServerContext en UserProfile troubles

I struggled some time with working with the UserProfile and ServerContext inside SharePoint (MOSS 2007).
I wrote a web part to show more details of a sitecontact. For that, I needed to get details from the UserProfile. The UserProfile was obtained from the UserProfileManager.
The code (web part) was running fine on the SharePoint server itself, but it failed on a client machine.
After struggling a lot, trying different suggestions (like fake SPContext and so on) today I found the solution. You need to use the SPSecurity.RunWithElevatedPrivileges method. RunWithElevatedPrivileges runs the code in the brackets under the SharePoint System Account.
So here is the piece of code I am using:

using (SPSite site = new SPSite(SPContext.Current.Site.ID))
ServerContext context = ServerContext.GetContext(site);
HttpContext currentContext = HttpContext.Current;
HttpContext.Current = null;

UserProfileManager profileManager =
new UserProfileManager(context);

UserProfile user =

PropertyCollection propCollection =

if (user != null && propCollection != null)
\\ do your stuff with the 'user'
HttpContext.Current = currentContext;
catch (Exception)
\\ handle the exception

I used this code for retrieving userprofile details. I didn't try to edit the user profile. But I assume it should work as well.

1 comment:

mnateras said...

Thanks my save me the day