How to: autoset values for user profile properties in SharePoint 2010

If you have a piece of functionality which stores its data in SharePoint 2010 user profile properties, you will likely need to pre-set the initial values for your users so that your component works properly for the fitst time.

In this post I will show you how to create and set custom user profile properties for a batch of users.

We’ll start with creating a property using SharePoint Central Admin UI.

1. In Central Admin navigate to Manage service applications -> User profile service application. If you have several User profile service application proxies, select the one which is associated to the site collection your user wil be accessing to.
2. Click Manage User Properties and click New Property from the following page.
3. In the Create new property page, specify values describing your property as you see fit.
One thing to note here, is that value types have their own intricacies when working with them in code. For example, Multi Value type will separate your content with a semicolon or a comma but you can’t write those respective characters in your code. You can, though, write them in the user profile UI.

Next, populating of your property values in code. We’ll use Visual feature receiver to write to the property of a given user in code.

1. Start with adding the User Profile reference namespace.

using Microsoft.Office.Server.UserProfiles;

2. Here is how we update the profile property value of property named “MyProperty”

SPServiceContext serviceContext = SPServiceContext.GetContext([siteCollection]);

UserProfileManager userProfileManager = 
UserProfile userProfile = userProfileManager.GetUserProfile([UserName]);

userProfile["MyProperty"].Add("some value");
userProfile["MyProperty"].Add("this value will be comma separated");

Above, we get a hold of the profile loader and load a profile for a given user “domain\username”. You can iterate here to fill properties of other users if you need to.
Since our profile property is a multi value property in this example, each new line is added with an Add method. This doesn’t apply to single line of text property etc.

When done, we commit the batch.
That’s it, enjoy!

About the author: Yaroslav Pentsarskyy