Reputation: 157
I have an application where I need to pull contacts from Active Directory.
Here is the code that I'm using:
Public Function GetADContacts(ByVal LastNameStarts As String) As DirectoryServices.SearchResultCollection
Dim rootDSE As New DirectoryServices.DirectoryEntry("LDAP://RootDSE")
Dim defaultNamingContext As String = rootDSE.Properties("defaultNamingContext").Value.ToString()
Dim objSearch As New DirectoryServices.DirectorySearcher()
Dim cllQueryResults As DirectoryServices.SearchResultCollection
With objSearch
.SearchRoot = New DirectoryServices.DirectoryEntry("LDAP://" + defaultNamingContext)
.Filter = "(&(objectclass=contact)(mailNickname=*)(cn=*)(sn=" + LastNameStarts + "*)(givenname=*))"
.SearchScope = DirectoryServices.SearchScope.Subtree
.PropertiesToLoad.AddRange(New String() {"cn", "sn", "givenname", "mailNickname"})
.Sort.PropertyName = "sn"
.Sort.Direction = DirectoryServices.SortDirection.Ascending
cllQueryResults = .FindAll()
End With
Return cllQueryResults
End Function
I've checked to make sure the contacts have sn, cn, givenname, and mailNickname attributes set, but nothing is returned. When I change the objectcategory to user, I get all the users, but for contacts, I get nothing.
Is there something I'm doing wrong?
Upvotes: 0
Views: 1441
Reputation: 446
If you want to search for contacts only your filter should look like this:
Searcher.Filter = "(&(objectCategory=person)(objectClass=contact))"
Here a little example to get the DN of all contacts:
Dim Searcher As New DirectorySearcher("LDAP://")
Dim QueryResults As SearchResultCollection
Dim Result As SearchResult
Searcher.PropertiesToLoad.Add("distinguishedName")
Searcher.Filter = "(&(objectCategory=person)(objectClass=contact))"
QueryResults = Searcher.FindAll
For Each Result In QueryResults
Console.WriteLine(Result.Properties("distinguishedName")(0))
Next
Console.ReadLine()
There is a very helpful article on this topic: Active Directory: LDAP Filter Syntax. Sadly I dind't save the link.. I'll try to provide it later.
Upvotes: 1