Analytics


Google

Thursday, August 14, 2008

Querying LDAP using .Net

To query LDAP using .Net, use System.DirectoryServices library.

Quickest way is as follows:

Dim LDAPEntry As DirectoryEntry
Dim LDAPStr as String = "ldap://ldap.blogspot.com/ou=people,o=blogspot.com,o=SDS"

LDAPStr = "LDAP://" & LDAPSrv & LDAPPostFix
LDAPEntry = New DirectoryEntry(LDAPStr)

Dim srch As New DirectorySearcher(LDAPEntry)
srch.Filter = "uid=1234"

Dim rslt As SearchResult
rslt = srch.FindOne
Dim tmpStr as String
Dim tmpObj as Object

Dim rsltPropCol As ResultPropertyCollection = rslt.Properties
For Each keyStr In rsltPropCol.PropertyNames
Try
For Each tmpObj In rslt.Properties(keyStr)
'This loop is there because in LDAP multiple entry is
'permitted for the same key.
'Also any object are permitted some of which cannot be
'converted into string
keyVal = Replace(CStr(tmpObj), "'", "")
Next
Catch ex As System.Exception
keyVal = ""
End Try
tmpStr = String.Format("key is {0}, value is {1}", keyStr, keyVal)
Console.Writeline(tmpStr)
Next

In the example above, the LDAPStr is made up, you need to refer to the one use by your company. The same is the filter.

One of the key things that is important is that the values can be object of any kind so you need to be careful when retrieving it and then assigning to the variables.

If you don't specify properties to load, it will return all the fields same as you do a select * in SQL. If you want to restrict the fields it returns then specify it before you call the FindOne method:
   srch.PropertiesToLoad.Add("mail")
srch.PropertiesToLoad.Add("dept")
srch.PropertiesToLoad.Add("telephonenumber")
srch.PropertiesToLoad.Add("title")


It is possible to use wildcard. In LDAP, "*" is the wildcard.

FindOne will return only one result. If you want more than one, then use FindAll as in:

Dim rsltList As SearchResultCollection
rsltList = srch.FindAll

You can then loop thru the collection as in

For each rslt in rsltList
...
Next

Authentication

You can also use LDAP for authentication. When you set the Directory.AuthenticationType.

For example, when you set the following:

LDAPEntry.AuthenticationType = AuthenticationTypes.ReadonlyServer

Then you need to have the username and password prior to calling FindOne or FindAll as in:

LDAPEntry.Username = "uid=" & uid & ",ou=people,o=blogspot.com,o=sds"
LDAPEntry.Password = pwd



If you just want to query, just set the authenticationType to none. You can see all the other enumerations here.

No comments: