Querying Active Directory
I have a piece of code that I am using to retrieve a first name from
Active Directory based on a logon id (called a COMITID) that is also in
Active Directory.
I am using a filter
The code is as follow:
1. WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent();
2. //code above gets the Windows logon ID of the current user
3. string _userID = System.Security.Principal.WindowsIdentity.GetCurrent().Name.Split('\\').Last();
4. //all the code below is to strip out everything so I am left with just the domain (string domain)
5. string s = currentIdentity.Name;
6. int stop = s.IndexOf("\\");
7. string domain = (stop > -1) ? s.Substring(0, stop) : string.Empty;
8. //code below setting the DirectoryEntry and DirectorySearcher variables
9. DirectoryEntry entry = new DirectoryEntry("LDAP://" + domain);
10. DirectorySearcher dSearch = new DirectorySearcher(entry);
11. //code below is the filter
12. dSearch.Filter = "(objectClass=user)" ;
13. //code below sets the properties I want to retrieve to the givenName (Fisrt name), sn (the surname) and samAccountName (the logon id)
14. var propertiesToLoad = new[]
15. {
16. "givenName",
17. "sn",
18. "samAccountName>"
19. };
20. //adding the properties
21. dSearch.PropertiesToLoad.AddRange(propertiesToLoad);
22. //looping through Active Directory
23. foreach (SearchResult searchEntry in dSearch.FindAll())
24. {
25. //getting the entry I want
26. var userEntry = searchEntry.GetDirectoryEntry();
27. //in reality "XBBLDZQ" will not be hardcoded in; this example is just for testing
28. if (userEntry.Properties["samAccountName"].Value.ToString().Trim().Contains("XBBLDZQ"))
29. {
30. //shows the first name in a messagebox
31. MessageBox.Show(userEntry.Properties["givenName"].Value.ToString());
32. }
33. }
This does not give me back the first name (line 31). However when I change the filter (line 12) from what is there now:
dSearch.Filter = "(objectClass=user)";
to
dSearch.Filter = "(&(objectClass=user)(samAccountName=XBBLDZQ))";
then it works.
This is obviously not the way I want it to work as I don't want to filter by a single COMITID (XBBLDZQ), I want to loop through them all and pick out the one with the COMITID I want (XBBLDZQ). This is what line 28 should do.
This makes no sense to me as if I change line 12 in the way I described above, it is setting the filter to say "only give me the users with the COMITID XBBLDZQ". If I remove the filter it should give me all COMITID's (so line 31 should still execute).
Am I right or maybe I don't understand the way filters work. If I remove the filter completely then it doesn't work either. The only way it works is if I add the COMITID as a filter like below;
dSearch.Filter = "(&(objectClass=user)(samAccountName=XBBLDZQ))";
But that kind of defeats the purpose of what I want to do in the first place.