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





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















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;
}









share|improve this question























  • It looks like your issue is that your object keeps returning null. Have you checked out this link and explored those options -> stackoverflow.com/questions/37050930/…

    – Robin
    Nov 16 '18 at 19:29


















0















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;
}









share|improve this question























  • It looks like your issue is that your object keeps returning null. Have you checked out this link and explored those options -> stackoverflow.com/questions/37050930/…

    – Robin
    Nov 16 '18 at 19:29














0












0








0








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;
}









share|improve this question














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;
}






c# active-directory directoryservices






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 16 '18 at 19:25









JoshJosh

177




177













  • It looks like your issue is that your object keeps returning null. Have you checked out this link and explored those options -> stackoverflow.com/questions/37050930/…

    – Robin
    Nov 16 '18 at 19:29



















  • It looks like your issue is that your object keeps returning null. Have you checked out this link and explored those options -> stackoverflow.com/questions/37050930/…

    – Robin
    Nov 16 '18 at 19:29

















It looks like your issue is that your object keeps returning null. Have you checked out this link and explored those options -> stackoverflow.com/questions/37050930/…

– Robin
Nov 16 '18 at 19:29





It looks like your issue is that your object keeps returning null. Have you checked out this link and explored those options -> stackoverflow.com/questions/37050930/…

– Robin
Nov 16 '18 at 19:29












1 Answer
1






active

oldest

votes


















3














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;
}





share|improve this answer


























  • I am using employeeNumber. So in the last block of code, the Filter says get users where employeeNumber = the EmployeeNumber I provide? Then it only loads mail. In the result it finds the first match of the employeeNumber and sets emailAddress to the search result? Sorry i just want to understand it

    – Josh
    Nov 16 '18 at 20:17











  • Right. So that code assumes you have a variable called employeeNumber already. Then it sets emailAddress to the mail attribute of the user it found.

    – Gabriel Luci
    Nov 16 '18 at 20:22













  • it worked like a charm. thanks so much!

    – Josh
    Nov 16 '18 at 20:27












Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53344176%2fquerying-active-directory-using-c-sharp-for-user-email-by-employee-id%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









3














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;
}





share|improve this answer


























  • I am using employeeNumber. So in the last block of code, the Filter says get users where employeeNumber = the EmployeeNumber I provide? Then it only loads mail. In the result it finds the first match of the employeeNumber and sets emailAddress to the search result? Sorry i just want to understand it

    – Josh
    Nov 16 '18 at 20:17











  • Right. So that code assumes you have a variable called employeeNumber already. Then it sets emailAddress to the mail attribute of the user it found.

    – Gabriel Luci
    Nov 16 '18 at 20:22













  • it worked like a charm. thanks so much!

    – Josh
    Nov 16 '18 at 20:27
















3














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;
}





share|improve this answer


























  • I am using employeeNumber. So in the last block of code, the Filter says get users where employeeNumber = the EmployeeNumber I provide? Then it only loads mail. In the result it finds the first match of the employeeNumber and sets emailAddress to the search result? Sorry i just want to understand it

    – Josh
    Nov 16 '18 at 20:17











  • Right. So that code assumes you have a variable called employeeNumber already. Then it sets emailAddress to the mail attribute of the user it found.

    – Gabriel Luci
    Nov 16 '18 at 20:22













  • it worked like a charm. thanks so much!

    – Josh
    Nov 16 '18 at 20:27














3












3








3







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;
}





share|improve this answer















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;
}






share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 16 '18 at 20:20

























answered Nov 16 '18 at 19:35









Gabriel LuciGabriel Luci

11.6k11525




11.6k11525













  • I am using employeeNumber. So in the last block of code, the Filter says get users where employeeNumber = the EmployeeNumber I provide? Then it only loads mail. In the result it finds the first match of the employeeNumber and sets emailAddress to the search result? Sorry i just want to understand it

    – Josh
    Nov 16 '18 at 20:17











  • Right. So that code assumes you have a variable called employeeNumber already. Then it sets emailAddress to the mail attribute of the user it found.

    – Gabriel Luci
    Nov 16 '18 at 20:22













  • it worked like a charm. thanks so much!

    – Josh
    Nov 16 '18 at 20:27



















  • I am using employeeNumber. So in the last block of code, the Filter says get users where employeeNumber = the EmployeeNumber I provide? Then it only loads mail. In the result it finds the first match of the employeeNumber and sets emailAddress to the search result? Sorry i just want to understand it

    – Josh
    Nov 16 '18 at 20:17











  • Right. So that code assumes you have a variable called employeeNumber already. Then it sets emailAddress to the mail attribute of the user it found.

    – Gabriel Luci
    Nov 16 '18 at 20:22













  • it worked like a charm. thanks so much!

    – Josh
    Nov 16 '18 at 20:27

















I am using employeeNumber. So in the last block of code, the Filter says get users where employeeNumber = the EmployeeNumber I provide? Then it only loads mail. In the result it finds the first match of the employeeNumber and sets emailAddress to the search result? Sorry i just want to understand it

– Josh
Nov 16 '18 at 20:17





I am using employeeNumber. So in the last block of code, the Filter says get users where employeeNumber = the EmployeeNumber I provide? Then it only loads mail. In the result it finds the first match of the employeeNumber and sets emailAddress to the search result? Sorry i just want to understand it

– Josh
Nov 16 '18 at 20:17













Right. So that code assumes you have a variable called employeeNumber already. Then it sets emailAddress to the mail attribute of the user it found.

– Gabriel Luci
Nov 16 '18 at 20:22







Right. So that code assumes you have a variable called employeeNumber already. Then it sets emailAddress to the mail attribute of the user it found.

– Gabriel Luci
Nov 16 '18 at 20:22















it worked like a charm. thanks so much!

– Josh
Nov 16 '18 at 20:27





it worked like a charm. thanks so much!

– Josh
Nov 16 '18 at 20:27




















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53344176%2fquerying-active-directory-using-c-sharp-for-user-email-by-employee-id%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Florida Star v. B. J. F.

Error while running script in elastic search , gateway timeout

Adding quotations to stringified JSON object values