Groups | Blog | Home
all groups > asp.net > september 2005 >

asp.net : Problem retrieving Active Directory users


tangus via DotNetMonster.com
9/30/2005 9:14:45 PM
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.ToString() &
"<br>")
Response.Write(resEnt.GetDirectoryEntry().Path.ToString() &
"<br>")
Response.Write(resEnt.GetDirectoryEntry().NativeGuid.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.

S. Justin Gengo
9/30/2005 11:59:38 PM
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

AddThis Social Bookmark Button