SharePointCommunity
Die deutschsprachige Community für SharePoint, Microsoft 365, Teams, Yammer und mit Azure
SharePoint : How to get ‘first name’ and ‘last name’ of a user by code

Blogs

Oliver Wirkus

Syndication

Certifications

Web 2.0

http://smits-net.de/img/linkedin_button.gif

XING

http://i80.photobucket.com/albums/j191/mikesamerica/twitter_button_zpsee74f711.png

 

 Add to Technorati Favorites

 

 Delicious Bookmark this on Delicious

 

  Locations of visitors to this page

 

Did you ever write code that sends an email to the current user informing her or him about something? For example: a SharePoint user reserved a conference room using a webpart - and this webpart sends a confirmation email to the user.

In most cases you would like to address this user by her or his real name - instead of using the login name. Unfortunately the common SPUser object has neither a property ‘first name’ nor a property ‘last name’ That’s why the impersonal login name is used quite often.

But there is a way to get the first name and the last name of a SharePoint user - both are stored in the User Profile of the current user (well - in most cases). Here is a simple code snippet to show you how to obtain the first name and the last name of a SharePoint user:

   1:  bool GetNameOfSharePointUser(Guid siteId, SPUser user, ref string firstName, ref string lastName)
   2:  {
   3:      bool retParam = false;
   4:      string tmpFirstName = string.Empty;
   5:      string tmpLastName = string.Empty;
   6:   
   7:      SPSecurity.RunWithElevatedPrivileges(delegate() 
   8:      {
   9:          using (SPSite site = new SPSite(siteId)) 
  10:          {
  11:              try
  12:              {
  13:                  SPServiceContext serverContext = SPServiceContext.GetContext(site);
  14:                  UserProfileManager profileManager = new UserProfileManager(serverContext);
  15:   
  16:                  UserProfile profile = profileManager.GetUserProfile(user.LoginName);
  17:                  tmpFirstName = profile["FirstName"].Value.ToString();
  18:                  tmpLastName = profile["LastName"].Value.ToString();
  19:   
  20:                  retParam = true;
  21:              }
  22:              catch (Exception)
  23:              {
  24:                  // Do proper Exception handling here
  25:                  retParam = false;
  26:              }
  27:          }      
  28:      });
  29:   
  30:      if (true == retParam)
  31:      {
  32:          firstName = tmpFirstName;
  33:          lastName = tmpLastName;
  34:      }
  35:   
  36:      return retParam;
  37:  }

http://msdn.microsoft.com/en-us/library/microsoft.office.server.userprofiles.userprofile(v=office.15).aspx

TweetThisButton

Bereitgestellt 31 Jul 2013 12:47 von Oliver Wirkus
Gespeichert unter: , ,