Random C# – Active Directory
Recently I’ve had to create a web form that would submit a request through our internal trouble ticket system. That part’s fine. It was the part where I needed to filter the requesting users according to a few criteria. In order to submit the form, the the user would need to be (1) on our new domain, (2) based in a certain city, and (3) on certain email exchanges. At first, I was thinking how I would accomplish this task. Active Directory! Right! That’s what ASP.Net is good for! But how?…
I searched and searched. I did find articles but the wording, bad grammar, and confusing posts made it a tad difficult to understand at first. I asked a co-worker who actually had wrote a site that interacted with Active Directory. Thank you, Matt, for getting me started on this. The example code he gave me was very helpful and I found it was easier than I thought. I tried it out and was overjoyed. There. I can search AD and grab the account name with no problem! But… What about the other properties I need for this project? What are their names? I scoured the Interweb in search for an answer to my plea: Where’s a list of all of the properties that I can access? No luck at all. All of my searches ended with the same old articles. The fact turned out to be that all Directories are going to be different according to the infrastructure’s needs. Slap myself. Duh. Well then, back to the old coding board with me.
Using System.DirectoryServices; // Don't forget this at the top
private static String GetADInfo(String user)
{
String output = "";
// Fill in with your own LDAP domain path
DirectorySearcher searcher = new DirectorySearcher(new DirectoryEntry(”LDAP://DC=“);
searcher.Filter = “(&(anr=” + user + “) (objectCategory=Person))”;
SearchResult result = searcher.FindOne();
try
{
if (result != null)
{
foreach (string key in result.Properties.PropertyNames)
{
foreach (object propValue in result.Properties[key])
{
output += key + ” = ” + propValue + ““;
}
}
}
else
{
output = “User ”" + user + “” does not exist in AD.”;
}
}
catch (Exception e)
{
Response.Write(e.Message);
}
return output;
}
Assign that function to a text field on the page and it will output every single property AD will allow you to retrieve for a user account. With all seven pages of results printed out, I was able to find the properties I needed to stick into:
searcher.PropertiesToLoad.AddRange(new String[] { "property1", "property2" });
Sometimes you can’t find everything on the Internet and you have to figure it out yourself. This project is looking good so far and I hope it works out. At least I learned something. Useful links for future reference:
