UserProfile and ChoiceLists, reading and saving

Last few days I have been struggling with a piece of code that should update a UserProfile.
The idea was to make a nice feature that allows a WebPart to display a link that would
open a screen showing the user some options to change UserProfile values. Those change
options should be rendered based on three pieces of information; a Site Column containing
possible values, a ControlType and the UserProfileProperty to save it to.

The first few versions worked pretty well since I only had to save strings or checkboxes,
however further along the way I decided that ChoiceLists from the UserProfile should
be supported, and there it all went wrong, even with Google it took me quite some
time figuring out how to do it, so here a few tips:

Saving a single value to a UserProfileProperty even when its a ChoiceList is pretty
easy:

userprofile[item.Key].Value = item.Value;

Saving multiple values to a userProfileProperty took me some more time, but finally
even that appeared to be possible:

   foreach (string choice in choiceList)

{

userprofile[item.Key].Add((Object)choice);

}

Minor detail on that part appeared that the .add option does as it says, it only adds
items; ergo if you would already have selected option1 in your profile, and try to
update it with an option2, it would keep the option1 saved, and adds the option2.

So before you are actually try to save values that way do a:

   userprofile.clear();

   userprofile.update();

Now that’s for ‘saving’ values to your UserProfile, reading them is another story,
reading a ‘normal’ string can be done with a simple:

   userprofile["PropertyToRead"].Value;

Reading a ChoiceList should be done like:

   if (userprofile["PropertyToRead"] is UserProfileValueCollection)

clValue = userprofile["PropertyToRead"] as UserProfileValueCollection;

Whenever you done that you can simple loop trough the UserProfileValueCollection for
reading the selected items.

Leave a Reply