Solved

how to read users information from active directory in asp.net application

Posted on 2009-05-17
18
812 Views
Last Modified: 2012-05-07
i am writing a application in asp.net 2.0  to read the users from active directory.
but i am receiving error as : a referral was returned from the server in .net application

my code  is:
Try
          Dim path As String = "LDAP://100.0.0.1/CN=Users,DC=firm,DC=domainname,DC=com"
            Dim AD As DirectoryEntry = New DirectoryEntry(path)
            AD.Username = "domainname\username"
            AD.Password = "password"

            AD.Children.SchemaFilter.Add("users")
            Dim obj As DirectoryEntry
            For Each obj In AD.Children

                'Dim replaced As String = FixString(obj.Name.ToString(), "CN=", "")
                Dim replaced As String = obj.Name.ToString()
                'replaced = FixString(replaced, "\\", "")
                ADUsersList.Items.Add(replaced)

            Next
        Catch e As Exception

            'MsgBox("Error is " & e.Message)
            'Return RetArray

        End Try
0
Comment
Question by:softtt
  • 9
  • 7
  • 2
18 Comments
 
LVL 11

Expert Comment

by:Muhammad Ousama Ghazali
ID: 24409477
0
 
LVL 70

Expert Comment

by:Chris Dent
ID: 24409894

It isn't the cause of your problem, but this won't help much:

> AD.Children.SchemaFilter.Add("users")

The filter should be "user" not "users". "user" is the objectClass you're filtering to.

Otherwise I agree with moghazali. The most likely cause of your problem is an invalid value for "path".

Chris
0
 

Author Comment

by:softtt
ID: 24419008

Dea rmoghazali:

from the second link i found that it says add the domain control name
in the code i already added the domainname
Dim path As String = "LDAP://100.0.0.1/CN=Users,DC=firm,DC=domainname,DC=com"

even though same error.


0
 
LVL 11

Expert Comment

by:Muhammad Ousama Ghazali
ID: 24419110
Please try replacing IP address with the "domainname" and check. If the full domain name is something like "mydomain.org" then replace IP with "mydomain.org" rather than "mydomain". In you sample, I think it would be a ".com".
0
 

Author Comment

by:softtt
ID: 24419192

Dear moghazali:

i replace the IP with the domain name , even though same error.
0
 
LVL 11

Expert Comment

by:Muhammad Ousama Ghazali
ID: 24419240
Try using the code below, I am pasting a modified version from a running implementation. Hope this helps.
Private Function GetDomainUsers(ByVal domainName As String, Optional ByVal userName As String = "", Optional ByVal password As String = "") As DataTable
 

	Dim dtDomainUsers As DataTable = Nothing

	Dim count As Integer

	Dim dirEntry As DirectoryEntry = Nothing

	Dim dirSearcher As DirectorySearcher = Nothing

	Dim resultCollection As SearchResultCollection = Nothing

	Dim blnPassCredentials As Boolean = False
 

	Try

		dirEntry = New DirectoryEntry(GetLdapFormattedDomainName(domainName))
 

		If userName.Length > 0 Then dirEntry.Username = userName : blnPassCredentials = True
 

		If password.Length > 0 Then dirEntry.Password = password : blnPassCredentials = True
 

		If blnPassCredentials Then dirEntry.AuthenticationType = AuthenticationTypes.Secure
 

		dirSearcher = New DirectorySearcher(dirEntry)
 

		With dirSearcher
 

			.Sort = New SortOption("samAccountName", SortDirection.Ascending)
 

			.Filter = "(objectCategory=User)"	' search filter
 

			.PropertyNamesOnly = True
 

			.PropertiesToLoad.Add("samAccountName")

			.PropertiesToLoad.Add("displayName")
 

			.SearchScope = SearchScope.Subtree
 

			.PageSize = 500
 

		End With
 

		resultCollection = dirSearcher.FindAll()
 

		count = resultCollection.Count
 

		If count > 0 Then
 

  		dtDomainUsers = New DataTable("DomainUsers")

			dtDomainUsers.Columns.Add("LogonName")

			dtDomainUsers.Columns.Add("FullName")

			dtDomainUsers.Columns.Add("Sid")
 

			Dim rowTemp As DataRow = Nothing
 

			For intIterate As Integer = 0 To count - 1 Step 1
 

				rowTemp = dtDomainUsers.NewRow()

				rowTemp("LogonName") = resultCollection(intIterate).GetDirectoryEntry().Properties("samAccountName").Value

				rowTemp("FullName") = resultCollection(intIterate).GetDirectoryEntry().Properties("displayName").Value

				rowTemp("Sid") = resultCollection(intIterate).GetDirectoryEntry().Properties("objectSid").Value
 

				dtDomainUsers.Rows.Add(rowTemp)
 

			Next intIterate
 

		End If
 

	Catch ex As Exception

    Throw
 

	End Try
 

	Return dtDomainUsers
 

End Function
 

Private Function GetLdapFormattedDomainName(ByVal domainName As String) As String

	'Generic Return Sample: "LDAP://<domainName>/DC=<domainNamePart1>,DC=<domainNamePart2>,DC=<domainNamePartN>"

	'Specific Return Sample: "LDAP://mydomain/DC=mydomain,DC=com,DC=pk" where domainName = mydomain.com.pk
 

	If domainName Is Nothing OrElse domainName.Length = 0 Then Throw New ArgumentNullException("domainName")
 

	Dim strDomainName As String()

	Dim strQuery As String = String.Empty
 

	If domainName.IndexOf(".") >= 0 Then
 

		strDomainName = domainName.Split(".")
 

		For Each item As String In strDomainName
 

			strQuery &= "DC=" & item & ","
 

		Next
 

		strQuery = strQuery.Substring(0, strQuery.Length - 1)
 

	End If
 

	domainName = "LDAP://" & domainName
 

	If strQuery.Length > 0 Then domainName &= "/" & strQuery
 

	Return domainName
 

End Function

Open in new window

0
 
LVL 70

Expert Comment

by:Chris Dent
ID: 24419469

The return of a Referral does indicate that you're talking to an LDAP server, so the IP / domain name portion is fine. I would verify the LDAP path you're passing it: "CN=Users,DC=firm,DC=domainname,DC=com". It looks fine at first glance assuming the domain is "firm.domainname.com".

Chris
0
 

Author Comment

by:softtt
ID: 24419636
dear moghazali:

very very very Thanks a lot for your help
with your code i got the information.
actually i tested this in my virtual machines, i created 2 virtual machine 1 is server and 1 is domain,
then i retrieve the information from domain ,
let me test this in real environment

regards.
shams




0
 

Author Comment

by:softtt
ID: 24419719

Dear moghazali:

now i am creating a login page.  and check that user from this active directory,
how i can give authenticate from this active directory.
if user is available in this active directory. then he will be login to proceed.

i need help from you.

regards
shams
0
 
LVL 11

Accepted Solution

by:
Muhammad Ousama Ghazali earned 500 total points
ID: 24419879
Now, instead of a code used by me, I am refering you to an official documentation page which have a good example and explanation how you could do that:
http://support.microsoft.com/kb/326340 and/or http://msdn.microsoft.com/en-us/library/ms998360.aspx
 Hope this helps.
0
 

Author Comment

by:softtt
ID: 24455031

Dear moghazali:

very very thanks for your solution , i got success from the above links,

regards.
shams
0
 

Author Closing Comment

by:softtt
ID: 31582488
Dear moghazali:

very very thanks for your solution , i got success from the above links,

regards.
shams
0
 
LVL 11

Expert Comment

by:Muhammad Ousama Ghazali
ID: 24455661
I am glad that it helped. Happy programming.
0
 

Author Comment

by:softtt
ID: 24467798
Dear moghazali:

when i publish this active directory application i am getting error.

Error authenticating. Error authenticating user. Logon failure: unknown user name or bad password
but it works fine in my local p.c.

regards
shams.
0
 
LVL 11

Expert Comment

by:Muhammad Ousama Ghazali
ID: 24467993
Hi,
Use the function GetDomainUsers with user name and password being passed. This user name/password must be of an active account within the Domain whose name is passed as first argument and where probably you are publishing your side.
One other alternative might be to use personalization in ASP.NET. Check if the above works otherwise I'll try to point you to some resources on ASP.NET personalization.
0
 
LVL 11

Expert Comment

by:Muhammad Ousama Ghazali
ID: 24468125
Correction: ASP.NET Impersonation
0
 

Author Comment

by:softtt
ID: 24468394

Dear moghazali:

when i publish in my local p.c also it is not working.
if i run the application it works fine.

regards
shams
0
 

Author Comment

by:softtt
ID: 24550075
Dears,

please any body help.
i am using this class to retrieve users information from active directory.
first time when i am login its work fine, but even i am searching again the variable of (filterAttributeDept ) value is empty.

Public Function IsAuthenticated(ByVal domain As String, ByVal username As String, ByVal pwd As String) As Boolean

        Dim domainAndUsername As String = domain & "\" & username
        Dim entry As DirectoryEntry = New DirectoryEntry(_path, domainAndUsername, pwd)

        Try
            'Bind to the native AdsObject to force authentication.                  
            Dim obj As Object = entry.NativeObject
            Dim search As DirectorySearcher = New DirectorySearcher(entry)

            search.Filter = "(SAMAccountName=" & username & ")"
            search.PropertiesToLoad.Add("cn")
            search.PropertiesToLoad.Add("department")
            search.PropertiesToLoad.Add("memberOf")
            search.PropertiesToLoad.Add("Pager")
            search.PropertiesToLoad.Add("Aliases")
            Dim result As SearchResult = search.FindOne()

            If (result Is Nothing) Then
                Return False
            End If

            'Update the new path to the user in the directory.
            _path = result.Path
            _filterAttribute = CType(result.Properties("cn")(0), String)
            _filterAttributeDept = CType(result.Properties("memberOf")(2), String)

            'Session("FilterAtt") = _filterAttributeDept

        Catch ex As Exception
            Throw New Exception("Error authenticating user. " & ex.Message)
        End Try

        Return True
    End Function
0

Join & Write a Comment

Using Quotation Marks in PHP This question (http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28217211.html) seems to come up a lot for developers who are new to PHP.  And it got me thinking, "How can we explain the rule…
It’s a strangely common occurrence that when you send someone their login details for a system, they can’t get in. This article will help you understand why it happens, and what you can do about it.
Wufoo.com provides powerful tools for surveying targeted groups, and utilizing data from completed surveys to find trends, discover areas of demand or customer expectation, and make business decisions on products or services.
Use Wufoo, an online form creation tool, to make powerful forms. Learn how to selectively show certain fields based on user input using rules to gather relevant information and data from your forms. The rules feature provides you with an opportunity…

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now