Monday, August 18, 2014

Accessing Network Users Email With LDAP

If your running an application on your personal or company network and it's using Windows Authentication, this snippet may be of some use.  This past weekend, I was at an event where I was given the task to create an application that allowed users in the network to register for a company event.  One of the many requirements was to send a confirmation email once the registration was complete.  Since this application would be used on our company network, I decided to use WindowsIdentity and DirectoryServices in the .Net framework.

In the snippet below, I will show you how to access the current users email address.  As you begin to explore the Active Directory, remember that "mail" is only one of many attributes that you can accessed through LDAP.  For more, go here.  Happy Coding!! :)



You'll need to reference DirectoryServices in your project.
using System.DirectoryServices;
using System.Security.Principal;
 
public static string DisplayEmail(IIdentity id)
 {
    string email = string.Empty;
    var winId = id as WindowsIdentity;
     if (id == null)
      {
        return "Identity is not a windows identity";
      }

    var userInQuestion = winId.Name.Split('\\')[1];
    var myDomain = winId.Name.Split('\\')[0];

    var entry = new DirectoryEntry("LDAP://" + myDomain);

    var adSearcher = new DirectorySearcher(entry)
      {
       SearchScope = SearchScope.Subtree,
       Filter = "(&(objectClass=user)(samaccountname=" + userInQuestion + "))"
      };

    var userObject = adSearcher.FindOne();

    if (userObject != null)
      {
       email = string.Format("{0}", userObject.Properties["mail"][0]);
      }
       
       return email;
 }

Typically, I put functions like this in my Utility class but you can put it where ever you see fit. Below is an example of how to execute this function.
 
var email = Utility.DisplayUser(WindowsIdentity.GetCurrent());



Retrieve OS version with Javascript

Recently, I was given a task to find out what OS version an end users machine was running on.  The reason I need this information was to check if the user should be running the application on IE9 32bit or IE9 64bit.  Now, this might not sound very useful but given the environment I was working in, the end user could be having an awkword experience.

 
 <script type="text/javascript">
      function checkOSVersion() {
        if (navigator.userAgent.indexOf("WOW64") != -1 || navigator.userAgent.indexOf("Win64") != -1) 
           {
             alert("This is a 64 bit OS");
           } 
        else 
            {
                alert("Not a 64 bit OS");
            }
           }
    </script>