Could you help me and tell if im using the "using statement" correctly in my directoryservice function that gets distingushed name from my Active Directory. I want to dispose and close objects correctly.
Code:
Public Function GetObjectDistinguishedName(ByVal objClass As objectClass, _
ByVal returnValue As returnType, _
ByVal objName As String, ByVal LdapDomain As String, _
Optional ByVal includeLdapPrefix As Boolean = True) As String
Dim distinguishedName As String = String.Empty
Dim connectionPrefix = "LDAP://" & LdapDomain
Using entry As DirectoryEntry = New DirectoryEntry(connectionPrefix)
Dim mySearcher = New DirectorySearcher(entry)
Dim result As SearchResult
Dim directoryObject As DirectoryEntry
Select Case objClass
Case objectClass.user
mySearcher.Filter = "(&(objectClass=user)(|(cn=" + objName + ")(sAMAccountName=" + objName + ")))"
Case objectClass.group
mySearcher.Filter = "(&(objectClass=group)(|(cu=" + objName + ")(dn=" + objName + ")))"
Case objectClass.computer
mySearcher.Filter = "(&(objectClass=computer)(|(cn=" + objName + ")(dn=" + objName + ")))"
Case objectClass.organizationalunit
mySearcher.Filter = "(ou=" + objName + ")"
End Select
result = mySearcher.FindOne()
If result Is Nothing Then 'If the search results in nothing, call for help!'
Throw New NullReferenceException("Unable to locate the distinguishedName for the " & objClass.ToString & " : " & objName & " in the " & LdapDomain & " domain")
End If
directoryObject = result.GetDirectoryEntry()
If returnValue.Equals(returnType.distinguishedName) Then
If includeLdapPrefix Then
distinguishedName = "LDAP://" & directoryObject.Properties("distinguishedName").Value
Else
distinguishedName = directoryObject.Properties("distinguishedName").Value
End If
End If
End Using
Return distinguishedName
End Function