Wednesday, February 8, 2012

DirectorySearcher PropertiesToLoad Add is not working

If you have played with or is using System.DirectoryServices.ActiveDirectory, you might jump into the consclusio that "DirectorySearcher PropertiesToLoad.Add " is not working/useless/will be ignored.But that might not be the case.

Lets see a sample, this sample below tries to get the list of users with their user name, first name,last name and email.

  Private Sub LoadUsersForDomain(SelectedDomain As Domain)
        If SelectedDomain IsNot Nothing Then
            Dim sentry As DirectoryEntry = SelectedDomain.GetDirectoryEntry
            Dim Searcher As New DirectorySearcher(sentry)
            Dim srs As SearchResultCollection
            Searcher.PropertiesToLoad.Add("samaccountname")
            Searcher.PropertiesToLoad.Add("GivenName")
            Searcher.PropertiesToLoad.Add("sn")
            Searcher.PropertiesToLoad.Add("Mail")
            Searcher.Filter = "(&(objectClass=user)(objectCategory=person))"
            srs = Searcher.FindAll
            For Each Result As SearchResult In srs
                If Result IsNot Nothing Then
                    Dim fuser As New User
                    If Result.Properties("samaccountname") IsNot Nothing AndAlso Result.Properties("samaccountname").Count > 0 Then
                        fuser.UserName = (Result.Properties("samaccountname")(0).ToString())
                    End If
                    If Result.Properties("GivenName") IsNot Nothing AndAlso Result.Properties("GivenName").Count > 0 Then
                        fuser.FirstName = (Result.Properties("GivenName")(0).ToString())
                    End If
                    If Result.Properties("sn") IsNot Nothing AndAlso Result.Properties("sn").Count > 0 Then
                        fuser.LastName = (Result.Properties("sn")(0).ToString())
                    End If
                    If Result.Properties("Mail") IsNot Nothing AndAlso Result.Properties("Mail").Count > 0 Then
                        fuser.Email = (Result.Properties("Mail")(0).ToString())
                    End If
                End If
            Next
            Searcher.Dispose()
            sentry.Dispose()
        End If
    End Sub

When you debug the code, you will notice that for some search results there wont be sn givenname and mail properties in the returned list.

As samaccountname is the only required field when creating a active directory user you will get that all the time in the returned property list, but the others might be there or not depending on the  information got filled in properly or not at the time of creating the user.


----
directorysearcher propertiestoload list
directorysearcher propertiestoload add
directorysearcher clienttimeout
directorysearcher propertiestoload example
directorysearcher properties
directorysearcher filter
directorysearcher propertiestoload email
directorysearcher example

No comments:

Post a Comment