Convert from VBA to VB.net - AD user?

ahbenshaut

Well-known member
Joined
Oct 29, 2004
Messages
62
Location
Alaska
Programming Experience
5-10
I found the following code that is supposed to determine whether or not a user is a member of a particular Active Directory group but I am having trouble converting it to VB.net. I have added the Active DS Type Library to my project references.

VB.NET:
Function IsMember(ByVal strDomain As String, ByVal strGroup As String, ByVal strMember As String) As Boolean
        'Dim grp As Object
        Dim strPath As String
        Dim grp As ActiveDs.IADsGroup

        strPath = "WinNT://" & strDomain & "/"
        grp = GetObject(strPath & strGroup & ",group")
        IsMember = grp.IsMember(strPath & strMember)
    End Function
Any help is greatly appreciated!
 
Try to avoid using COM unless absolutely nessesary.

You can do what you're after using DirectoryServices.

I didn't write this BTW. Just incase the guy that did is around here somewhere. :)

PublicClass UserSearcher
PublicFunction UserIsMemberOfGroupA(ByVal group AsString, ByVal user As DirectoryEntry) AsBoolean
Dim isMember AsBoolean = False
Try
' Get the SID for Group A
Dim objectSid AsByte() = GetGroupSID(group)
IfNot IsNothing(objectSid) Then
'
' now retrieve the tokenGroups property on the user "John Doe"
'
Dim props() AsString = {"tokenGroups"}
user.RefreshCache(props)
'
' cycle through the tokenGroups and see if one matches the SID of group A
'
ForEach entry AsByte() In user.Properties("tokenGroups")
If CompareByteArrays(entry, objectSid) Then
isMember = True
ExitFor
EndIf
Next
EndIf
Catch ex As Exception
ThrowNew ApplicationException("An error occurred while checking group membership.")
EndTry
Return isMember
EndFunction
PrivateFunction GetGroupSID(ByVal group AsString) AsByte()
' Bind directly to the SMS group
Dim entry As DirectoryEntry
Try
entry = New DirectoryEntry(group)
IfNot IsNothing(entry) Then
'
' retrieve the objectSID for the group
'
Dim sid AsByte() = CType(entry.Properties("objectSID").Value, Byte())
Return sid
Else
ReturnNothing
EndIf
Catch ex As Exception
ThrowNew ApplicationException("An error occurred while binding to the group in Active Directory.")
Finally
IfNot IsNothing(entry) Then
entry.Dispose()
entry.Close()
EndIf
EndTry
EndFunction
PrivateFunction CompareByteArrays(ByVal data1 AsByte(), ByVal data2 AsByte()) AsBoolean
Try
' If both are null, they're equal
If IsNothing(data1) And IsNothing(data2) Then
ReturnTrue
EndIf
' If either but not both are null, they're not equal
If IsNothing(data1) OrElse IsNothing(data2) Then
ReturnFalse
EndIf
If data1.Length <> data2.Length Then
ReturnFalse
EndIf
For index AsInteger = 0 To data1.Length - 1
If data1(index) <> data2(index) Then
ReturnFalse
EndIf
Next
ReturnTrue
Catch ex As Exception
ThrowNew ApplicationException("An error occurred while comparing byte arrays.")
EndTry
EndFunction
EndClass
 
Back
Top