Josh
Josh

Reputation: 97

Querying Active Directory using C# for user email by employee ID

Is it possible to get a user's email from Active Directory using employeenumber as the query term?

I am using C#'s System.DirectoryServices and am a little bit lost. The previous developer at my company was using this process, but he had an email and was querying for the employee number. I have changed it to what I believe it should be, but to be honest, I don't understand the code that well.

Is there something wrong with my code? every time i run it, I get a Null Reference error on the DirectoryEntry up_user = line. I assume it is because the previous line is not getting any entities.

Also, is there any good documentation on this topic? Everywhere I look, the posts are from 2011 or 2013.

I have the following:

try
{
    string email = string.Empty;
    ContextType authenticationType = ContextType.Domain;
    PrincipalContext principalContext = new PrincipalContext(authenticationType, "MATRIC");
    UserPrincipal userPrincipal = null;

    userPrincipal = UserPrincipal.FindByIdentity(principalContext, empnum);

    DirectoryEntry up_User = (DirectoryEntry)userPrincipal.GetUnderlyingObject();
    DirectorySearcher deSearch = new DirectorySearcher(up_User);
    SearchResultCollection results = deSearch.FindAll();
    if (results != null && results.Count > 0)
    {
        ResultPropertyCollection rpc = results[0].Properties;
        foreach (string rp in rpc.PropertyNames)
        {
            if (rp == "mail") 
            {
                email = rpc["mail"][0].ToString();
            }
        }

        if (email != string.Empty)
        {
            return email;
        }

        return null;
    }
            return null;
}
catch (Exception ex)
{
    throw ex;
}

Upvotes: 0

Views: 7978

Answers (1)

Gabriel Luci
Gabriel Luci

Reputation: 40958

UserPrincipal.FindByIdentity only works for finding a user by what AD considers an identifying attribute. These are listed in the IdentityType enumeration. The employee number isn't one of those.

Are you using employeeId or employeeNumber in AD? They are different attributes, although both are just strings with no special meaning or restrictions in AD.

The employeeId attribute is exposed in the UserPrincipal class, so you can search by it with UserPrincipal as described in the answer here:

UserPrincipal searchTemplate = new UserPrincipal(principalContext);
searchTemplate.EmployeeID = employeeId;
PrincipalSearcher ps = new PrincipalSearcher(searchTemplate);

UserPrincipal user = (UserPrincipal)ps.FindOne();

Then you can use the EmailAddress property of the account you find (you don't need to do what you're doing with the DirectorySearcher).

var emailAddress user?.EmailAddress;

If you're using employeeNumber, then you will need to use DirectorySearcher to find it. Something like this:

var search = new DirectorySearcher(new DirectoryEntry("LDAP://yourdomain.com"));
search.Filter = $"(&(ObjectClass=user)(employeeNumber={employeeNumber}))"; 
search.PropertiesToLoad.Add("mail");

var result = search.FindOne();
string emailAddress = null;
if (result.Properties.Contains("mail")) {
    emailAddress = result.Properties["mail"][0].Value as string;
}

Upvotes: 8

Related Questions