Friday, January 11, 2013

Getting Hierarchy Of User Profiles In SharePoint Using C#



Getting Hierarchy Of User Profiles In SharePoint Using C#


Below is the examples respectively for 
  • Find immediate manager of a particular user.
  • All the users who reports the same manager. 
  • All the managers above in the chain for a particular user
Note : 

Add Following Dll Before Coding.

"Microsoft.Office.Server.dll & Microsoft.Office.Server.UserProfiles.dll"

Location For The Dll:
  • C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI\Microsoft.Office.Server.dll
  • C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI\Microsoft.Office.Server.UserProfiles.dll

Find Manager for currently logged in user.
private void GetManegerProfile()
 {
 SPSite site;
 SPWeb web;
 SPServiceContext serviceContext;
 UserProfileManager profiles;
 UserProfile profile; 
 try
  {
    using (site = new SPSite(SPContext.Current.Web.Url))
    {
      using (web = site.OpenWeb())
      {
        serviceContext = SPServiceContext.GetContext(site);
        profiles = new UserProfileManager(serviceContext);
        //Getting the profile of logged in user.
       profile = profiles.GetUserProfile(web.CurrentUser.LoginName);
      //Getting profile of the manager of the logged in user.
      profile = profile.GetManager();
      }
    } 
  }
catch { }
}
Find all the user who reports the same manager as logged in user. 
private void GetManegerProfile()
{
SPSite site;
SPWeb web;
SPServiceContext serviceContext;
UserProfileManager profiles;
UserProfile profile;
List<UserProfile> peers; 
try
{
  using (site = new SPSite(SPContext.Current.Web.Url))
  {
   using (web = site.OpenWeb())
    {
      serviceContext = SPServiceContext.GetContext(site);
      profiles = new UserProfileManager(serviceContext);
      //Getting the profile of logged in user.
      profile = profiles.GetUserProfile(web.CurrentUser.LoginName);
      //Getting peers of the logged in user.
      peers = new List<UserProfile>(profile .GetPeers());
      }
    }
  }
catch { }
}

Find all the managers above in the chain for the logged in user.

private void GetManegerProfile()
{
SPSite site;
SPWeb web;
SPServiceContext serviceContext;
UserProfileManager profiles;
UserProfile profile;
List<UserProfile> managers;
try
{
using (site = new SPSite(SPContext.Current.Web.Url))
{
using (web = site.OpenWeb())
  {
   serviceContext = SPServiceContext.GetContext(site);
   profiles = new UserProfileManager(serviceContext);
   //Getting the profile of logged in user.
   profile = profiles.GetUserProfile(web.CurrentUser.LoginName);
   //Getting manager profiles of the logged in user.
    managers =new List<UserProfile>( profile.GetManagers());
    }
  }
}
catch { }

No comments:

Post a Comment