473,385 Members | 1,907 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Problem retrieving Active Directory users

Hello all, I'm really struggling with getting some Active Directory code to
work in ASP.NET. Can you please provide assistance? I am executing the
following code:

Dim enTry As DirectoryEntry = New DirectoryEntry("LDAP://domain")
Dim mySearcher As New DirectorySearcher(enTry)
Dim resEnt As SearchResult

mySearcher.Filter = ("(objectClass=*)")
mySearcher.SearchScope = SearchScope.Subtree
Response.Write("Active Directory Information<br>")
Response.Write("================================== =========<br><br>")

Try
For Each resEnt In mySearcher.FindAll()
Response.Write(resEnt.GetDirectoryEntry().Name.ToS tring() &
"<br>")
Response.Write(resEnt.GetDirectoryEntry().Path.ToS tring() &
"<br>")
Response.Write(resEnt.GetDirectoryEntry().NativeGu id.ToString
() & "<br>")
Response.Write
("===========================================<br>< br>")
Next
Catch exc As Exception
Response.Write(exc.Message)
End Try
Response.End()

And it will display some information. However, when I change my filter to:
mySearcher.Filter = ("(objectClass=user)")

....nothing is being returned. In fact, I can't filter by anything and get
results back. Please advise.

Thanks for any assistance you can provide!
Nov 19 '05 #1
1 3865
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.ToStr ing, 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(marrPro pertiesToLoad,
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.ToStr ing, mintLoop)

Next

'---Create the search object

Dim adSearcher As DirectorySearcher = GetSearchObject()

adSearcher.PropertiesToLoad.AddRange(CType(marrPro pertiesToLoad,
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.ToStr ing, 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(marrPro pertiesToLoad,
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.ToStr ing, mintLoop)

Next

'---Create the search object

Dim adSearcher As DirectorySearcher = GetSearchObject()

adSearcher.PropertiesToLoad.AddRange(CType(marrPro pertiesToLoad,
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.ReadonlyServ er

adDirectoryEntry.Path = "GC://mscs1n1.Krause.com"

adDirectoryEntry.Username = "FW\AdReadMaster"

adDirectoryEntry.Password = "z#2?9c!0"

'---Create the search object

Return New DirectoryServices.DirectorySearcher(adDirectoryEnt ry)

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).To String

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.LoadP roperties.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.LoadP roperties.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).ToStr ing

FirstName = mdsObjectTables.Tables("tblgivenName").Rows(0)(1). ToString

MiddleInitial = mdsObjectTables.Tables("tblinitials").Rows(0)(1).T oString

LastName = mdsObjectTables.Tables("tblsn").Rows(0)(1).ToStrin g

Title = mdsObjectTables.Tables("tbltitle").Rows(0)(1).ToSt ring

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).To String

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.userPrin cipalName) > -1 Then

IncludesUserPrincipalName = True

Else

ReDim Preserve PropertiesToLoad(PropertiesToLoad.GetUpperBound(0) + 1)

PropertiesToLoad(PropertiesToLoad.GetUpperBound(0) ) =
FW.ActiveDirectory.Objects.LoadProperties.userPrin cipalName

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").ToStri ng, 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("|".ToC harArray)

'---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").ToStr ing > "" 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.Colum ns("member"))

End If

If Not IncludesUserPrincipalName Then

UsersDataTable.Columns.Remove(UsersDataTable.Colum ns("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.memberO f}

Objects.AddFilter(FW.ActiveDirectory.Objects.LoadP roperties.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
Nov 19 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: CJM | last post by:
I'm trying to retrieve the users email address via ADSI in ASP. So far, I have the following code: Set oUser = GetObject("WinNT://domain/" & Request.Form("UID") & ",user") Response.Write...
7
by: jsale | last post by:
I'm currently using ASP.NET with VS2003 and SQL Server 2003. The ASP.NET app i have made is running on IIS v6 and consists of a number of pages that allow the user to read information from the...
3
by: Luis Esteban Valencia | last post by:
Hello gusys, Is it possible to make my asp.net application add users to the AD , I also want to be able to delete users, modify their information, everything through a website. Thanks for the...
4
by: Patrick.O.Ige | last post by:
If i want to generate a menu structure depending on who is logged in in an intranet system(using windows authentication) is it better to use the GROUPS in Active Directory or to move the Active...
4
by: pjdouillard | last post by:
Hello all, Here is the context of my problem: We have an ASP.NET 1.1 application that has its own application pool setup and that runs under the identity of a NT Domain service account (this...
1
by: eloymaster | last post by:
Hi! I do have a problem while retrieving the AccountName of Members of a Active Directory-Group. I get the members with the DirectorySearcher (of the System.DirectoryServices namespace). It...
0
by: jakobsgaard | last post by:
It is possible to Map a certificate to a Active Directory User Account from DotNet? Please provide an example. Best regards, Ejnar Jakobsgaard...
0
by: Chung Leong | last post by:
In this brief tutorial I'll describe how you retrieve information from an Active Directory through the OLE-DB extension. While it is possible to use the LDAP extension to achieve the same goal, as...
0
by: fabiomoggi | last post by:
Hello Guys, I am developing a web application to manage Active Directory resources, and one of my tasks is to map Organizational Units hierarchy into a SQL Server database. Let's suppose that I...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.