[Webinar] Streamline your web hosting managementRegister Today

x
?
Solved

vb.net 2 domain ldap query

Posted on 2014-10-29
3
Medium Priority
?
245 Views
Last Modified: 2014-10-29
I have a program i developed that looks up user info in LDAP and returns it to a listview. It works fine with one domain, when i try to include the second in an IF statement it fails like something is empty in LDAP, which is not blank when i manually check. The logic in my if statement is probably flawed, can someone take a peek?

 
Dim userIds As IEnumerable(Of String) = {"test1", "test2", "test3", "test4", "test5", "test6", "test7", "test8"}
        For Each i As String In userids
            Dim de As New DirectoryEntry("LDAP://domain1.com:389/DC=domain1,DC=com")
            Dim LdapFilter As String = "(sAMAccountName=" & i & ")"
            Dim searcher As New DirectorySearcher(de, LdapFilter)
            Dim result As SearchResult = searcher.FindOne()
            Dim res As SearchResultCollection = searcher.FindAll()

            If res Is Nothing OrElse res.Count <= 0 Then
                Dim tdbfg As New DirectoryEntry("LDAP://domain2.com:389/OU=Users,OU=domain2,DC=domain2,DC=com")
                Dim TDLdapFilter As String = "(sAMAccountName=" & i & ")"
                Dim TDsearcher As New DirectorySearcher(tdbfg, TDLdapFilter)
                Dim TDresult As SearchResult = searcher.FindOne()
                Dim item As ListViewItem = ListView1.Items.Add(i)
                item.SubItems.Add(result.Properties("displayName")(0).ToString())
                item.SubItems.Add(result.Properties("title")(0).ToString())
                item.SubItems.Add(result.Properties("userPrincipalName")(0).ToString())
            Else
                Dim item As ListViewItem = ListView1.Items.Add(i)
                item.SubItems.Add(result.Properties("displayName")(0).ToString())
                item.SubItems.Add(result.Properties("title")(0).ToString())
                item.SubItems.Add(result.Properties("userPrincipalName")(0).ToString())
            End If
        Next

Open in new window


Basically, if it cant find the userid in the first search, it should look again in the second domain, and return the results. Also, how can i turn this into an ELSEIF statement? I would like to have a third else statement that says if the ids arent found in either domain then "do something".

Thanks!
0
Comment
Question by:derek7467
  • 2
3 Comments
 
LVL 35

Accepted Solution

by:
it_saige earned 2000 total points
ID: 40410753
I'm not finding an issue with your if statement.  Here is how you would add an IfElse;
Dim userIds As IEnumerable(Of String) = {"test1", "test2", "test3", "test4", "test5", "test6", "test7", "test8"}
Dim de As DirectoryEntry
Dim filter As String
Dim searcher As DirectorySearcher
Dim result As SearchResult
Dim results As SearchResultCollection
Dim item As ListViewItem
For Each i As String In userIds
	de = New DirectoryEntry("LDAP://DC01/OU=Users,DC=domain1,DC=com")
	filter = String.Format("(sAMAccountName={0})", i)
	searcher = New DirectorySearcher(de, filter)
	result = searcher.FindOne()
	results = searcher.FindAll()

	If results Is Nothing OrElse results.Count <= 0 Then
		de = New DirectoryEntry("LDAP://DC02/OU=Users,DC=domain2,DC=com")
		filter = String.Format("(sAMAccountName={0})", i)
		searcher = New DirectorySearcher(de, filter)
		result = searcher.FindOne()
		If Not result Is Nothing Then
			item = New ListViewItem(i)
			item.SubItems.Add(result.Properties("displayName")(0).ToString())
			item.SubItems.Add(result.Properties("title")(0).ToString())
			item.SubItems.Add(result.Properties("userPrincipalName")(0).ToString())
		Else
			item = New ListViewItem(String.Format("User {0} not found", i))
		End If
	ElseIf Not results Is Nothing AndAlso results.Count > 0 Then
		'' Other statements here
		item = New ListViewItem(i)
		item.SubItems.Add(result.Properties("displayName")(0).ToString())
		item.SubItems.Add(result.Properties("title")(0).ToString())
		item.SubItems.Add(result.Properties("userPrincipalName")(0).ToString())
	Else
		item = New ListViewItem(i)
		item.SubItems.Add(result.Properties("displayName")(0).ToString())
		item.SubItems.Add(result.Properties("title")(0).ToString())
		item.SubItems.Add(result.Properties("userPrincipalName")(0).ToString())
	End If

	ListView1.Items.Add(item)
Next

Open in new window


-saige-
0
 

Author Comment

