vb.net ldap querying 2 domains at same time - vb.net

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
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!

ahh, had my variables wrong in the else portion!
hope this helps someone else.

Related

How to retrieve properties for an Active Directory user using DirectorySearcher in VB.Net

I am trying to retrieve the email address for a known Active Directory user by using their login ID and the DirectorySearcher.FindOne() method in VB.Net but I have been unable to get any results.
Sorry but I am new to VB.Net and do not know where I am going wrong. I have tried using various examples that I have found on the net but they all are in C#. I have been able to convert the code to VB but I am still not able to pull results using what I have found. In the latest example I found here! it is using the FindAll() method and putting the results in a SearchResultCollection object. The collection ended up with a count of 0 so I have tried using the FindOne() method and tried to put the result in a SearchResult object. This didn't work for me either.
Public Shared Sub RetrieveUser(ByVal username As String)
Dim propUsername As String = "samaccountname"
Dim propFirstName As String = "givenName"
Dim propLastName As String = "sn"
Dim propDisplayName As String = "cn"
Dim propMail As String = "mail"
Dim propGuid As String = "objectguid"
Dim results As SearchResultCollection
Dim result As SearchResult
Dim directoryEntry As DirectoryEntry = New DirectoryEntry("LDAP_PATH", "DOMIAIN\USERNAME", "PASSWORD", AuthenticationTypes.ServerBind)
Using directorySearcher As DirectorySearcher = New DirectorySearcher(directoryEntry)
directorySearcher.PropertiesToLoad.Add(propUsername)
directorySearcher.PropertiesToLoad.Add(propDisplayName)
directorySearcher.PropertiesToLoad.Add(propFirstName)
directorySearcher.PropertiesToLoad.Add(propLastName)
directorySearcher.PropertiesToLoad.Add(propMail)
directorySearcher.PropertiesToLoad.Add(propGuid)
directorySearcher.Filter = String.Format("({0})", "&(objectClass=user)(cn=" & username & ")")
directorySearcher.SearchScope = SearchScope.Subtree
' directorySearcher.SearchRoot.AuthenticationType = AuthenticationTypes.Secure
directorySearcher.PageSize = 100
'results = directorySearcher.FindAll()
result = directorySearcher.FindOne()
'For Each result In results
If result.Properties.Contains(propUsername) Then
Console.WriteLine("User Name: " & result.Properties(propUsername)(0))
End If
If result.Properties.Contains(propGuid) Then
Console.WriteLine("User GUID: " & BitConverter.ToString(CType(result.Properties(propGuid)(0), Byte())).Replace("-", String.Empty))
End If
If result.Properties.Contains(propMail) Then
Console.WriteLine("Mail ID: " & result.Properties(propMail)(0))
End If
If result.Properties.Contains(propDisplayName) Then
Console.WriteLine("DisplayName: " & result.Properties(propDisplayName)(0))
End If
'Next
directorySearcher.Dispose()
directoryEntry.Dispose()
End Using
End Sub

Searching AD for a printer using VB.net

I am using VB.net, trying to query Active Directory to check and see if a printer exists there. I have an AD connection but it doesn't seem to return any values when I run the code. Here is the snippet of my code
Dim searchResults As New ArrayList
Dim myDirectorySearcher As New DirectorySearcher(myDirectoryEntry))
Dim targetObject as string = "printerName"
Dim searchFilter as string = "cn"
Dim strFilter = "(&(objectClass=printer)(" & searchFilter & "=" & targetObject & "))"
myDirectorySearcher.Filter = strFilter
myDirectorySearcher.CacheResults = False
For i = 0 To searchCriteria.Count - 1
myDirectorySearcher.PropertiesToLoad.Add(searchCriteria(i).ToString)
Next
Dim mySearchResult As SearchResult = myDirectorySearcher.FindOne()
Tried various methods but nothing seems to be working, any advice would be much appreciated.
I had to do something similar to this with a project I was working on at work. In short, I think you might be searching under the wrong objectClass in ActiveDirectory.
Printers sometimes get added under printQueue.
Your code would then be something like:
Dim searchResults As New ArrayList
Dim myDirectorySearcher As New DirectorySearcher(myDirectoryEntry))
Dim targetObject as string = "printerName"
Dim strFilter = "(&(objectClass=printQueue)(cn=" & targetObject & "))"
myDirectorySearcher.Filter = strFilter
myDirectorySearcher.CacheResults = False
For i = 0 To searchCriteria.Count - 1
myDirectorySearcher.PropertiesToLoad.Add(searchCriteria(i).ToString)
Next
Dim mySearchResult As SearchResult = myDirectorySearcher.FindOne()
It is also worth bearing in mind that sometimes the printerName will have the domain appended to the end, so your query may not always return the results you would expect.
For example your printer name may be PRINTER-RECEPTION but is referenced on your domain with PRINTER-RECEPTION.MYCOMPANY.DOMAIN.
Hope this helps you.

