views:

28

answers:

1

I'm using the following code, which works, to login a user to an application built in VB.NET against active directory.

This code works great but I need to retreive the user's first name, last name, display name and also check if the user is part of a group.

I've tried many forms of adResults.Property("displayname").ToString() and the like but just can't get it to work right.

Anyone have any ideas how to do what I'm looking to do?

Here's the code I'm using now and thanks in advance.

Public Function ValidateActiveDirectoryLogin(ByVal sDomain As String, ByVal sUserName As String, ByVal sPassword As String) As Boolean

    Dim bSuccess As Boolean = False
    Dim adEntry As New System.DirectoryServices.DirectoryEntry("LDAP://" & sDomain, sUserName, sPassword)
    Dim adSearcher As New System.DirectoryServices.DirectorySearcher(adEntry)
    adSearcher.SearchScope = DirectoryServices.SearchScope.OneLevel
    Try
        Dim adResults As System.DirectoryServices.SearchResult = adSearcher.FindOne
        bSuccess = Not (adResults Is Nothing)
    Catch ex As Exception
        bSuccess = False
        MsgBox("Error")
    End Try

    Return bSuccess

End Function 
+1  A: 

Look at the System.DirectoryServices.AccountManagemment namespace. The userprincipal object has everything you need and more. Here's an explanation on how to use this API.

EDIT: it's really much simpler to use actually. Have a look at this sample code:

Dim userName = Environment.UserName

' create a domain context
Dim DC = New PrincipalContext(ContextType.Domain)

' find a user in the domain
Dim user = UserPrincipal.FindByIdentity(DC, userName)

' get the user's groups
Dim groups = user.GetGroups()

' get the user's first and last name
Dim firstName = user.GivenName
Dim lastName = user.SurName

' get the distinguishednames for all groups of the user
Dim groupNames = From g in groups Select g.DistinguishedName
' etc...
jeroenh
Indeed that is definitely more than I'm looking for but if it's the only way to get what I need I'll definitely take a look at it but is there anyway to retreive user information from the System.DirectoryServices.SearchResult object? It'd be nice to keep it as simple as possible. Thanks =)
Tom
@Tom it's really much simpler to use actually, have a look at my edit
jeroenh
Wow, that was easy. Thanks.
Tom