by:derek7467
ID: 40410904
ahh  thanks for making me think.  I had my variables under the else incorrect.  Thanks!  Works now.

I have another question, i changed my search criteria to specify departmentNumber and it only brings back one entry when i know there should be around 100, any reason you think im only receiving one result?
0
 
LVL 35

Expert Comment

by:it_saige
ID: 40411143
Did you add it as a filter or property?
Imports System.DirectoryServices
Imports System.Text

Module Module1
	Sub Main()
		Dim userIds As IEnumerable(Of String) = {"test1", "test2", "test3", "test4", "test5", "test6", "test7", "test8"}
		Dim de As DirectoryEntry
		Dim filter As String
		Dim searcher As DirectorySearcher
		Dim result As SearchResult
		Dim results As SearchResultCollection
		Dim users As New Dictionary(Of String, Dictionary(Of String, ResultPropertyValueCollection))
		Dim tempUser As Dictionary(Of String, ResultPropertyValueCollection)
		Dim write As New StringBuilder
		For Each i As String In userIds
			tempUser = New Dictionary(Of String, ResultPropertyValueCollection)
			de = New DirectoryEntry("LDAP://DC01/DC=domain1,DC=com")
			filter = String.Format("(sAMAccountName={0})", i)
			searcher = New DirectorySearcher(de, filter)
			result = searcher.FindOne()
			results = searcher.FindAll()

			If results Is Nothing OrElse results.Count <= 0 Then
				de = New DirectoryEntry("LDAP://DC02/OU=Users,DC=domain2,DC=com")
				filter = String.Format("(sAMAccountName={0})", i)
				searcher = New DirectorySearcher(de, filter)
				result = searcher.FindOne()
				If Not result Is Nothing Then
					tempUser.Add("Dispaly Name", result.Properties("displayName"))
					tempUser.Add("Departments", result.Properties("departmentNumber"))
					tempUser.Add("Title", result.Properties("title"))
					tempUser.Add("Principal Name", result.Properties("userPrincipalName"))
				Else
					tempUser.Add("Dispaly Name", Nothing)
					tempUser.Add("Departments", Nothing)
					tempUser.Add("Title", Nothing)
					tempUser.Add("Principal Name", Nothing)
				End If
			ElseIf Not results Is Nothing AndAlso results.Count > 0 Then
				'' Other statements here
				tempUser.Add("Dispaly Name", result.Properties("displayName"))
				tempUser.Add("Departments", result.Properties("departmentNumber"))
				tempUser.Add("Title", result.Properties("title"))
				tempUser.Add("Principal Name", result.Properties("userPrincipalName"))
			Else
				tempUser.Add("Dispaly Name", result.Properties("displayName"))
				tempUser.Add("Departments", result.Properties("departmentNumber"))
				tempUser.Add("Title", result.Properties("title"))
				tempUser.Add("Principal Name", result.Properties("userPrincipalName"))
			End If

			users.Add(i, tempUser)
		Next

		For Each user As KeyValuePair(Of String, Dictionary(Of String, ResultPropertyValueCollection)) In users
			write.AppendLine("================================================================================")
			write.AppendLine(String.Format("User: {0}", user.Key))
			For Each [Property] As KeyValuePair(Of String, ResultPropertyValueCollection) In user.Value
				write.Append(String.Format("{0}: ", [Property].Key))
				If Not [Property].Value Is Nothing Then
					Dim firstValue As Boolean = True
					For Each value As Object In [Property].Value
						If firstValue Then
							write.Append(value)
							firstValue = False
						Else
							write.Append(String.Format(", {0}", value))
						End If
					Next
				Else
					write.Append("No value defined for this property.")
				End If
				write.AppendLine()
			Next
			write.AppendLine("================================================================================")
			write.AppendLine()
		Next
		Console.WriteLine(write)
		Console.ReadLine()
	End Sub
End Module

Open in new window


-saige-
0

Featured Post

Simplify Active Directory Administration

Administration of Active Directory does not have to be hard.  Too often what should be a simple task is made more difficult than it needs to be.The solution?  Hyena from SystemTools Software.  With ease-of-use as well as powerful importing and bulk updating capabilities.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In real business world data are crucial and sometimes data are shared among different information systems. Hence, an agreeable file transfer protocol need to be established.
Simulator games are perfect for generating sample realistic data streams, especially for learning data analysis. It is even useful for demoing offerings such as Azure stream analytics, PowerBI etc.
This tutorial will walk an individual through the process of configuring their Windows Server 2012 domain controller to synchronize its time with a trusted, external resource. Use Google, Bing, or other preferred search engine to locate trusted NTP …
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …
Suggested Courses

613 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question