SharePoint 2010: Writing User Profile Properties Programatically

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;

}

});

Advertisement

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 )

Facebook photo

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

Connecting to %s