Pages

Friday, March 9, 2012

Working with custom user profile properties programmatically

This one is just to share how can we get the values of custom properties in user profiles in SharePoint 2010. actually this was the outcome of a quick POC while answering on MSDN SharePoint forums. so thought to share as this may help someone.

I have created a custom user profile property of type string and internal name is set to PrefferedColor while display name is - Preffered Color.
Then a simple web part which reads this custom user profile property.

All you need to do is Include references of following assemblies

Microsoft.Office.Server;
Microsoft.Office.Server.UserProfiles;


public class ShowPropertyWp : WebPart
{
  private string m_propertyInternalName = "PrefferedColor";
  private string m_propertyDisplayName = "Preffered Color";
  private string color;

  protected override void CreateChildControls()
  {
    try
    {
      Guid siteId = SPContext.Current.Site.ID;
      Guid webId = SPContext.Current.Web.ID;
      using (SPSite site = new SPSite(siteId))
      {
        SPServiceContext serviceContext = SPServiceContext.GetContext(site);
        UserProfileManager upm = new UserProfileManager(serviceContext);

        if (upm != null)
        {

             UserProfile up = upm.GetUserProfile("domain\\user");
             if (up != null)
             {
                color = up[m_propertyInternalName].Value.ToString();

                color = up[m_propertyDisplayName].Value.ToString(); // This will give an error.
             }


         }
      }

      if (!string.IsNullOrEmpty(color))
      {
         this.Controls.Add(new LiteralControl("You Have Preffered Color - " + color));
      }
      else
      {
         this.Controls.Add(new LiteralControl("You have not selected any preffered color"));
   }
  }
  catch (Exception ex)
  {
     this.Controls.Add(new LiteralControl("Error: " + ex.Message));
  }
 }
}


No comments:

Post a Comment