Monday, January 10, 2011

LDAP lookup in vb.net

I was developing a synchronization feature that should synchronize users from AD to my web application. The scenario was, that when a new user was added to Active Directory, the user would be registered in my app also. In addition to that, names, addresses, phone numbers etc. should also be changed automaticcally to reflect the changes in AD. Deletion should also inactivate the user in my app.

However I ran into problems when I tried to get the directory-entries from AD.
My approach was something like:

My AD path that I would read from was at:

ldap://my_server:389/OU=MyOU Users,OU=MyOU,DC=Mynet,DC=net

so my VB.Net code was:


Imports System.DirectoryServices

    Public Shared Function GetDirectoryEntry(ByVal path As String) As DirectoryEntry
        Dim de As DirectoryEntry = New DirectoryEntry()
        de.Path = path
        de.Username = "domain\user"
        de.Password = "password"
        Return de
    End Function

    Dim de As DirectoryEntry = GetDirectoryEntry("ldap://my_server:389/OU=MyOU Users,OU=MyOU,DC=Mynet,DC=net")
    Dim ds As DirectorySearcher = New DirectorySearcher(de)
    Dim filter As StringBuilder = New StringBuilder()
    filter.Append("(objectClass=user)")
    ds.Filter = filter.ToString()
    ds.SearchScope = SearchScope.Subtree
    Dim results As SearchResultCollection = ds.FindAll()
    For Each result As SearchResult In results
        Dim dey As DirectoryEntry = GetDirectoryEntry(result.Path)
        LocateAndSaveUser(dey.Properties("sAMAccountName").Value, _
               dey.Properties("displayName").Value, _
               dey.Properties("mail").Value, _
               dey.Properties("telephoneNumber").Value)
    Next result
    de.Close()

This returned:
Unknown error (0x80005000)

Quite an informative error message :)

It was a mixture of luck and googling that I found out what was wrong. It seems that you get this error if you don't write the "ldap://" in caps : "LDAP://"

After that it had no problems :)

Changed this:

ldap://my_server:389/OU=MyOU Users,OU=MyOU,DC=Mynet,DC=net

To this:

LDAP://my_server:389/OU=MyOU Users,OU=MyOU,DC=Mynet,DC=net


There weren't so many hits on google that had a solution on this, so I thought this would probably help someone else if I blogged it.

No comments: