Solved

vb.net and ldap query results handling

Posted on 2014-11-17
4
221 Views
Last Modified: 2014-11-20
I wrote the below program to query a list of usernames.  What it does is this - it queries domain1 and if no match it queries domain2.  What i need help with is how to return my own defined values if the username isnt found in either domain.  Right now im handling it in a try-catch but thats not the right way:

Dim userIds As String() = TextBox1.Text.Split(New String() {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
        For Each i As String In userIds
            Try
                Dim de As New DirectoryEntry("domain1.com/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/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)
                    Dim ADEntry As DirectoryEntry = New DirectoryEntry(TDresult.Path)

                    If ADEntry.Properties("displayName").Value Is Nothing Then
                        item.SubItems.Add("Attribute not found")
                    Else
                        item.SubItems.Add(TDresult.Properties("displayName")(0).ToString())
                    End If

                    If ADEntry.Properties("title").Value Is Nothing Then
                        item.SubItems.Add("Attribute not found")
                    Else
                        item.SubItems.Add(TDresult.Properties("title")(0).ToString())
                    End If

                    If ADEntry.Properties("userPrincipalName").Value Is Nothing Then
                        item.SubItems.Add("Attribute not found")
                    Else
                        item.SubItems.Add(TDresult.Properties("userPrincipalName")(0).ToString())
                    End If

                ElseIf Not res.Count <= 0 Then
                    Dim ADEntry As DirectoryEntry = New DirectoryEntry(result.Path)
                    Dim item As ListViewItem = ListView1.Items.Add(i)

                    If ADEntry.Properties("manager").Value Is Nothing Then
                        item.SubItems.Add("Attribute not found")
                    Else
                        item.SubItems.Add(ADEntry.Properties("manager")(0).ToString())
                    End If

                    If ADEntry.Properties("title").Value Is Nothing Then
                        item.SubItems.Add("Attribute not found")
                    Else
                        item.SubItems.Add(ADEntry.Properties("title")(0).ToString())
                    End If

                    If ADEntry.Properties("userPrincipalName").Value Is Nothing Then
                        item.SubItems.Add("Attribute not found")
                    Else
                        item.SubItems.Add(ADEntry.Properties("userPrincipalName")(0).ToString())
                    End If
                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

Open in new window


Basically i want to remove the try-catch and actually check if the user is not found in either domain then return the below values to my listview.
0
Comment
Question by:derek7467
  • 3
4 Comments
 

Author Comment

by:derek7467
Comment Utility
no one can help?
0
 
LVL 35

Accepted Solution

by:
Robert Schutt earned 500 total points
Comment Utility
I tried your code but initially I wrestled with some problems that prevented me from successfully testing the process as you describe it. So I changed a few things around and I think I got to what you're describing. It's not that complicated in itself but those things may have prevented other experts from taking on this question (not really important, just trying to offer a possible explanation/excuse for why you did not get a prompt response).

* the posted code contains html encoded characters, not a big problem but we shouldn't need to clean up the code before we can even begin trying to help you;
* you did not describe the form elements and references needed to get your code working, again not a big problem just raising the threshold a little more;
* there is a difference in the if/else blocks that may be on purpose but could also be a mistake (displayName vs manager), I left that as it was;
* It's not clear why you would need findOne() as well as findAll(), again this could be on purpose but could also be a mistake, I changed it to use only findOne() because there is no use of wildcards and account names should be unique.

So please don't take offense, just trying to explain how a better formulated question might have gotten more/better/quicker responses...

After all that, below is my version of the code which seems to do the trick. Note that I still use "Try ... Catch" but only to catch connect errors and other errors not related to the searching itself, which can just be verified against Nothing.
Imports System.DirectoryServices

Public Class Form1

    Const C_DOMAIN1 As String = "LDAP://domain1.com/DC=domain1,DC=com"
    Const C_DOMAIN2 As String = "LDAP://domain2.com/DC=domain2,DC=com"

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

        Dim de As DirectoryEntry, tdbfg As DirectoryEntry, ADEntry As DirectoryEntry, res As SearchResult, item As ListViewItem

        Try
            de = New DirectoryEntry(C_DOMAIN1)
            tdbfg = New DirectoryEntry(C_DOMAIN2)
        Catch ex As Exception
            MsgBox("could not contact one of the servers: " & ex.Message)
            Exit Sub
        End Try

        Dim userIds As String() = TextBox1.Text.Split(New String() {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)

        ListView1.Items.Clear()

        For Each i As String In userIds
            item = ListView1.Items.Add(i)
            Try
                Dim LdapFilter As String = "(sAMAccountName=" & i & ")"
                Using searcher As New DirectorySearcher(de, LdapFilter)

                    res = searcher.FindOne() ' search DOMAIN1

                    If res Is Nothing Then ' not found on DOMAIN1

                        Using TDsearcher As New DirectorySearcher(tdbfg, LdapFilter)

                            res = TDsearcher.FindOne() ' search DOMAIN2

                            If res Is Nothing Then ' not found on DOMAIN2 either

                                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")

                            Else ' found on DOMAIN2 !

                                ADEntry = New DirectoryEntry(res.Path)

                                If ADEntry.Properties("displayName").Value Is Nothing Then
                                    item.SubItems.Add("Attribute not found")
                                Else
                                    item.SubItems.Add(ADEntry.Properties("displayName")(0).ToString())
                                End If

                                If ADEntry.Properties("title").Value Is Nothing Then
                                    item.SubItems.Add("Attribute not found")
                                Else
                                    item.SubItems.Add(ADEntry.Properties("title")(0).ToString())
                                End If

                                If ADEntry.Properties("userPrincipalName").Value Is Nothing Then
                                    item.SubItems.Add("Attribute not found")
                                Else
                                    item.SubItems.Add(ADEntry.Properties("userPrincipalName")(0).ToString())
                                End If

                            End If
                        End Using

                    Else ' found on DOMAIN1 !

                        ADEntry = New DirectoryEntry(res.Path)

                        If ADEntry.Properties("manager").Value Is Nothing Then
                            item.SubItems.Add("Attribute not found")
                        Else
                            item.SubItems.Add(ADEntry.Properties("manager")(0).ToString())
                        End If

                        If ADEntry.Properties("title").Value Is Nothing Then
                            item.SubItems.Add("Attribute not found")
                        Else
                            item.SubItems.Add(ADEntry.Properties("title")(0).ToString())
                        End If

                        If ADEntry.Properties("userPrincipalName").Value Is Nothing Then
                            item.SubItems.Add("Attribute not found")
                        Else
                            item.SubItems.Add(ADEntry.Properties("userPrincipalName")(0).ToString())
                        End If
                    End If
                End Using

            Catch ex As Exception
                item.SubItems.Add("Error: " & ex.Message)
            End Try
        Next

    End Sub
End Class

Open in new window

Final remarks; some parts could be simplified, especially if you actually want to show the same properties from both domains. Also, checking the properties for Nothing is now repeated many times, this should be made into a subroutine. This also makes it more flexible if you would want to change it later to show all instead of just the first entry in multi-valued fields.
capture
0
 

Author Comment

by:derek7467
Comment Utility
thank you very much, i will try this as soon as i can and post back.
0
 

Author Closing Comment

by:derek7467
Comment Utility
Appreciate you taking the time to do this.  It worked flawlessly, i really owe you.  Thanks for not just giving me an answer but helping me make a better question next time!
0

Featured Post

Why spend so long doing email signature updates?

Do you spend loads of your time carrying out email signature updates? Not very interesting are they? Don’t let signature updates get you down. Let Exclaimer Cloud - Signatures for Office 365 make managing email signatures a breeze.

Join & Write a Comment

Creating and Managing Databases with phpMyAdmin in cPanel.
Find out how to use Active Directory data for email signature management in Microsoft Exchange and Office 365.
This tutorial will walk an individual through the steps necessary to join and promote the first Windows Server 2012 domain controller into an Active Directory environment running on Windows Server 2008. Determine the location of the FSMO roles by lo…
This tutorial will walk an individual through the process of transferring the five major, necessary Active Directory Roles, commonly referred to as the FSMO roles from a Windows Server 2008 domain controller to a Windows Server 2012 domain controlle…

771 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now