vb.net ldap query try catch statement

Ok i have the below code that works, it looks up users that could be a part of 2 domains. The logic works. I wrapped a try-catch statement to catch blanks or users that dont exist. Basically im thinking, ill see an error everytime a user is blank or doesnt exist, ill handle it with a try-catch. Then in my try-catch, im added the ID searched and some text to a listview. It works, but its added a blank line with just the wrong ID and then it adds the line with ID and the text i want. Not sure if my try-catch is in wrong order?
Dim userIds As IEnumerable(Of String) = {"idthatworks", "idthatworks", "doesntwork", "idthatworks", "doesntwork"}
For Each i As String In userIds
Try
Dim de As New DirectoryEntry("LDAP://domain1.net:389/DC=domain1,DC=net")
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 = TDsearcher.FindOne()
Dim item As ListViewItem = ListView1.Items.Add(i)
item.SubItems.Add(TDresult.Properties("givenName")(0).ToString())
item.SubItems.Add(TDresult.Properties("cn")(0).ToString())
item.SubItems.Add(TDresult.Properties("userPrincipalName")(0).ToString())
ElseIf Not res.Count <= 0 Then
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
Catch ex As Exception
Dim item As ListViewItem = ListView1.Items.Add(i)
item.SubItems.Add("Not found in US or CA Domain")
item.SubItems.Add("Not found in US or CA Domain")
item.SubItems.Add("Not found in US or CA Domain")
End Try
Next

Looping through each item in a ListBox control with VB.NET

I wrote the below program to look up an LDAP user and return back a property. The way I need it to work is as follows: first I will load a list of user ID's into ListBox1, then when I click a button a property (such as DisplayName) will be appended to ListBox2. Right now I have to click on an item in ListBox1 and then click the button and it works, but I want it to loop through every ID in ListBox1 and write the properties for all of them to ListBox2 without me having to click on each user ID. How can I put the below in a for each loop?
Dim de As New DirectoryEntry("LDAP://test.com/DC=test,DC=com")
Dim LdapFilter As String = "(sAMAccountName=" & ListBox1.Text & ")"
Dim searcher As New DirectorySearcher(de, LdapFilter)
Dim result As SearchResult = searcher.FindOne()
ListBox2.Items.Add(result.Properties("displayName")(0).ToString())
Update
I tried to use a ListView to display two columns, as suggested. It's not working, however. It just adds the ListView columns:
Dim item As ListViewItem = ListView1.Items.Add("Username")
Dim item1 As ListViewItem = ListView1.Items.Add("Title")
For Each i As String In ListBox1.Items
Dim de As New DirectoryEntry("LDAP://test.com/DC=test,DC=com")
Dim LdapFilter As String = "(sAMAccountName=" & i & ")"
Dim searcher As New DirectorySearcher(de, LdapFilter)
Dim result As SearchResult = searcher.FindOne()
item.SubItems.Add(result.Properties("sAMAccountName")(0).ToString())
item1.SubItems.Add(result.Properties("title")(0).ToString())
Dim ADEntry As DirectoryEntry = New DirectoryEntry(result.Path)
If result.Properties("displayName") Is Nothing Then
On Error Resume Next
End If
Next
You shouldn't really be using the ListBox1.Text property. It's rather confusing. In this case, you want to loop through all of the strings in the ListBox1.Items list (presuming they are actually strings). For instance:
For Each i As String in ListBox1.Items
Dim de As New DirectoryEntry("LDAP://test.com/DC=test,DC=com")
Dim LdapFilter As String = "(sAMAccountName=" & i & ")"
Dim searcher As New DirectorySearcher(de, LdapFilter)
Dim result As SearchResult = searcher.FindOne()
ListBox2.Items.Add(result.Properties("displayName")(0).ToString())
Next
Or, if ListBox1 doesn't actually contain strings, you could loop through them as Object and call the ToString method on each one, like this:
For Each i As Object in ListBox1.Items
Dim de As New DirectoryEntry("LDAP://test.com/DC=test,DC=com")
Dim LdapFilter As String = "(sAMAccountName=" & i.ToString() & ")"
Dim searcher As New DirectorySearcher(de, LdapFilter)
Dim result As SearchResult = searcher.FindOne()
ListBox2.Items.Add(result.Properties("displayName")(0).ToString())
Next
As I mentioned in the comments below, rather than using two separate ListBox controls, it would be preferable to use a ListView control with two columns. For instance, if you had a ListView1 control with three columns (entitled "ID", "Username", and "Title"), then you could add the items like this:
Dim userIds As IEnumerable(Of String) = getAllLdapUserIds() ' Get the list of ID's using whatever means you are currently using
For Each i As String In userIds
Dim de As New DirectoryEntry("LDAP://test.com/DC=test,DC=com")
Dim LdapFilter As String = "(sAMAccountName=" & i & ")"
Dim searcher As New DirectorySearcher(de, LdapFilter)
Dim result As SearchResult = searcher.FindOne()
Dim item As ListViewItem = ListView1.Items.Add(i)
item.SubItems.Add(result.Properties("sAMAccountName")(0).ToString())
item.SubItems.Add(result.Properties("title")(0).ToString())
Next

