Recently I’ve been working on an application which writes custom properties to the User Profile Manager. If you try write profile properties, you may get an error stating that you must allow unsafe updates. The main issue here is the HttpContext needs to be null, but we must store the HttpContext for the session, prior to updating the changes to the user profile manager, and then set the HttpContext back to the original context.
The C# code below enables you to write a user profile property without recieving the error:
currentUser = SPContext.Current.Web.CurrentUser.ToString().Substring(SPContext.Current.Web.CurrentUser.ToString().IndexOf(“\\”) + 1);
SPSite spSite = SPContext.Current.Site;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
System.Web.
HttpContext currentContext = System.Web.HttpContext.Current;System.Web.
HttpContext.Current = null;
try
{
// Set the context of the site to the SPSite site
SPServiceContext context = SPServiceContext.GetContext(spSite);
//Create and instance of the UserProfileManager
UserProfileManager profileManager = newUserProfileManager(context);
UserProfile userProfile = profileManager.GetUserProfile(userName);
UserProfile[propertyName].Value = propertyValue;
userProfile.Commit();
}
catch (SPException ex)
{
}
finally
{
System.Web.HttpContext.Current = currentContext;
}
});