Update SPLIst Items with data from User Profiles

Greetings!

I know it's been a while since I've posted, but I've been saving up! Party!!! I recently repsonded to a post by a user on the SharePoint University message boards in regards to updating a SharePoint list with information in a users profile via an ItemAdded event handler. I hope someone can get some use from this code. I found it very educating and entertaining to get it to work properly.

First, let's start with a list of available properties (by default) in a MOSS user profile:

UserProfile_GUID
SID
ADGuid
AccountName
FirstName
LastName
PreferredName
WorkPhone
Office
Department
Title
Manager
AboutMe
PersonalSpace
PictureURL
UserName
QuickLinks
WebSite
PublicSiteRedirect
SPS-Dotted-line
SPS-Peers
SPS-Responsibility
SPS-Skills
SPS-PastProjects
SPS-Interests
SPS-School
SPS-SipAddress
SPS-Birthday
SPS-MySiteUpgrade
SPS-DontSuggestList
SPS-ProxyAddresses
SPS-HireDate
SPS-LastColleagueAdded
SPS-OWAUrl
SPS-ResourceSID
SPS-ResourceAccountName
SPS-MasterAccountName
Assistant
WorkEmail
CellPhone
Fax
HomePhone

Of course, these can be added to with custom entries, but those are the defaults. Next, we look at how to get at these bad boys:

First, you have to reference Microsoft.Office.Server.UserProfiles and add the Microsoft.Office.Server dll to your project, as well as the standard stuff.

                using (SPWeb web = properties.OpenWeb())
                {
                    //Get the current site, list item being added, current user and context

                    SPSite site = web.Site;
                    SPListItem listItem = properties.ListItem;
                    SPUser user = web.CurrentUser;
                    ServerContext Context = ServerContext.GetContext(site);
                   

                     //Get the user's profile manager from the current context and ignore privacy

                    UserProfileManager upcm = new UserProfileManager(Context, true);
                    PropertyCollection props = upcm.Properties;
                  

                    //Get the user profile

                    UserProfile userprof = upcm.GetUserProfile(user.LoginName);

                    //Get the property you want the data from
                    UserProfileValueCollection name = userprof["PreferredName"];

                    //write property value to list item
                   
                    listItem["Title"] = name;
                    listItem.Update();

                }

Of course, you can change the property to one from the list by changing PreferredName to something else.

Hope this helps!

Leave a Reply