How do I get the users that belong to a group in Active Directory?

I have a dropdownlist that I am trying to fill with users that belong to a certain group in Active Directory.
The group name is OverRiders and 8 people are members of this group. More members could be added.
I have the following dropdown but I run the code, the dropdown is blank.
What am I doing wrong?
Please see code:
Private Sub FillDropdown()
Dim oroot As DirectoryEntry = New DirectoryEntry("LDAP://CN=OverRiders,OU=Departments,DC=domain,DC=com")
Dim osearcher As DirectorySearcher = New DirectorySearcher(oroot)
Dim oresult As SearchResultCollection
Dim result As SearchResult
Dim list As New List(Of String)
osearcher.Filter = "(&(objectCategory=group)(cn={0}))"
' search filter; only display emp with firstname / lastname pair
osearcher.PropertiesToLoad.Add("name") ' member
oresult = osearcher.FindAll()
For Each result In oresult
If Not result.GetDirectoryEntry.Properties("name").Value Is Nothing Then
list.Add(result.GetDirectoryEntry.Properties("name").Value.ToString())
Call list.Sort()
End If
Next
emplist.DataSource = list
emplist.DataBind()
End Sub
I have been able to confirm that the group does exist and the group name is valid.
Thanks a lot in advance
Changed:
Dim oroot As DirectoryEntry = New DirectoryEntry("LDAP://CN=OverRiders,OU=Departments,DC=domain,DC=com")
to
Dim oroot As DirectoryEntry = New DirectoryEntry("LDAP://DC=domain,DC=com")
and this:
osearcher.Filter = "(&(objectCategory=group)(cn={0}))"
to this:
osearcher.Filter = "(&(objectCategory=user)(memberOf=CN=overRiders,OU=Departments,DC=domain,DC=com)‌​)"
Everything else remain unchanged.
Hope it helps someone else.
I know this is an old question, but this is what worked for me in a similar situation:
Dim UsersInGroup As New Collection()
Dim de As New DirectoryEntry("LDAP://[Domain]")
Dim MemberSearcher As New DirectorySearcher
With MemberSearcher
.SearchRoot = de
.Filter = "(&(ObjectClass=Group)(CN=" & Group & "))"
.PropertiesToLoad.Add("Member")
End With
Dim mySearchResults As SearchResult = MemberSearcher.FindOne()
For Each User In mySearchResults.Properties("Member")
UsersInGroup.Add(User)
Next