Solved

Returning Multiple Values from AD Query Function

Posted on 2014-11-26
8
237 Views
Last Modified: 2014-11-28
I have a visual basic application which connects to AD, uses the current logged on user's samAccountName to search for the account, and then pulls the extensionAttribute3-9 form the account and displays 1 as text, 3 as comboboxes and 3 as textboxes. However, although I can perform the AD query successfully, I can't get the values to extensionAttribute3-9 to return. Probably because a function can only return 1 result! So how can I get multiple results to be returned? Maybe load the query results into an array, and then return the array? Or some other better method?

My form code to call the function
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Try
            Dim currentADUser As System.DirectoryServices.AccountManagement.UserPrincipal
            currentADUser = System.DirectoryServices.AccountManagement.UserPrincipal.Current
            Dim DisplayName As String = currentADUser.GivenName & " " & currentADUser.Surname
            Username.Text = DisplayName
            extension3.Text = GetUserProperties()
            extension4TextBox.Text = GetUserProperties()
            extension5ComboBox.SelectedText = GetUserProperties()
        Catch ex As Exception
            MsgBox("No Connection to domain." & Environment.NewLine & "Please connect to corporate network & try again.", MsgBoxStyle.Critical, "Network Error #1")
            Application.Exit()
        End Try
    End Sub

Open in new window


My GetUserProperties() function code

 Private Function GetUserProperties()
        Dim ADName As String = GetLogonName()
        Dim bSuccess As Boolean = False
        Dim dirEntry As DirectoryEntry = GetDirectoryEntry()
        Dim dirSearcher As DirectorySearcher = New DirectorySearcher(dirEntry)
        Dim extension3 As Integer
        Dim extension4 As String
        dirSearcher.Filter = ("(samAccountName=" & ADName & ")")
        dirSearcher.PropertiesToLoad.Add("extensionAttribute3")
        dirSearcher.PropertiesToLoad.Add("extensionAttribute4")
        dirSearcher.PropertiesToLoad.Add("extensionAttribute5")
        dirSearcher.PropertiesToLoad.Add("extensionAttribute6")
        dirSearcher.PropertiesToLoad.Add("extensionAttribute7")
        dirSearcher.PropertiesToLoad.Add("extensionAttribute8")
        dirSearcher.PropertiesToLoad.Add("extensionAttribute9")
        dirSearcher.SearchScope = SearchScope.Subtree
        Try
            Dim dirResult As SearchResult = dirSearcher.FindOne()
            bSuccess = Not (dirResult Is Nothing)
            If dirResult Is Nothing OrElse dirResult.GetDirectoryEntry.Properties("extensionAttribute3").Value Is Nothing Then
                Return "<Not Set>"
            Else
                extension3 = (dirResult.Properties("extensionAttribute3")(0).ToString())
                extension4 = (dirResult.Properties("extensionAttribute4")(0).ToString())
                extension5 = (dirResult.Properties("extensionAttribute5")(0).ToString())
            End If
            Return extension3
        Catch ex As Exception
            bSuccess = False
            MsgBox("No Connection to the domain." & Environment.NewLine & "Please connect to corporate network & try again.", MsgBoxStyle.Critical, "Network Error #2")
            Application.Exit()
        End Try
        Return False
    End Function

Open in new window

0
Comment
Question by:bjblackmore
  • 3
  • 3
8 Comments
 
LVL 9

Expert Comment

by:p_sie
ID: 40468729
There are multiple options.
1. create 3 public variables in a module and assign the values to that variables in the function. Then you can use the variables in the form_load sub
2. create a structure or class with the 3 variables in it and let the function return a value of this structure or class.
0
 
LVL 15

Assisted Solution

by:ChloesDad
ChloesDad earned 100 total points
ID: 40468785
Another way would be to overload the function, have one return string, one a combo box and one a textbox

Private overloads Function GetUserProperty(attributename as string) as String

return somestring
end function

Private overloads Function GetUserProperty(attributename as string) as combobox

return somecombobox
end function

Private overloads Function GetUserProperty(attributename as string) as textbox

return sometextbox
end function

Open in new window


Then in the calling sub have 1 call to return a string, 3 to return a combobox and 3 to return a textbox. The code in each subroutine will be the same apart from this line

sometext= dirResult.Properties(attributename)(0).ToString

or

SomeCombobox= trycast(dirResult.Properties(attributename)(0),combobox)

or

Sometextbox = trycast(dirResult.Properties(attributename)(0),textbox)
0
 

Author Comment

by:bjblackmore
ID: 40468787
Do you have any example code I could use/modify? Or easy to follow tutorials? My visual basic skills are very basic. The code above is stuff I've managed get get from other projects/sites, and modify for use.
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 

Author Comment

by:bjblackmore
ID: 40468790
Thanks for the example code ChloesDad. I'll give it a try!
0
 
LVL 9

Accepted Solution

by:
p_sie earned 400 total points
ID: 40468817
Hi bjblackmore,

I tried to implement my suggestion in some code:

 Private Structure ADProperties
        Public Three As String
        Public Four As String
        Public Five As String
    End Structure

    Private Function GetUserProperties() As ADProperties

        '.... other code
        GetUserProperties.Three = "hello"
        GetUserProperties.Four = "number 4"
        GetUserProperties.Five = "Five"
        '.... more other code

    End Function

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Try
            Dim currentADUser As System.DirectoryServices.AccountManagement.UserPrincipal
            currentADUser = System.DirectoryServices.AccountManagement.UserPrincipal.Current
            Dim DisplayName As String = currentADUser.GivenName & " " & currentADUser.Surname
            Username.Text = DisplayName

            Dim ADProp As ADProperties = GetUserProperties()
            extension3.Text = ADProp.Three
            extension4TextBox.Text = ADProp.Four
            extension5ComboBox.SelectedText = ADProp.Five
        Catch ex As Exception
            MsgBox("No Connection to domain." & Environment.NewLine & "Please connect to corporate network & try again.", MsgBoxStyle.Critical, "Network Error #1")
            Application.Exit()
        End Try
    End Sub

Open in new window


You declare a structure ADProperties
Let the returnvalue of the function be of this structure
The declare a variable as this structure in form_load en set the value to the function GetUserProperties.
The you can set the values to the textboxes.

This is of course extendable to more variables in the structure.
0
 

Author Closing Comment

by:bjblackmore
ID: 40469235
Code worked. Was able to modify for my app use, and extend to a further 9 user attributes. Also the code sample helped me to easily understand how/why this worked, so hopefully I can use this again in the future!
0
 
LVL 9

Expert Comment

by:p_sie
ID: 40470619
Glad to hear it help you!
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
This tutorial gives a high-level tour of the interface of Marketo (a marketing automation tool to help businesses track and engage prospective customers and drive them to purchase). You will see the main areas including Marketing Activities, Design …
Windows 10 is mostly good. However the one thing that annoys me is how many clicks you have to do to dial a VPN connection. You have to go to settings from the start menu, (2 clicks), Network and Internet (1 click), Click VPN (another click) then fi…

863 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

24 Experts available now in Live!

Get 1:1 Help Now