Solved

Autocomplete in VB.net using LDAP usernames

Posted on 2012-03-14
18
691 Views
Last Modified: 2012-03-24
I am trying to create an auto complete textbox in VB.net using username in LDAP
I am using this in other parts of the code.

Public Shared Function GetUser(ByVal UserName As String) As DirectoryEntry
    'create an instance of the DirectoryEntry
    Dim dirEntry As DirectoryEntry = GetDirectoryObject("/" + GetLDAPDomain())

    'create instance fo the direcory searcher
    Dim dirSearch As New DirectorySearcher(dirEntry)

    dirSearch.SearchRoot = dirEntry
    'set the search filter
    dirSearch.Filter = "(&(objectCategory=user)(cn=" + UserName + "))"
    'deSearch.SearchScope = SearchScope.Subtree;

    'find the first instance
    Dim searchResults As SearchResult = dirSearch.FindOne()

    'if found then return, otherwise return Null
    If Not searchResults Is Nothing Then
        'de= new DirectoryEntry(results.Path,ADAdminUser, _
             ADAdminPassword,AuthenticationTypes.Secure);
        'if so then return the DirectoryEntry object
        Return searchResults.GetDirectoryEntry()
    Else
        Return Nothing
    End If
End Function

Open in new window

Can it be done?
0
Comment
Question by:r3nder
  • 11
  • 6
18 Comments
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 37726169
You can remove the filter to get all users back and then use that as autocomplete source.
0
 
LVL 6

Author Comment

by:r3nder
ID: 37727861
I removed the filter and changed the function name

In the page load
       
 Try

            ADWrapper.AutoPopulateUser(UserName)
            txtUser.AutoCompleteCustomSource.Clear()
 
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try

Open in new window


How whould I add it to a loop to start
0
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 37730330
You changed it to do a FindAll instead of FindOne and used a searchresultcollection class right?

http://msdn.microsoft.com/en-us/library/system.directoryservices.directorysearcher.findall.aspx
0
 
LVL 6

Author Comment

by:r3nder
ID: 37730490
This is what I did
 Public Shared Function AutoPopulateUser(ByVal UserName As String) As DirectoryEntry
            'create an instance of the DirectoryEntry
            Dim dirEntry As DirectoryEntry = GetDirectoryObject("/" + GetLDAPDomain())

            'create instance fo the direcory searcher
            Dim dirSearch As New DirectorySearcher(dirEntry)

            dirSearch.SearchRoot = dirEntry
            'set the search filter
            'dirSearch.Filter = "(&(objectCategory=user)(cn=" + UserName + "))"
            'deSearch.SearchScope = SearchScope.Subtree;

            'find the first instance
            Dim searchResults As SearchResultCollection = dirSearch.FindAll()

            'if found then return, otherwise return Null
            If Not searchResults Is Nothing Then
                'de= new DirectoryEntry(results.Path,ADAdminUser,ADAdminPassword,AuthenticationTypes.Secure);
                'if so then return the DirectoryEntry object
                Return searchResults.GetEnumerator()
            Else
                Return Nothing
            End If
        End Function

Open in new window

now how do I loop through it to get results?
Thank you for the help
0
 
LVL 6

Author Comment

by:r3nder
ID: 37730572
Do I  use the on text changed for the text box and call the AutoPopulateUser and use the searchresults (Dim serachresults)in the pageload
0
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 37730618
Use the ForEach on SearchResults object to populate a list of string.

Call the function to populate the list of string on form load. Then set the textbox properties and it will take care of using the list to make suggestions or append matching names depending on your chosen mode.
0
 
LVL 6

Author Comment

by:r3nder
ID: 37730697
so.......not getting it?
Dim results As List(Of String) = New List(Of String)
	vals.Add("???")
	vals.Add("???")
	vals.Add("???")

        Try

            ADWrapper.AutoPopulateUser(Nothing)
            Dim results = ADWrapper.AutoPopulateUser(searchResults)
            txtUser.AutoCompleteCustomSource.Clear()
            For Each s In results
                txtUser.AutoCompleteCustomSource.Add(s)

            Next

        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try

Open in new window

0
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 37731459
Modify your function so that it returns a list(of string). Then in function

change

            If Not searchResults Is Nothing Then
                'de= new DirectoryEntry(results.Path,ADAdminUser,ADAdminPassword,AuthenticationTypes.Secure);
                'if so then return the DirectoryEntry object
                Return searchResults.GetEnumerator()
            Else
                Return Nothing
            End If

Open in new window



to


    Dim names As New List(of String)
            If Not searchResults Is Nothing Then
               For Each result in SearchResults
                    names.Add(result.GetDirectoryEntry().Name)
               Next
            End If
     Return Names

Open in new window


Once you have this list of names, we will move to next part.
0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 6

Author Comment

by:r3nder
ID: 37731843
Done please see code I also had to Dim the result

       
 Public Shared Function AutoPopulateUser(ByVal UserName As String) As List(Of String)
            'Public Shared Function AutoPopulateUser() As DirectoryEntry
            'create an instance of the DirectoryEntry
            Dim dirEntry As DirectoryEntry = GetDirectoryObject("/" + GetLDAPDomain())

            'create instance fo the direcory searcher
            Dim dirSearch As New DirectorySearcher(dirEntry)

            dirSearch.SearchRoot = dirEntry
            'set the search filter
            'dirSearch.Filter = "(&(objectCategory=user)(cn=" + UserName + "))"
            'deSearch.SearchScope = SearchScope.Subtree;

            'find the first instance
            Dim searchResults As SearchResultCollection = dirSearch.FindAll()

            'if found then return, otherwise return Null
            Dim result
            Dim names As New List(Of String)
            If Not searchResults Is Nothing Then
                For Each result In searchResults
                    names.Add(result.GetDirectoryEntry().Name)
                Next
            End If
            Return names

        End Function

