Tuesday, January 25, 2011

Get user profiles details programmatically in SharePoint 2010

Introduction:
In this article we will discuss how to get user profile details by using SharePoint object model classes in SharePoint. In my last article we have discussed Save user profile properties programmatically in sharepoint 2010.
Description:
Here we will discuss how to get user profile properties and also how to access profile properties using SharePoint 2010. We have used here SharePoint object model.
private UserProfile GetUserInfo(string AccountName)
{
UserProfile profile = null;
SPServiceContext serviceContext = SPServiceContext.Current;
UserProfileManager profileManager = new UserProfileManager(serviceContext);
if (AccountName != string.Empty)
{
profile = profileManager.GetUserProfile(AccountName);
}
else
{
profile = profileManager.GetUserProfile(SPContext.Current.Web.CurrentUser.RawSid);
}
return profile;
}


void GetCurrentUserDetails()
{
UserProfile userProfile = GetUserInfo("");
lblUserName.Text = GetUserName(userProfile);
if (userProfile[PropertyConstants.FirstName].Value != null)
{
lblUserName.Text += " (" + userProfile[PropertyConstants.FirstName].Value.ToString() + ")";
}

try
{
imgBtnUserImage.ImageUrl = userProfile[PropertyConstants.PictureUrl].Value.ToString();
}
catch (Exception ex)
{
imgBtnUserImage.ImageUrl = "/_layouts/ExpressionsWP/0.jpg";
}
if (userProfile[PropertyConstants.Department].Value != null)
{
ltrAddress.Text = userProfile[PropertyConstants.Department].Value.ToString();
}
if (ltrAddress.Text != string.Empty)
{
if (userProfile[PropertyConstants.Location].Value != null)
{
ltrAddress.Text += "," + userProfile[PropertyConstants.Location].Value.ToString();
}
}
else
{
if (userProfile[PropertyConstants.Location].Value != null)
{
ltrAddress.Text += userProfile[PropertyConstants.Location].Value.ToString();
}
}
}
If any problem or error, please post it in the new SharePoint Forum.