hexOffender
Programmer
I am trying to do an LDAP query of the AD server to get a users email address. I have seen various versions of essentially the same code all over the net so I know I am not that far off, but I keep getting an Object reference not set to an instance of an object error when I return my searchresults.
Example:
Public Function GetEmail(ByVal user As String) As String
Try
Dim search As New DirectorySearcher(GetDirectoryEntry())
search.Filter = "(&(objectCategory=Person)(objectClass=user)(SAMAccountName=" & user & "))"
search.PropertiesToLoad.Add("mail")
Dim searchResults As SearchResult = search.FindOne
Return searchResults.Properties("mail")(0).ToString 'object reference exception
Catch ex As Exception
MsgBox(ex.ToString, MsgBoxStyle.OKOnly)
End Try
End Function
Public Shared Function GetDirectoryEntry() As DirectoryEntry
Dim dirEntry As New DirectoryEntry("LDAP://SPLATAD1")
'Setting username & password to Nothing forces
'the connection to use your logon credentials
dirEntry.Username = Nothing
dirEntry.Password = Nothing
'Always use a secure connection
dirEntry.AuthenticationType = AuthenticationTypes.Secure
Return dirEntry
End Function
Example:
Public Function GetEmail(ByVal user As String) As String
Try
Dim search As New DirectorySearcher(GetDirectoryEntry())
search.Filter = "(&(objectCategory=Person)(objectClass=user)(SAMAccountName=" & user & "))"
search.PropertiesToLoad.Add("mail")
Dim searchResults As SearchResult = search.FindOne
Return searchResults.Properties("mail")(0).ToString 'object reference exception
Catch ex As Exception
MsgBox(ex.ToString, MsgBoxStyle.OKOnly)
End Try
End Function
Public Shared Function GetDirectoryEntry() As DirectoryEntry
Dim dirEntry As New DirectoryEntry("LDAP://SPLATAD1")
'Setting username & password to Nothing forces
'the connection to use your logon credentials
dirEntry.Username = Nothing
dirEntry.Password = Nothing
'Always use a secure connection
dirEntry.AuthenticationType = AuthenticationTypes.Secure
Return dirEntry
End Function