Saturday, April 12, 2008

Get "Currently Logged in" Manager

I posted in my earlier posts a sample on creating a custom webpart .
Today im gonna write a sample on how to use sharepoint object model to get the manager of the currently logged in user.
Create a class library and inherit WebPart, check creating a custom webpart .

Add the following references to your class library:
using Microsoft.Office.Server;
using Microsoft.SharePoint;
using Microsoft.Office.Server.UserProfiles;

Create a label to hold the value of the manager:
Label lbl;
protected override void CreateChildControls()
lbl = new Label();
lbl.Text = GetManager();

Get Manager
private string GetManager()
using (SPSite site = new SPSite("
string manager=string.Empty;
ServerContext context = ServerContext.GetContext(site);//Get the context for this site
UserProfileManager profileManger = new UserProfileManager(context);
SPUser user=SPContext.Current.Web.CurrentUser; //Get the current logged in user
UserProfile prof=profileManger.GetUserProfile(user.LoginName); //Get the profile for the current logged in user
manager = (prof[PropertyConstants.Manager].Value == null)
? "" : prof[PropertyConstants.Manager].Value.ToString(); //Get the manager
catch (Exception)
manager = "Manager was not found";

return manager;


Render the Label
protected override void RenderContents(System.Web.UI.HtmlTextWriter writer)