Get All Group Users
Queries the LDAP server to get all user members of a specific group, even if there are more than 1000 results. The max number of entry returned must be increased on the LDAP server otherwise always 1000 entries are returned.
Uses LDAP paging with LdapConnection.
VB
Public Function ldGetAllGroupUsers(groupDN As String,
serverPort As String,
domain As String,
username As String,
password As String) As List(Of SearchResultEntry)
Dim userList As New List(Of SearchResultEntry)()
' Validate inputs
If String.IsNullOrEmpty(groupDN) OrElse String.IsNullOrEmpty(serverPort) OrElse String.IsNullOrEmpty(domain) OrElse String.IsNullOrEmpty(username) OrElse String.IsNullOrEmpty(password) Then
Throw New ArgumentException("All parameters must be provided and not empty.")
End If
' Prepare LDAP connection
Dim ldapConnection As New LdapConnection(New LdapDirectoryIdentifier(serverPort))
ldapConnection.AuthType = AuthType.Basic
ldapConnection.SessionOptions.ProtocolVersion = 3
Dim credential As New NetworkCredential(username, password)
' Bind to LDAP server
Try
ldapConnection.Bind(credential)
Catch ex As Exception
Throw New Exception("LDAP bind error: " & ex.Message)
End Try
' LDAP filter: direct members of the group only
Dim filter As String = "(&(objectClass=user)(memberOf=" & groupDN & "))"
Dim attributes() As String = {} ' Load all attributes
' Prepare the page request control
Dim pageSize As Integer = 1000
Dim pageRequestControl As New PageResultRequestControl(pageSize)
' Search request
Dim searchRequest As New SearchRequest(domain, filter, Protocols.SearchScope.Subtree, attributes)
searchRequest.Controls.Add(pageRequestControl)
Dim morePages As Boolean = True
While morePages
Dim searchResponse As SearchResponse
Try
searchResponse = CType(ldapConnection.SendRequest(searchRequest), SearchResponse)
Catch ex As Exception
Throw New Exception("LDAP search error: " & ex.Message)
End Try
' Process search results
For Each entry As SearchResultEntry In searchResponse.Entries
If entry.Attributes.Contains("objectClass") AndAlso entry.Attributes("objectClass").GetValues(GetType(String)).Contains("user") Then
userList.Add(entry)
End If
Next
' Check for the paging cookie to see if there are more pages
morePages = False
For Each control As DirectoryControl In searchResponse.Controls
If TypeOf control Is PageResultResponseControl Then
Dim pageResponse As PageResultResponseControl = CType(control, PageResultResponseControl)
If pageResponse.Cookie.Length <> 0 Then
' More data available - continue paging
pageRequestControl.Cookie = pageResponse.Cookie
morePages = True
End If
End If
Next
End While
' Done - return all collected user entries
Return userList
End Function