Jump to content

VB.NET & Active Directory

Hellooo,

 

Having an issue with AD in VB.Net and hoping someone on here will be able to help. I am very new to AD in VB so its probably a really simple solution but I can't seem to find it on google.

 

I need to connect to AD to pull a users details and searching by their username.

 

so the code I have is...

 

        Dim rootEntry As New System.DirectoryServices.DirectoryEntry("--Domain--")
        Dim searcher As New DirectorySearcher(rootEntry)
        Dim ctx As New PrincipalContext(ContextType.Domain)
        Dim user As UserPrincipal = UserPrincipal.FindByIdentity(ctx, txtUsername.Text)
        If user IsNot Nothing Then
        Else
            MessageBox.Show("Student is not found in Active Directory, please check the username and try again")
            Exit Sub
        End If

        searcher.PropertiesToLoad.Add("cn")
        searcher.PropertiesToLoad.Add("extensionAttribute1")
        searcher.PropertiesToLoad.Add("displayName")
        searcher.PropertiesToLoad.Add("mail")
        searcher.Filter = "(&(anr=" & txtUsername.Text & ")(objectCategory=person))"
        Dim results As SearchResultCollection
        results = searcher.FindAll()
        Dim result As SearchResult
        For Each result In results
            StudentName = result.Properties("displayName")(0)
            StudentNumber = result.Properties("extensionattribute1")(0)
            sEmail = result.Properties("mail")(0)
        Next
        Status.Text = "Loading data from SQL Database, This may take several minutes..."

and this works almost perfectly.... with this I can pull up a users email, full name, user ID all from just their username. There is no need to sign in with a username and password as AD is read only to everyone on the network. 

 

The problem is its not searching for the exact username typed into "txtusername.text" it seems to be using a "like" syntax. If I search for a user e.g "BG12AAM" then as ong as that is the only user with a username like that then it will pull the information I need. If there are two users "BG12AAM" & "BG12AAM1" then it will give me the details for the most recently added user. Even if I type "BG12AAM" in the textbox it gives me the details for "BG12AAM1" which I don't want.

 

Is there a way to search for the exact user typed?


Thanks,

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×