Thursday, December 29, 2011

How to use WinNT or LDAP to query users and group

Recently, I got a problem. We have a piece of code built by a contractor. It validate if a user belong to a distribution group in Active Directory. The group is in Domain A, but a lot of users in this group belong to other domains. The code worked when user belong to the same domain as the group but it didn't work when users belong to different domains.

Originally, the contractor used WinNT to query the group. I did some search online and didn't find a simple way to solve my problem. I asked our IT guys and he said we may disable the search for querying other domains. Alright, let's try something different.

I am typically a C# developer, but this code block was build in VB. I found a piece of code from the here . I changed it to VB and it worked find. However, the only downside is it will loop the entire group every time. Anyway, who cares....

Now I have no problem to find out if a user belong to a certain group. And I don't have what domain it belong to. The query result handles everything.

  Shared Function ValidUser(ByVal User As String) As Boolean

        Try
        
            Dim ent As New DirectoryEntry("LDAP://DC=" + "ITG" + ",DC=com")
            Dim srch As New DirectorySearcher("(CN=" + "_Onyx_Lookup" + ")")
            Dim coll As SearchResultCollection = srch.FindAll()
            For Each rs As SearchResult In coll
                Dim resultPropColl As ResultPropertyCollection = rs.Properties
                For Each memberColl As [Object] In resultPropColl("member")
                    Dim gpMemberEntry As New DirectoryEntry("LDAP://" + memberColl.ToString())
                    Dim userProps As System.DirectoryServices.PropertyCollection = gpMemberEntry.Properties
                    Dim obVal As Object = userProps("sAMAccountName").Value
                    If obVal IsNot Nothing Then
                    
                        If obVal.ToString() = User.ToString() Then
                            Return True
                        End If
                    End If
                   
                Next
            Next
            Return False
        Catch ex As Exception
            Return False
        End Try
       
    End Function