Tangus,
Active Directory Class
I created this class for working with my company's active directory.
You'll want to look over the enumerated lists and make any necessary changes
to the names since network admins usually use their own naming conventions.
Imports System.Data
Imports System.DirectoryServices
Imports System.Security.Principal
Imports System.Threading
Public Class Objects
Private Filter As New System.Text.StringBuilder
Public Enum LoadProperties
accountExpires
c
cn
company
givenName
DC
department
description
directReports
dNSHostName
driverName
facsimileTelephoneNumber
groupType
homeDirectory
homeDrive
initials
info
ipPhone
keywords
l
location
logonHours
logonWorkstation
mail
manager
member
memberOf
mobile
operatingSystem
operatingSystemVersion
operatingSystemServicePack
otherTelephone
pager
pagerOther
physicalDeliveryOfficeName
postalCode
postOfficeBox
primaryGroupID
printColor
printDuplexSupported
printMaxResolutionSupported
printRate
printStaplingSupported
profilePath
pwdLastSet
objectClass
otherMobile
otherIpPhone
otherFacsimileTelephoneNumber
sAMAccountname
scriptPath
sn
st
street
streetAddress
telephoneNumber
title
uNCName
url
userAccountControl
userPrincipalName
uSNChanged
uSNCreated
whenCreated
whenChanged
wwwHomePage
End Enum
Public Enum SortProperties
accountExpires
cn
company
givenName
DC
department
dNSHostName
driverName
facsimileTelephoneNumber
groupType
homeDirectory
homeDrive
initials
info
ipPhone
keywords
l
location
logonHours
logonWorkstation
mail
mobile
operatingSystem
operatingSystemVersion
operatingSystemServicePack
otherTelephone
pager
physicalDeliveryOfficeName
postalCode
postOfficeBox
primaryGroupID
printColor
printDuplexSupported
printMaxResolutionSupported
printRate
printStaplingSupported
profilePath
pwdLastSet
otherMobile
otherIpPhone
otherFacsimileTelephoneNumber
sAMAccountname
scriptPath
sn
st
street
streetAddress
telephoneNumber
title
uNCName
url
userAccountControl
userPrincipalName
uSNChanged
uSNCreated
whenCreated
whenChanged
wwwHomePage
End Enum
Public Sub AddFilter(ByVal FilterProperty As LoadProperties, ByVal
FilterValue As String)
Try
Filter.Append("(" & FilterProperty.ToString & "=" & FilterValue & ")")
Catch e As Exception
Throw e
End Try
End Sub
Public Sub AddFilter(ByVal FilterProperties() As LoadProperties, ByVal
FilterValues() As String)
Try
If FilterProperties.GetUpperBound(0) <> FilterValues.GetUpperBound(0) Then
Throw New Exception("The number of filter properties in the
""FilterProperties"" array must mach the number of filter values in the
""FilterValues"" array.")
Exit Sub
End If
Dim mintCount, mintLoop As Int32
mintCount = FilterProperties.GetUpperBound(0)
Dim FilterProperty As LoadProperties
For mintLoop = 0 To mintCount
FilterProperty = FilterProperties(mintLoop)
Filter.Append("(" & FilterProperty.ToString & "=" &
FilterValues(mintLoop).ToString & ")")
Next
Catch e As Exception
Throw e
End Try
End Sub
Public Sub ClearFilter()
Try
Filter.Remove(0, Filter.Length)
Catch e As Exception
Throw e
End Try
End Sub
Public Function GetObjectsTable(ByVal PropertiesToLoad() As LoadProperties,
ByVal SortOn As SortProperties) As DataTable
Try
'---Search the Active Directory
'---Loop through the Properties the developer wants to load and prepare an
array of strings
Dim mintCount, mintLoop As Int32
Dim PropertyToLoad As LoadProperties
'---Create the array with the proper dimension
mintCount = PropertiesToLoad.GetUpperBound(0)
Dim marrPropertiesToLoad As Array =
marrPropertiesToLoad.CreateInstance(GetType(System.String), mintCount + 1)
'---Fill the array
For mintLoop = 0 To mintCount
PropertyToLoad = PropertiesToLoad(mintLoop)
marrPropertiesToLoad.SetValue(PropertyToLoad.ToString, mintLoop)
Next
'---Prepare the sort field
Dim adSort As New System.DirectoryServices.SortOption
adSort.PropertyName = SortOn.ToString
'---Create the search object
Dim adSearcher As DirectorySearcher = GetSearchObject()
adSearcher.PropertiesToLoad.AddRange(CType(marrPropertiesToLoad,
System.String()))
'---Set the filter (if there is one)
If Filter.Length > 0 Then
adSearcher.Filter = "(&" & Filter.ToString & ")"
End If
'---Set the sort object
adSearcher.Sort = adSort
'---Create a collection of results and fill it
Dim Results As SearchResultCollection
Results = adSearcher.FindAll()
'---Create the datatable and add each column.
Dim mstrColumnName As String
Dim mtblObjects As New DataTable
For Each mstrColumnName In marrPropertiesToLoad
mtblObjects.Columns.Add(mstrColumnName, GetType(System.String))
Next
'---Populate table
Dim Result As SearchResult
Dim mdrResultsTableRow As DataRow
Dim mintPropertiesCount, mintPropertiesLoop As Int32
Dim msbResults As New System.Text.StringBuilder
'---Loop through each record found
For Each Result In Results
'---Create a datarow to hold the record's info.
mdrResultsTableRow = mtblObjects.NewRow
'---Loop through each record's properties adding each to a column in the
datarow
For Each mstrColumnName In marrPropertiesToLoad
'---Reset the string builder
msbResults.Remove(0, msbResults.Length)
If Result.Properties.Contains(mstrColumnName) Then
'---Loop through the results found for this column (add each result to the
column with a pipe for concatenation)
mintCount = Result.Properties(mstrColumnName).Count - 1
For mintLoop = 0 To mintCount
msbResults.Append(Result.Properties(mstrColumnName)(mintLoop).ToString)
If mintCount > mintLoop Then
msbResults.Append("|")
End If
Next
mdrResultsTableRow(mstrColumnName) = msbResults.ToString
Else
mdrResultsTableRow(mstrColumnName) = ""
End If
Next
mtblObjects.Rows.Add(mdrResultsTableRow)
Next
Return mtblObjects
Catch e As Exception
Throw e
End Try
End Function
Public Function GetSingleObjectTable(ByVal PropertiesToLoad() As
LoadProperties) As DataTable
Try
'---Search the Active Directory
'---Loop through the Properties the developer wants to load and prepare an
array of strings
Dim mintCount, mintLoop As Int32
Dim PropertyToLoad As LoadProperties
'---Create the array with the proper dimension
mintCount = PropertiesToLoad.GetUpperBound(0)
Dim marrPropertiesToLoad As Array =
marrPropertiesToLoad.CreateInstance(GetType(System.String), mintCount + 1)
'---Fill the array
For mintLoop = 0 To mintCount
PropertyToLoad = PropertiesToLoad(mintLoop)
marrPropertiesToLoad.SetValue(PropertyToLoad.ToString, mintLoop)
Next
'---Create the search object
Dim adSearcher As DirectorySearcher = GetSearchObject()
adSearcher.PropertiesToLoad.AddRange(CType(marrPropertiesToLoad,
System.String()))
'---Set the filter (if there is one)
If Filter.Length > 0 Then
adSearcher.Filter = "(&" & Filter.ToString & ")"
End If
'---Create a collection of results and fill it
Dim Result As SearchResult
Result = adSearcher.FindOne()
'---Create the datatable and add each column.
Dim mstrColumnName As String
Dim mtblObjects As New DataTable
For Each mstrColumnName In marrPropertiesToLoad
mtblObjects.Columns.Add(mstrColumnName, GetType(System.String))
Next
'---Populate table
Dim mdrResultsTableRow As DataRow
Dim mintPropertiesCount, mintPropertiesLoop As Int32
Dim msbResults As New System.Text.StringBuilder
If Not IsNothing(Result) Then
'---Create a datarow to hold the record's info.
mdrResultsTableRow = mtblObjects.NewRow
'---Loop through each record's properties adding each to a column in the
datarow
For Each mstrColumnName In marrPropertiesToLoad
'---Reset the string builder
msbResults.Remove(0, msbResults.Length)
If Result.Properties.Contains(mstrColumnName) Then
'---Loop through the results found for this column (add each result to the
column with a pipe for concatenation)
mintCount = Result.Properties(mstrColumnName).Count - 1
For mintLoop = 0 To mintCount
msbResults.Append(Result.Properties(mstrColumnName)(mintLoop).ToString)
If mintCount > mintLoop Then
msbResults.Append("|")
End If
Next
mdrResultsTableRow(mstrColumnName) = msbResults.ToString
Else
mdrResultsTableRow(mstrColumnName) = ""
End If
Next
mtblObjects.Rows.Add(mdrResultsTableRow)
End If
Return mtblObjects
Catch e As Exception
Throw e
End Try
End Function
Public Function GetObjectPropertyTables(ByVal PropertiesToLoad() As
LoadProperties, ByVal KeyColumn As LoadProperties, ByVal SortOn As
SortProperties) As DataSet
Try
'---Search the Active Directory
'---Loop through the Properties the developer wants to load and prepare an
array of strings
Dim mintCount, mintLoop As Int32
Dim PropertyToLoad As LoadProperties
'---Create the array with the proper dimension
mintCount = PropertiesToLoad.GetUpperBound(0)
Dim marrPropertiesToLoad As Array =
marrPropertiesToLoad.CreateInstance(GetType(System.String), mintCount + 1)
'---Fill the array
For mintLoop = 0 To mintCount
PropertyToLoad = PropertiesToLoad(mintLoop)
marrPropertiesToLoad.SetValue(PropertyToLoad.ToString, mintLoop)
Next
'---Prepare the sort field
Dim adSort As New System.DirectoryServices.SortOption
adSort.PropertyName = SortOn.ToString
'---Create the search object
Dim adSearcher As DirectorySearcher = GetSearchObject()
adSearcher.PropertiesToLoad.AddRange(CType(marrPropertiesToLoad,
System.String()))
'---Set the filter (if there is one)
If Filter.Length > 0 Then
adSearcher.Filter = "(&" & Filter.ToString & ")"
End If
'---Set the sort object
adSearcher.Sort = adSort
'---Create a collection of results and fill it
Dim Results As SearchResultCollection
Results = adSearcher.FindAll()
'---Create a datatable for each property and add each column
Dim mstrColumnName As String
Dim mdsObjects As New DataSet("Objects")
For Each mstrColumnName In marrPropertiesToLoad
Dim mtblProperties As New DataTable("tbl" & mstrColumnName)
If mstrColumnName = KeyColumn.ToString Then
mtblProperties.Columns.Add(KeyColumn.ToString, GetType(System.String))
Else
mtblProperties.Columns.Add(KeyColumn.ToString, GetType(System.String))
mtblProperties.Columns.Add(mstrColumnName, GetType(System.String))
End If
mdsObjects.Tables.Add(mtblProperties)
Next
'---Populate tables
Dim Result As SearchResult
Dim mdrResultsTableRow As DataRow
'---Loop through each record found
For Each Result In Results
'---Loop through each record's properties adding each to the appropriate
table
For Each mstrColumnName In marrPropertiesToLoad
Call AddRow(mdsObjects, Result, mstrColumnName, KeyColumn.ToString)
Next
Next
Return mdsObjects
Catch e As Exception
Throw e
End Try
End Function
Public Function GetSingleObjectPropertyTables(ByVal PropertiesToLoad() As
LoadProperties, ByVal KeyColumn As LoadProperties) As DataSet
Try
'---Search the Active Directory
'---Loop through the Properties the developer wants to load and prepare an
array of strings
Dim mintCount, mintLoop As Int32
Dim PropertyToLoad As LoadProperties
'---Create the array with the proper dimension
mintCount = PropertiesToLoad.GetUpperBound(0)
Dim marrPropertiesToLoad As Array =
marrPropertiesToLoad.CreateInstance(GetType(System.String), mintCount + 1)
'---Fill the array
For mintLoop = 0 To mintCount
PropertyToLoad = PropertiesToLoad(mintLoop)
marrPropertiesToLoad.SetValue(PropertyToLoad.ToString, mintLoop)
Next
'---Create the search object
Dim adSearcher As DirectorySearcher = GetSearchObject()
adSearcher.PropertiesToLoad.AddRange(CType(marrPropertiesToLoad,
System.String()))
'---Set the filter (if there is one)
If Filter.Length > 0 Then
adSearcher.Filter = "(&" & Filter.ToString & ")"
End If
'---Create a collection of results and fill it
Dim Result As SearchResult
Result = adSearcher.FindOne()
'---Create a datatable for each property and add each column
Dim mstrColumnName As String
Dim mdsObjects As New DataSet("Objects")
For Each mstrColumnName In marrPropertiesToLoad
Dim mtblProperties As New DataTable("tbl" & mstrColumnName)
If mstrColumnName = KeyColumn.ToString Then
mtblProperties.Columns.Add(KeyColumn.ToString, GetType(System.String))
Else
mtblProperties.Columns.Add(KeyColumn.ToString, GetType(System.String))
mtblProperties.Columns.Add(mstrColumnName, GetType(System.String))
End If
mdsObjects.Tables.Add(mtblProperties)
Next
If Not IsNothing(Result) Then
'---Populate table
'---Loop through each record's properties adding each to the appropriate
table
For Each mstrColumnName In marrPropertiesToLoad
Call AddRow(mdsObjects, Result, mstrColumnName, KeyColumn.ToString)
Next
End If
Return mdsObjects
Catch e As Exception
Throw e
End Try
End Function
Private Function GetSearchObject() As DirectorySearcher
Try
'---Create the connection to the Active Directory
Dim adDirectoryEntry As New DirectoryServices.DirectoryEntry
adDirectoryEntry.AuthenticationType =
DirectoryServices.AuthenticationTypes.ReadonlyServer
adDirectoryEntry.Path = "GC://mscs1n1.Krause.com"
adDirectoryEntry.Username = "FW\AdReadMaster"
adDirectoryEntry.Password = "z#2?9c!0"
'---Create the search object
Return New DirectoryServices.DirectorySearcher(adDirectoryEntry)
Catch e As Exception
Throw e
End Try
End Function
Private Sub AddRow(ByRef ObjectsDataSet As DataSet, ByVal Result As
SearchResult, ByVal ColumnName As String, ByVal KeyColumn As String)
Try
Dim mdrResultsTableRow As DataRow
Dim mintPropertyCount, mintPropertyLoop As Int32
If Result.Properties.Contains(ColumnName) Then
If ColumnName = KeyColumn.ToString Then
'---Create a new row in the table
mdrResultsTableRow = ObjectsDataSet.Tables("tbl" & ColumnName).NewRow
mdrResultsTableRow(ColumnName) =
Result.Properties(KeyColumn.ToString)(0).ToString
ObjectsDataSet.Tables("tbl" & ColumnName).Rows.Add(mdrResultsTableRow)
Else
mintPropertyCount = Result.Properties(ColumnName).Count - 1
For mintPropertyLoop = 0 To mintPropertyCount
'---Create a new row in the table
mdrResultsTableRow = ObjectsDataSet.Tables("tbl" & ColumnName).NewRow
If Result.Properties.Contains(KeyColumn.ToString) Then
mdrResultsTableRow(KeyColumn.ToString) =
Result.Properties(KeyColumn.ToString)(0).ToString
Else
mdrResultsTableRow(KeyColumn.ToString) = ""
End If
mdrResultsTableRow(ColumnName) =
Result.Properties(ColumnName)(mintPropertyLoop).ToString
ObjectsDataSet.Tables("tbl" & ColumnName).Rows.Add(mdrResultsTableRow)
Next
End If
Else
'---Create a new row in the table
mdrResultsTableRow = ObjectsDataSet.Tables("tbl" & ColumnName).NewRow
mdrResultsTableRow(ColumnName) = ""
ObjectsDataSet.Tables("tbl" & ColumnName).Rows.Add(mdrResultsTableRow)
End If
Catch e As Exception
Throw e
End Try
End Sub
End Class
Public Class User
Public Id As String
Public FirstName As String
Public MiddleInitial As String
Public LastName As String
Public Title As String
Public Department As String
Public Location As String
Public Phone As String
Public IsManager As Boolean
Public ReportsTo As String
Public MemberOf As System.Collections.ArrayList
Public Sub New()
Try
MemberOf = New System.Collections.ArrayList
Catch e As Exception
Throw e
End Try
End Sub
Public Sub New(ByVal User As System.Security.Principal.WindowsIdentity)
Try
Dim Objects As New FW.ActiveDirectory.Objects
Dim mstrAMAccountName As String = User.Name.Substring(User.Name.IndexOf("\")
+ 1)
Dim Properties() As FW.ActiveDirectory.Objects.LoadProperties =
{FW.ActiveDirectory.Objects.LoadProperties.mail,
Objects.LoadProperties.givenName, Objects.LoadProperties.initials,
Objects.LoadProperties.sn, Objects.LoadProperties.title,
Objects.LoadProperties.department, Objects.LoadProperties.l,
Objects.LoadProperties.telephoneNumber, Objects.LoadProperties.manager,
Objects.LoadProperties.memberOf}
Objects.AddFilter(FW.ActiveDirectory.Objects.LoadProperties.sAMAccountname,
mstrAMAccountName)
Dim mdsObjectTables As DataSet =
Objects.GetSingleObjectPropertyTables(Properties,
Objects.LoadProperties.mail)
Call FillProperties(mdsObjectTables, Objects)
Catch e As Exception
Throw e
End Try
End Sub
Public Sub New(ByVal EmailAddress As String)
Try
Dim Objects As New FW.ActiveDirectory.Objects
Dim Properties() As FW.ActiveDirectory.Objects.LoadProperties =
{FW.ActiveDirectory.Objects.LoadProperties.mail,
Objects.LoadProperties.givenName, Objects.LoadProperties.initials,
Objects.LoadProperties.sn, Objects.LoadProperties.title,
Objects.LoadProperties.department, Objects.LoadProperties.l,
Objects.LoadProperties.telephoneNumber, Objects.LoadProperties.manager,
Objects.LoadProperties.memberOf}
Objects.AddFilter(FW.ActiveDirectory.Objects.LoadProperties.mail,
EmailAddress)
Dim mdsObjectTables As DataSet =
Objects.GetSingleObjectPropertyTables(Properties,
Objects.LoadProperties.mail)
Call FillProperties(mdsObjectTables, Objects)
Catch e As Exception
Throw e
End Try
End Sub
Public Sub FillProperties(ByVal mdsObjectTables As DataSet, ByRef objects As
Objects)
Try
Id = mdsObjectTables.Tables("tblmail").Rows(0)(0).ToString
FirstName = mdsObjectTables.Tables("tblgivenName").Rows(0)(1).ToString
MiddleInitial = mdsObjectTables.Tables("tblinitials").Rows(0)(1).ToString
LastName = mdsObjectTables.Tables("tblsn").Rows(0)(1).ToString
Title = mdsObjectTables.Tables("tbltitle").Rows(0)(1).ToString
Department = mdsObjectTables.Tables("tbldepartment").Rows(0)(1).ToString
Location = mdsObjectTables.Tables("tbll").Rows(0)(1).ToString
Phone = mdsObjectTables.Tables("tbltelephoneNumber").Rows(0)(1).ToString
Dim mstrManagerCn As String =
mdsObjectTables.Tables("tblmanager").Rows(0)(1).ToString
If mstrManagerCn = "" Then
IsManager = True
Else
IsManager = False
mstrManagerCn = mstrManagerCn.Replace("\,", "|23154|")
Dim marrManagerCn() As String = mstrManagerCn.Split(",".ToCharArray)
Dim mstrItem As String
For Each mstrItem In marrManagerCn
If mstrItem.IndexOf("CN=") > -1 Then
mstrManagerCn = mstrItem.Replace("CN=", "").Replace("|23154|", "\,")
Exit For
End If
Next
Dim ManagerProperties() As FW.ActiveDirectory.Objects.LoadProperties =
{objects.LoadProperties.mail}
objects.ClearFilter()
objects.AddFilter(objects.LoadProperties.cn, mstrManagerCn.Replace("\", ""))
Dim mtblManager As DataTable =
objects.GetSingleObjectTable(ManagerProperties)
If mtblManager.Rows.Count > 0 Then
ReportsTo = mtblManager.Rows(0)(0).ToString
Else
ReportsTo = ""
End If
End If
MemberOf = New System.Collections.ArrayList
Dim mintCount, mintLoop As Int32
mintCount = mdsObjectTables.Tables("tblmemberOf").Rows.Count - 1
For mintLoop = 0 To mintCount
MemberOf.Add(mdsObjectTables.Tables("tblmemberOf").Rows(mintLoop)(1).ToString)
Next
Catch ex As Exception
Throw ex
End Try
End Sub
Public Function GetFullName() As String
Try
Dim msbFullName As New System.Text.StringBuilder
msbFullName.Append(Me.FirstName & " ")
If Not Me.MiddleInitial = "" Then
msbFullName.Append(Me.MiddleInitial & ". ")
End If
msbFullName.Append(Me.LastName)
Return msbFullName.ToString
Catch e As Exception
Throw e
End Try
End Function
Public Function IsMemberOf(ByVal groupName As String) As Boolean
Try
Dim GroupCount, GroupLoop, RowCount, RowLoop As Int32
Dim GroupCN, NewGroup As String
Dim GroupDataTable As DataTable
'---Make a copy of the memberof array
Dim MemberOfCopy As New ArrayList(Me.MemberOf)
'---Loop through the groups the current Object is a member of
Do While MemberOfCopy.Count > 0
'---Get the common name of the current group
GroupCN = MemberOfCopy.Item(0).ToString
If GroupCN.IndexOf(groupName) > -1 Then
Return True
Else
'---Get the groups that this group is a member of
GroupDataTable = GetGroups(GroupCN)
If Not GroupDataTable Is Nothing Then
'---Add these groups to the array
RowCount = GroupDataTable.Rows.Count - 1
For RowLoop = 0 To RowCount
If GroupDataTable.Rows(RowLoop)("memberOf").ToString.IndexOf("CN=") > -1
Then
Dim NewGroupsArray() As String =
GroupDataTable.Rows(RowLoop)("memberOf").ToString.Split("|".ToCharArray)
For Each NewGroup In NewGroupsArray
MemberOfCopy.Add(NewGroup)
Next
End If
Next
End If
MemberOfCopy.RemoveAt(0)
End If
Loop
Return False
Catch ex As Exception
Throw (ex)
End Try
End Function
Public Function GetUsersTableByGroup(ByVal PropertiesToLoad() As
Objects.LoadProperties, ByVal sortOn As Objects.SortProperties, ByVal
groupName As String) As DataView
Try
'---Find out if the original properties array includes member and
userPrincipalName
Dim IncludesMail As Boolean = False
Dim IncludesMember As Boolean = False
Dim IncludesUserPrincipalName As Boolean = False
If Not PropertiesToLoad.IndexOf(PropertiesToLoad,
FW.ActiveDirectory.Objects.LoadProperties.cn) > -1 Then
ReDim Preserve PropertiesToLoad(PropertiesToLoad.GetUpperBound(0) + 1)
PropertiesToLoad(PropertiesToLoad.GetUpperBound(0)) =
FW.ActiveDirectory.Objects.LoadProperties.cn
End If
If PropertiesToLoad.IndexOf(PropertiesToLoad,
FW.ActiveDirectory.Objects.LoadProperties.mail) > -1 Then
IncludesMail = True
Else
ReDim Preserve PropertiesToLoad(PropertiesToLoad.GetUpperBound(0) + 1)
PropertiesToLoad(PropertiesToLoad.GetUpperBound(0)) =
FW.ActiveDirectory.Objects.LoadProperties.mail
End If
If PropertiesToLoad.IndexOf(PropertiesToLoad,
FW.ActiveDirectory.Objects.LoadProperties.member) > -1 Then
IncludesMember = True
Else
ReDim Preserve PropertiesToLoad(PropertiesToLoad.GetUpperBound(0) + 1)
PropertiesToLoad(PropertiesToLoad.GetUpperBound(0)) =
FW.ActiveDirectory.Objects.LoadProperties.member
End If
If PropertiesToLoad.IndexOf(PropertiesToLoad,
FW.ActiveDirectory.Objects.LoadProperties.userPrincipalName) > -1 Then
IncludesUserPrincipalName = True
Else
ReDim Preserve PropertiesToLoad(PropertiesToLoad.GetUpperBound(0) + 1)
PropertiesToLoad(PropertiesToLoad.GetUpperBound(0)) =
FW.ActiveDirectory.Objects.LoadProperties.userPrincipalName
End If
'---Get the users and groups contained in the original group
Dim Objects As New Objects
Objects.AddFilter(Objects.LoadProperties.memberOf, groupName)
Dim DataTable As DataTable = Objects.GetObjectsTable(PropertiesToLoad,
sortOn)
'---Make a copy of the datatable to hold users found
Dim UsersDataTable As DataTable = DataTable.Clone()
Dim Item, CommonNameFound As String
Dim SearchDataTable As DataTable
Dim ItemArrayCount, ItemArrayLoop, ObjectsCount, ObjectsLoop As Int32
Do While DataTable.Rows.Count > 0
'---Check if the first row is a user or another group (users have a
LoadProperties.userPrincipalName)
If DataTable.Rows(0)("UserPrincipalName").ToString > "" Then
'---If a user add to the UsersDataTable
'---Check if user already exists
If Not UserAlreadyExists(DataTable.Rows(0)("mail").ToString, UsersDataTable)
Then
UsersDataTable.ImportRow(DataTable.Rows(0))
End If
Else
'---If a group check if it contains other users and / or groups
'---Split the group info returned into separate items
Dim GroupItemArray() As String =
DataTable.Rows(0)("member").ToString.Split("|".ToCharArray)
'---Loop through the items searching for the common name element
For Each Item In GroupItemArray
'---Get the common name of the item
Item = Item.Replace("\,", "|23154|")
Dim ItemArray() As String = Item.Split(",".ToCharArray)
ItemArrayCount = ItemArray.GetUpperBound(0)
For ItemArrayLoop = 0 To ItemArrayCount
If ItemArray(ItemArrayLoop).IndexOf("CN=") > -1 Then
CommonNameFound = ItemArray(ItemArrayLoop).ToString.Replace("CN=", "")
CommonNameFound = CommonNameFound.Replace("CN=", "").Replace("|23154|", ",")
Exit For
End If
Next
'---Set the filter
Objects.ClearFilter()
Objects.AddFilter(Objects.LoadProperties.cn, CommonNameFound)
'---Get the new table
SearchDataTable = Objects.GetObjectsTable(PropertiesToLoad, sortOn)
'---If the row has a user principal name then it's a user
If SearchDataTable.Rows(0)("UserPrincipalName").ToString > "" Then
'---If this user doesn't already exist then add them
If Not UserAlreadyExists(SearchDataTable.Rows(0)("mail").ToString,
UsersDataTable) Then
UsersDataTable.ImportRow(SearchDataTable.Rows(0))
End If
Else
'---If a group add to the original datatable
DataTable.ImportRow(SearchDataTable.Rows(0))
End If
Next
End If
'---Delete the row
DataTable.Rows(0).Delete()
Loop
'---If the original properties to load didn't include member and / or
userPrincipalName
' remove them
If Not IncludesMember Then
UsersDataTable.Columns.Remove(UsersDataTable.Columns("member"))
End If
If Not IncludesUserPrincipalName Then
UsersDataTable.Columns.Remove(UsersDataTable.Columns("userPrincipalName"))
End If
Dim DataView As New DataView(UsersDataTable, Nothing, sortOn.ToString,
DataViewRowState.CurrentRows)
Return DataView
Catch ex As Exception
Throw (ex)
End Try
End Function
Private Function UserAlreadyExists(ByVal emailAddress As String, ByVal
dataTableToCheckIn As DataTable) As Boolean
Try
Dim DataRows() As DataRow = dataTableToCheckIn.Select("mail='" &
emailAddress & "'")
If DataRows.GetUpperBound(0) = -1 Then
Return False
Else
Return True
End If
Catch ex As Exception
Throw ex
End Try
End Function
Private Function GetGroups(ByVal memberOfItem As String) As DataTable
Try
Dim memberOfItemArray() As String = memberOfItem.Split(",".ToCharArray)
Dim Item As String
For Each Item In memberOfItemArray
If Item.IndexOf("CN=") > -1 Then
memberOfItem = Item.Replace("CN=", "")
Dim Objects As New FW.ActiveDirectory.Objects
Dim PropsToLoad() As FW.ActiveDirectory.Objects.LoadProperties =
{FW.ActiveDirectory.Objects.LoadProperties.memberOf}
Objects.AddFilter(FW.ActiveDirectory.Objects.LoadProperties.cn,
memberOfItem)
Dim DataTable As DataTable = Objects.GetSingleObjectTable(PropsToLoad)
Return DataTable
End If
Next
Return Nothing
Catch ex As Exception
Throw ex
End Try
End Function
End Class
--
Sincerely,
S. Justin Gengo, MCP
Web Developer / Programmer
www.aboutfortunate.com
"Out of chaos comes order."
Nietzsche