Working with custom user profile properties programmatically

nThis 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.
n
nI have created a custom user profile property of type string and internal name is set to PrefferedColor while display name is – Preffered Color.
nThen a simple web part which reads this custom user profile property.
n
nAll you need to do is Include references of following assemblies
n
nMicrosoft.Office.Server;
nMicrosoft.Office.Server.UserProfiles;
n
n
n

npublic class ShowPropertyWp : WebPart

n

n{

n

n  private string m_propertyInternalName = “PrefferedColor”;

n

n  private string m_propertyDisplayName = “PrefferednColor”;

n

n  private string color;

n

n

n

n  protected override void CreateChildControls()

n

n  {

n

n    try

n

n    {

n

n      Guid siteId = SPContext.Current.Site.ID;

n

n      Guid webId = SPContext.Current.Web.ID;

n

n      using (SPSite site = new SPSite(siteId))

n

n      {

n

n        SPServiceContextnserviceContext = SPServiceContext.GetContext(site);

n

n        UserProfileManager upm = new UserProfileManager(serviceContext);

n

n

n

n        if (upm != null)

n

n        {

n

n

n

n             UserProfile up = upm.GetUserProfile(“domain\\user”);

n

n             if (up != null)

n

n             {

n

n                color =nup[m_propertyInternalName].Value.ToString();

n

n

n

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

n

n             }

n

n

n

n

n

n         }

n

n      }

n

n

n

n      if (!string.IsNullOrEmpty(color))

n

n      {

n

n         this.Controls.Add(new LiteralControl(“You Have PrefferednColor – “ + color));

n

n      }

n

n      else

n

n      {

n

n         this.Controls.Add(new LiteralControl(“You have not selectednany preffered color”));

n

n   }

n

n  }

n

n  catch (Exception ex)

n

n  {

n

n     this.Controls.Add(new LiteralControl(“Error: “ + ex.Message));

n

n  }

n

n }

n

n}

n
n
n

Leave a Comment