Open in new window

0
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 37733833
So now you successfully get a list of names?

Set the list of names as AutoCompleteSource property of the textbox. See example in below link

http://msdn.microsoft.com/en-us/library/system.windows.forms.textbox.autocompletesource.aspx
0
 
LVL 6

Author Comment

by:r3nder
ID: 37734013
Does this look correct? - I dont know if it takes a  long time to query or if its not working
but its not doing autocomplete

       
Dim mSource As New AutoCompleteStringCollection()
        mSource.Add(ADWrapper.AutoPopulateUser(txtUser.Text).ToString())
        With txtUser
            txtUser.AutoCompleteCustomSource = mSource
            .AutoCompleteMode = AutoCompleteMode.SuggestAppend
            .AutoCompleteSource = AutoCompleteSource.CustomSource
            .Visible = True
        End With

Open in new window

0
 
LVL 6

Author Comment

by:r3nder
ID: 37753224
Here is my updated code can anyone tell me why ADentry in Dim Ds As New List(of ADEntry) undefined?
        Try
            Dim ADEntry As New AutoCompleteStringCollection()
            Dim Ds As New List(Of ADEntry)()
            Ds = New DirectoryEntry("MYSERVER", "MYUSERNAME", "MYPASSWORD")
            Dim dt As New DataTable()
            dt.Columns.Add("Name", GetType(String))
            dt.Columns.Add("Email", GetType(String))
            For Each adentry As ADEntry In Ds
                Dim dr As DataRow = dt.NewRow()
                For i As Integer = 0 To adentry.Information.Count - 1
                    If adentry.Information(i).Key = "mail" Then
                        dr("Email") = adentry.Information(i).Value
                    End If
                    If adentry.Information(i).Key = "displayname" Then
                        dr("Name") = adentry.Information(i).Value
                    End If
                Next
                If Not dr("Email").ToString().Equals("") Then
                    dt.Rows.Add(dr)
                End If
            Next

Open in new window

0
 
LVL 6

Author Comment

by:r3nder
ID: 37754808
Could anyone help with this - I have my function in my class it returns a List(Of string)
I am trying to auto populate it in a textbox I have - how do I assign the List(of string) from that function
My Auto complete code is
        Try
            Dim mSource As New AutoCompleteStringCollection()
            mSource.AddRange(ADWrapper.AutoPopulateUser(txtUser.Text))


            With txtUser
                txtUser.AutoCompleteCustomSource = mSource
                .AutoCompleteMode = AutoCompleteMode.SuggestAppend
                .AutoCompleteSource = AutoCompleteSource.CustomSource
                .Visible = True
            End With
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try

Open in new window


my function in the class is (and this works)
       Public Shared Function AutoPopulateUser(ByVal UserName As String) As List(Of String)
            'Public Shared Function AutoPopulateUser() As DirectoryEntry
            'create an instance of the DirectoryEntry
            Dim dirEntry As DirectoryEntry = GetDirectoryObject("/" + GetLDAPDomain())

            'create instance fo the direcory searcher
            Dim dirSearch As New DirectorySearcher(dirEntry)

            dirSearch.SearchRoot = dirEntry
            'set the search filter
            'dirSearch.Filter = "(&(objectCategory=user)(cn=" + UserName + "))"
            'deSearch.SearchScope = SearchScope.Subtree;

            'find the first instance
            Dim searchResults As SearchResultCollection = dirSearch.FindAll()

            'if found then return, otherwise return Null
            Dim result
            Dim names As New List(Of String)
            If Not searchResults Is Nothing Then
                For Each result In searchResults
                    names.Add(result.GetDirectoryEntry().Name)
                Next
            End If
            Return names

Open in new window


can someone PLEASE HELP
0
 
LVL 6

Author Comment

by:r3nder
ID: 37755455
Am I close? it keeps telling me UserName is undefined
       
 Try
            Dim mSource As New AutoCompleteStringCollection()
            Dim UserName As New List(Of String)
            Dim suggestions As List(Of String) = New List(Of String)(New String() {ADWrapper.AutoPopulateUser(Username)})


            mSource.AddRange(suggestions.ToArray)


            With txtUser
                txtUser.AutoCompleteCustomSource = mSource
                .AutoCompleteMode = AutoCompleteMode.SuggestAppend
                .AutoCompleteSource = AutoCompleteSource.CustomSource
                .Visible = True
            End With
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try

Open in new window

Any help please?  would be greatly appreciatred
0
 
LVL 6

Author Comment

by:r3nder
ID: 37755637
i found the problem with UserName now it is telling me
Value of type 'System.Collections.Generic.List(Of String)' cannot be converted to 'String'.
Any help is always appreciated
0
 
LVL 6

Author Comment

by:r3nder
ID: 37759380
I found it - it works now
0
 
LVL 83

Accepted Solution

by:
CodeCruiser earned 500 total points
ID: 37761240
I helped you half the way didn't i?
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

We were having a lot of "Heartbeat Alerts" in our SCOM environment, now "Heartbeat" in a SCOM environment for those of you who might not be familiar with SCOM is a packet of data sent from the agent to the management server on a regular basis, basic…
The System Center Operations Manager 2012, known as SCOM, is a part of the Microsoft system center product that provides the user with infrastructure monitoring and application performance monitoring. SCOM monitors:   Windows or UNIX/LinuxNetwo…
Viewers will learn how to maximize accessibility options in an Excel workbook for users with accessibility issues.
The viewer will learn how to use a discrete random variable to simulate the return on an investment over a period of years, create a Monte Carlo simulation using the discrete random variable, and create a graph to represent the possible returns over…

747 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