Skip to main content

Getting user First Name and Last Name from Active Directory

Recently, I had to create a MVC portal for organizing test messages. Since site is personalized for User, we were required to fetch and disply username, when they login. This being intranet site, user is authenticated using Windows Authentication. Windows user names are most of the time are mix of literal, not conveying users First and Last name. I used following code to get User First and Last name, using DirectorySearcher class to query Active Directory. Since user name in HttpContext is in format DomainName\\UserName, I had to extract user name alone and use it filter.

using System.DirectoryServices;
DirectorySearcher ds = new DirectorySearcher();
var indexOfBS = User.Identity.Name.IndexOf("\\");
ds.Filter = String.Format("((SAMAccountName={0}))", User.Identity.Name.Substring(indexOfBS + 1, User.Identity.Name.Length - indexOfBS - 1));
var directoryEntry = ds.FindOne();
var givenName = directoryEntry.Properties["givenName"][0];
var surName = directoryEntry.Properties["sn"][0];
string userName = String.Format("{0}, {1}", surName, givenName);


Popular posts from this blog

GIF Support in Outlook

I been waiting for the day when Outlook will get GIF support and it is here. I been creating GIF to explain a situation or when creating troubleshooting mailer. Now that outlook has given support to GIF, I can draft GIF embedded mail with more grace. So effectively another dimension i.e.time has been added to my mails. I use ScreentoGIF  to create GIF and it is a nice piece of software with ton of option to edit your recorded GIF like reducing delay between frames, reducing adding transition, adding caption..etc. One thing I recommend is adding a progress bar, so that user intuitively knows at what state the animation is in, when he/she starts noticing it.