Smart questions
Smart answers
Smart people
INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Member Login




Remember Me
Forgot Password?
Join Us!

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips now!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

Join Tek-Tips
*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.
Jobs from Indeed

Link To This Forum!

Partner Button
Add Stickiness To Your Site By Linking To This Professionally Managed Technical Forum.
Just copy and paste the
code below into your site.

Example of ASP LDAP query string?Helpful Member!(14) 

MikeBronner (Programmer) (OP)
10 Sep 02 19:30
Could someone post an example of ASP code used to query LDAP without any proprietary components?

Thanks!

Take Care,
Mike

mjcreamer (Programmer)
6 Dec 02 10:46
Were you every able to find something like this... it would be very helpful to me as well.

Thanks!
Michael
addsd (Programmer)
25 Feb 03 10:53
HI.

Have you got any solution to connect to LDAP server ?. I'm also looking for a code as how to connect to LDAP from ASP.  Could u pls share if you got anu solution for this.

Thanks

Ahmed
MikeBronner (Programmer) (OP)
25 Feb 03 11:04
no solution found yet... anyone else?

Take Care,
Mike

Helpful Member!  RoKKos (Programmer)
26 Feb 03 4:21
This link might be what you are looking for
http://www.4guysfromrolla.com/webtech/041800-1.shtml
Helpful Member!(11)  zcolton (IS/IT--Management)
1 May 03 13:19
I have a small set of asp pages the queries ldap.
You can check them out at:
http://www.burltwpsch.org/district/BTSphoneno1.asp
Click the search button. If is seems like something you can use as a model I can zip them up and email them to you

zcolton@burltwpsch.org
zcolton (IS/IT--Management)
2 May 03 9:44
zcolton (IS/IT--Management)
2 May 03 11:02
The code is available at:

http://www.burltwpsch.org/users/zcolton/tools/phonebook.zip

I would appriciate comments and suggestions if you download the code.

Zac
RoKKos (Programmer)
5 May 03 7:36
U have not closed your connections. Try adding

con.Close
Set rs = Nothing
Set con = Nothing

in the end of your asp-files were U have conncetions.
But I have never connected to a LDAP befor so I dont know if U have to do it here :)
zcolton (IS/IT--Management)
5 May 03 8:59
RoKKos -

Thank you for catching that error.

zcolton
ColdFusionKing (Programmer)
15 Jul 03 10:27
Hi Guys,

I want to connect to my IPlanet LDAP Server using ASP. This is how I connect to the server using ColdFusion. Can somebody please show me how to QUERY the LDAP Server using ASP.

ColdFusion:
-----------

<CFLDAP
 server="ldapserver"
 port="389"
 action="query"
 name="results"
 start="o=microsoft"
 scope="onelevel"
 attributes="dn"
 sort="ou"
 maxrows="100"
 timeout="20">

<table border="0" cellspacing=2 cellpadding=2>
<cfoutput query="results">
<tr>
    <td>#dn#<br></td>
</tr>
</cfoutput>
</table>

Regards,
Allan
zcolton (IS/IT--Management)
15 Jul 03 10:37
This is one of my pages for my W2K Active Directory Phonebook.

<%@ Language=VBScript %>
<%
Option Explicit
Dim con,rs,Com,letter,school
%>
<html>
<head>
<style>
.over { background-color: #FFFF66; cursor: hand}
.out { background-color: #CCCCCC}
</style>
</head>
<body topmargin="0" leftmargin="0" bgcolor="#CCCCCC" >
<%
letter = request.queryString("letter")
school = request.queryString("school")
If letter <> "" Then
Set con = Server.CreateObject("ADODB.Connection")
con.provider ="ADsDSOObject"
con.open "Active Directory Provider"
Set Com = CreateObject("ADODB.Command")
Set Com.ActiveConnection = con
Com.CommandText ="select name, sAMAccountname from 'LDAP://hs_inst.burlington.org/OU=Staff,OU=Domain Users,DC=burlington,DC=org' WHERE objectCategory='person' AND department='"+school+"' AND sn='"+letter+"*' ORDER BY name"
Set rs = Com.Execute
%>
<table border="0" cellpadding="0" bgcolor="#CCCCCC">
 <%
 Do While Not rs.EOF
 %>
 <tr><td onMouseOver="this.className='over'" onMouseOut="this.className='out'" class="out" valign="middle" onclick="window.open('info.asp?user=<% response.write rs("sAMAccountname")%>','InfoFrame');window.open('emailstart.htm','EmailFrame');"><a><b><font color="#000080" face="Verdana" size="2">
   <% response.write rs("Name")%></font></b></a></td>
 </tr>
 <%
     rs.MoveNext
     Loop
     rs.Close
%>
</table>
<%
con.Close
Set rs = Nothing
Set con = Nothing
End If
%>
</body>
</html>
ColdFusionKing (Programmer)
16 Jul 03 4:19
zcolton, thank you for the code, however I can't get it to work. If I give you my ldap server details, can you add it in your code and post it here.

LDAP Server: develLdap
Port: 389
Action: Query
Start: "o=microsoft"

Can you do this for me?

Regards
Allan
zcolton (IS/IT--Management)
16 Jul 03 8:18
The code I posted has a few items that need to be taken into consideration. I posted a link in a post above where you can download the complete phonebook. It has a readme that has some vital info in it to get it to work on your system. What exaclty do you want the asp page to do?
ColdFusionKing (Programmer)
16 Jul 03 10:07
I want my asp code to query m iPlanet LDAP directory. I showed you how ColdFusion makes call to the LDAP Server, I want to do exactly the same with ASP
ColdFusionKing (Programmer)
16 Jul 03 10:08
I'm a newbie to ASP and would appreciate your help
zcolton (IS/IT--Management)
17 Jul 03 11:59
The code I pasted above will work, you will need to modify it to match your setup.
ColdFusionKing (Programmer)
18 Jul 03 6:18
Your code connect to the Active Directory Server it being a microsoft product. But I'm trying to connect to iPlanet (Sun product) using ASP.

Here is the code, it works.

<%
Set pLDAP = CreateObject("LDAPClient.3")
Call pLDAP.Connect("ldapserver","389","cn=Directory Manager", "password")

Set pAttributeNames = CreateObject("LDAPClient.StringCollection")
Call pAttributeNames.Add("givenName")

' Find all the Johns and all the Smiths
Set pEntries = pLDAP.Search("o=airus", "(|(givenName=John)(sn=Smith))", , pAttributeNames)
For Each pEntry In pEntries
    Response.Write(pEntry.Attributes("givenName").Values(0).Value & "<br>")
Next
%>

I have downloaded the The ActiveX LDAP Client. ActiveX component is designed for accessing Lightweight Directory Access Protocol (LDAP) servers from Visual Basic and Active Server Pages applications. The LDAP Client can be used from any application that supports ActiveX components.

The licensed version of the ActiveX LDAP Client is not available for download.

Do you know if there is a ActiveX LDAP component which can be used for free to connect to LDAP

Regards,

Allan
 
barradas (Programmer)
23 Jul 03 6:57
i zcolton
your code give me the error:

Provider(0x80004005)
Unspecified error

Line:
Set rs = Com.Execute

Can you help me ?
ColdFusionKing (Programmer)
23 Jul 03 7:22
did you install ActiveX LDAP Client Evalutaion Copy.(http://www.ldapservices.com/Downloads/download.asp). I'm using iPlanet LDAP Server and it works for me.
barradas (Programmer)
23 Jul 03 14:06
mdac 2.7 was the solution. gracias
Helpful Member!  jbigham (IS/IT--Management)
1 Aug 03 11:16
Many thanks Zac, works perfectly. I have hacked it up to do the following.

1. Removed the web based email function, using it internally so users will use their email clients for communication.

2. Changed it to default to a listing of all employees on load, instead of a blank page telling them to choose a letter and/or location

3. The main page now shows Full Name, Title, Department, Location, Phone, and Fax. Right frame elimanted so all info above fits. No need for a details page per user now. Instead, the users name is a mailto: link now.

4. Added headings of Full Name, Title, Department, Location, Phone, and Fax above output listing.

Basically, I have it down to two files, phonebook.asp and list.asp

My changes, like Zac's contribution, are free for the asking.
zcolton (IS/IT--Management)
13 Aug 03 14:51
I have modified my code so that it requires no changes to work on your system. If you do download a copy from the link I posted above, please take a look at the readme.
JanetSze (TechnicalUser)
9 Sep 03 2:50
hi Zac, I tested the phonebook.asp at my win2K IIS. The asp listed A to Z, but when I click on any of the letter, nothing return. In fact an "Error on Page" detected at the bottom task bar with error details 'document.departmentchoice.departmentname[...].checked' is null or not an object.
Please advice. Thanks.
zcolton (IS/IT--Management)
9 Sep 03 7:48
The top bar of radio buttons is used to select which department the list of user is filtered with. Are you using that field in you AD? Let me know if your still having problems.
ToddFuhrman (IS/IT--Management)
10 Oct 03 1:33
JBIGHAM,

I would love to have that code you hacked up. Very nice work zcolton.

tfuhrman@frsd.k12.nj.us
ToddFuhrman (IS/IT--Management)
10 Oct 03 1:55
I was wondering if your modified version still displays the departments up top?

Ideally for me would be to display the departments up top, but upon choosing them have them auto display all members of that department by display name or last name/ first name, which in my case is their display name.

I'm thinking my desired phonebook lies somewhere between the original and your modified version.

Hopefully you check in soon and can send those files over.  Thank you in advance.
zcolton (IS/IT--Management)
10 Oct 03 9:02
ToddFuhrman,

It wouldn't take much to change the latest code I have to do what you want. Would you like me to put something together for you?
ToddFuhrman (IS/IT--Management)
10 Oct 03 11:39
That would be awesome.
zcolton (IS/IT--Management)
10 Oct 03 13:31
ToddFuhrman (IS/IT--Management)
13 Oct 03 14:55
Thanks Zac.  I downloaded and put it up at the web.  I was able to change a lot of things I wanted to but I did not touch the email component of it.  

Can you tell me how to change the code to a mailto: type response.  I don't want anonymous emails, we want to click on the email address and have the clients email application open a new mail.

Check out what I have, looks great!

http://www.frsd.k12.nj.us/phone/phonebook.asp
zcolton (IS/IT--Management)
14 Oct 03 10:01
Zip up your phonebook directory and email it to me. I can make the changes.
zcolton@burltwpsch.org
jbigham (IS/IT--Management)
14 Oct 03 10:57
YGM

I have some different features in my endeavor.

The ability to navigate up the org chart, assuming you have populated your manager field in ADUC. Found on the users details page (click on a user)

Email is setup to use the users email client. Just plain safer this way (spammers, jokers, audit tracking, etc)

Default behavior is to show all users on launch, rather than requiring a letter to be chosen.

An option to revert back to show all users at any time, see * symbol.

Phone # field pulls from the 1st element in the otherTelephone array.

Layout is somewhat different.

Not yet implemented the code to make it more transportable (still have to code server names)
zcolton (IS/IT--Management)
14 Oct 03 11:02
jbigham

take a look at my newest code. It doesn't require server or domain names to be hard coded. This exmple just spits out a list of departments. I was using this to help someone else.

Example:


<%@ Language=VBScript %>
<%
Option Explicit
Dim con,rs,Com,objADsPath,objDomain
%>
<html>
<head>
</head>
<body bgcolor="#CCCCCC">
<%
Set objDomain = GetObject ("GC://RootDSE")
objADsPath = objDomain.Get("defaultNamingContext")
Set objDomain = Nothing
Set con = Server.CreateObject("ADODB.Connection")
con.provider ="ADsDSOObject"
con.open "Active Directory Provider"
Set Com = CreateObject("ADODB.Command")
Set Com.ActiveConnection = con
Com.CommandText ="select department from 'GC://"+objADsPath+"' WHERE department ='*'"
Set rs = Com.Execute

Do While Not rs.EOF Or rs.BOF

Response.Write rs("department") & "<BR>"

rs.MoveNext
Loop
rs.Close

con.Close
Set rs = Nothing
Set con = Nothing
%>
</body>
</html>
jbigham (IS/IT--Management)
14 Oct 03 15:12
I was thinking about doing something like that... just no time. This is the "fun stuff" that I have to hold off on until other projects are completed.

A variation of that will work for the printable list I wanted to do though, as grouping by department is preferred. I'd just do:

Response.Write rs("department") & "<BR>"

<insert loop to list associated departmental employees)

rs.MoveNext

I'll keep you udated as I make changes... I have webspace, guess I should just start posting my sources. Maybe after I weed out our hard-coded company info in there.
jbigham (IS/IT--Management)
14 Oct 03 15:23
Quick note, I think you need to loop through that recordset again so that you can extract distinct entries for departments... so you don't have repeating groups.

I see you did this for someone else... so it may not apply for you setup.
zcolton (IS/IT--Management)
14 Oct 03 20:42
The code I just posted was for someone who was having problems just getting the department info. This is my actual asp page that will retrieve a complete list of departments and use them as choices for the query.


<%@ Language=VBScript %>
<%
Option Explicit
Dim t,x,con,rs,Com,objADsPath,objDomain,iLoop,bolFound,strdepartments
strdepartments=""
%>
<html>
<head>
<script type="text/javascript">

function listlink(a,q)
{
for (var c = 0; c <= q; c++)
    {if (document.departmentchoice.departmentname[c].checked) b = document.departmentchoice.departmentname[c].value;}
open('list.asp?letter='+a+'&department='+b,'ListFrame');
open('info.asp','InfoFrame');
open('blank.htm','EmailFrame');
}

function reflist()
{
open('list.asp','ListFrame');
open('blank.htm','InfoFrame');
open('blank.htm','EmailFrame');
}
</script>

<title>Phone List</title>
<style>
.over { background-color: #FFFF66; cursor: hand}
.out { background-color: #CCCCCC}
</style>
</head>
<body bgcolor="#CCCCCC" topmargin="0" leftmargin="0">
<%
Set objDomain = GetObject ("GC://rootDSE")
objADsPath = objDomain.Get("defaultNamingContext")
Set objDomain = Nothing
Set con = Server.CreateObject("ADODB.Connection")
con.provider ="ADsDSOObject"
con.open "Active Directory Provider"
Set Com = CreateObject("ADODB.Command")
Set Com.ActiveConnection = con
Com.CommandText ="select department from 'GC://"+objADsPath+"' WHERE objectCategory='person' AND department='*' ORDER BY department"
Set rs = Com.Execute

Do While Not rs.EOF
 dim myarray
 myarray=split(strdepartments,",")
 bolFound = False
 For iLoop = LBound(myarray) to UBound(myarray)
  If CStr(myarray(iLoop)) = CStr(rs("department")) Then
   bolFound = True
  End If
 Next
 IF bolFound = False Then
  If strdepartments="" then
   strdepartments=rs("department")
   Else
    strdepartments=strdepartments&","&rs("department")
  End If
 End If
rs.MoveNext
Loop
rs.Close
dim deparray
deparray=split(strdepartments,",")
t=UBound(deparray)+1
%>
<form name="departmentchoice">
<table border="1" cellpadding="0" cellspacing="0" width="550">
<tr><td colspan="26" valign="middle" align="center" height="20"><p><font face="Tahoma" size="1"><b>
  <input type="radio" onclick="reflist();" name="departmentname" value="*" checked>All
<%For iLoop = LBound(deparray) to UBound(deparray)%>
  <input type="radio" onclick="reflist();" name="departmentname" value="<%response.write deparray(iLoop)%>"><%response.write deparray(iLoop)%>
<%Next%>
</b></font></p></td>
</tr>
<tr>
<%For x = 65 to 90%>
 <td onMouseOver="this.className='over'" onMouseOut="this.className='out'" class="out" width="20" height="20" valign="middle" align="center" onclick="listlink('<%response.write chr(x)%>','<%response.write t%>');"><a><b><font color="#000080" face="Verdana" size="2"><%response.write chr(x)%></font></b></a></td>
<%Next%>
</tr>
<tr>
 <td valign="top" colspan="10"><IFRAME NAME="ListFrame" FRAMEBORDER="0" SCROLLING="AUTO" SRC="list.asp" width="223" height="458"></IFRAME></td>
 <td valign="top" colspan="16"><IFRAME NAME="InfoFrame" FRAMEBORDER="0" SCROLLING="AUTO" SRC="blank.htm" width="320" height="125"></IFRAME>
 <IFRAME NAME="EmailFrame" FRAMEBORDER="0" SCROLLING="AUTO" SRC="blank.htm" width="320" height="330"></IFRAME></td>
</tr>
</table>
</form>
</body>
</html>

LordBass (MIS)
16 Oct 03 10:18
Greetings all,
I'm attempting to implement something close to this on an ASP through FrontPage (with MS back end), and am not sure how to modify it for my situation.

What I'm trying to do is get an ASP to detect the currently logged on user and query AD to display their email address on the screen. I've already got my ASP running a JavaScript that will properly detect and display their username, but this bit with displaying the email address has been more daunting. I'm not a programmer, so I'm trying to piece things into place with examples from other sites. No luck so far.

My concerns are:
1. My method has been to use the (Request.ServerVariables("LOGON_USER")) variable to query LDAP and find the email address, but no luck so far.
2. What is the proper URL syntax for an LDAP server? I have a domain controller name to work off of, but have so far been unable to properly connect to it. I'm not sure how to fit this in with the DN.. Still learning how these all interact.
3. My ASP runs a JavaScript to find the username of the user accessing the page. Is it also possible to run a VBScript on the same page?

*phew!* That's enough to get started. Any help is *greatly* appreciated.

Thanks!
Chris
zcolton (IS/IT--Management)
16 Oct 03 10:19
Post the code and I will take a look at it.
LordBass (MIS)
16 Oct 03 10:48
This is the best example that I've been able to work with so far. The example was taken from http://www.experts-exchange.com/Web/Web_Languages/ASP/Q...

I believe this example will do what I'm looking for, though the only value I really need returned is the email address (this should return many more values, but if it can work, it can be cut back to just display the email address).

I think the only change needed here is to add the correct LDAP info.. The values in this code are from the example on the link above. Perhaps also change the 'script language' value to VBScript? The final working version of this code will be pasted onto an ASP form page with JavaScript though, so not sure yet how those will work together.

<html>

<head>
<meta name="GENERATOR" content="Microsoft FrontPage 5.0">
<meta name="ProgId" content="FrontPage.Editor.Document">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>testsearch</title>

<script language="JavaScript"></script>

</head>

<body>

<%
on error resume next

     strLogonID = Request.Servervariables("LOGON_USER")

     If InStr(strLogonID, "\") > 0 Then
          strLogonID = LCase(Right(strLogonID, InStr(strLogonID, "\") - 2))
     End If
     
     id = LCase(strLogonID)

    Set User = GetObject("WinNT://scotland/" & id & "")
     Fullname = User.Fullname

'###### Pathway to use to Active Directory ######
testpath = "LDAP://CN=" & FullName & ",OU=\#Scots Users,DC=scotland,DC=co,DC=uk"
set usr = GetObject(testpath)

'###### Flush any cache held ######
usr.GetInfo

'###### Active Directory variables ######
strName = usr.get("givenName") '###### Users Christian Name ######
strSurname = usr.get("sn") '###### Users Surname ######
strInitials = usr.get("initials") '###### Users Initials ######
displayName = usr.get("displayName") '###### Full Display Name ######
strAddress = usr.get("StreetAddress") '###### Address Information ######
strRoom = usr.get("PhysicalDeliveryOfficeName") '###### Room/Area Information ######
secretary = usr.get("secretary") '###### Secrectary/Assistant ######
strTitle = usr.get("title") '###### Job Title ######
strTelephone = usr.get("telephoneNumber") '###### Official Intneral Telephone Number ######
strFax = usr.get("facsimileTelephoneNumber") '###### Fax Number ######
mobile = usr.get("mobile") '###### Mobile Number ######
telephoneAssistant = usr.get("telephoneAssistant") '###### Telephone Assistant ######
strDepartment = usr.get("department") '###### Department ######
strCC = usr.get("ExtensionAttribute1") '###### COST Centre ######
strBuilding = usr.get("ExtensionAttribute2") '###### Building ######
strDivision = usr.get("ExtensionAttribute3") '###### Division ######
strBranch = usr.get("ExtensionAttribute4") '###### Branch ######
ExtensionAttribute5 = usr.get("ExtensionAttribute5") '###### PC Item Number ######
ExtensionAttribute6 = usr.get("ExtensionAttribute6") '###### External Telephone Number ######
strGroup = usr.get("ExtensionAttribute7") '###### Group ######
othertelephone = usr.get("othertelephone") '###### GTN Telephone Number ######
samaccountname = usr.get("samaccountname") '###### User ID ######
adspath = usr.get("adspath") '###### Pathway to AD? ######
strFullName = usr.get("cn") '###### Full Display Name ######
strMail = usr.get("mail") '###### E-Mail Address ######
strManager = usr.get("manager")                                   '###### Reporting Officer ######
'###### End Active Directory variables ######

set usr = nothing

Response.Write     "Firstname = " & strName & "<br />"
Response.Write     "Surname = " & strSurname & "<br />"
Response.Write     "initials = " & strInitials & "<br />"
Response.Write     "displayName = " & displayName & "<br />"
Response.Write     "StreetAddress = " & strAddress & "<br />"
Response.Write     "PhysicalDeliveryOfficeName = " & strRoom & "<br />"
Response.Write     "secretary = " & secretary & "<br />"
Response.Write     "title = " & strTitle & "<br />"
Response.Write     "telephoneNumber = " & strTelephone & "<br />"
Response.Write     "facsimileTelephoneNumber = " & strFax & "<br />"
Response.Write     "mobile = " & mobile & "<br />"
Response.Write     "telephoneAssistant = " & telephoneAssistant & "<br />"
Response.Write     "department = " & strDepartment & "<br />"
Response.Write     "ExtensionAttribute1 = " & strCC & "<br />"
Response.Write     "ExtensionAttribute2 = " & strBuilding & "<br />"
Response.Write     "ExtensionAttribute3 = " & strDivision & "<br />"
Response.Write     "ExtensionAttribute4 = " & strBranch & "<br />"
Response.Write     "ExtensionAttribute5 = " & ExtensionAttribute5 & "<br />"
Response.Write     "ExtensionAttribute6 = " & ExtensionAttribute6 & "<br />"
Response.Write     "ExtensionAttribute7 = " & strGroup & "<br />"
Response.Write     "othertelephone = " & othertelephone & "<br />"
Response.Write     "samaccountname = " & samaccountname & "<br />"
Response.Write     "adspath = " & adspath & "<br />"
Response.Write     "FullName = " & strFullName & "<br />"
Response.Write     "e-mail = " & strMail & "<br />"
Response.Write     "strManager = " & strManager & "<br />"

If Err.Number <> 0 Then
      GetInfo = False
      Response.Write(Err.Number & ": " & Err.Description) 'always get "The Active Directory datatype cannot be converted to/from a native DS datatype"
      Err.Clear
  Else
      GetInfo = True
  End If
%>

<head> <body>

</body>

</html>

Once again, any direction is greatly appreciated.

Thanks!
Chris
zcolton (IS/IT--Management)
16 Oct 03 12:47
Please post the asp that you do have that does display the username.
LordBass (MIS)
16 Oct 03 13:13
The code that displays the username is:

<%
Dim strNTUser, iPos
strNTUser = RTrim(Request.ServerVariables("LOGON_USER"))
iPos = Len(strNTUser) - InStr(1, strNTUser,"\",1)
strNTUser = Right(strNTUser, iPos)
Response.Write(strNTUSer)
%>

(To function, this requires turning off anonymous access in IIS for the folder this ASP is in. A design feature, according to MS. This particular code example above parses out the domain name of the username.)

And the ASP code is:

<html>

<head>
<meta http-equiv="Content-Language" content="en-us">
<meta name="GENERATOR" content="Microsoft FrontPage 5.0">
<meta name="ProgId" content="FrontPage.Editor.Document">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Add Change</title>

<script language="JavaScript" src="../scripts/calendar.js"></script>

</head>

<body topmargin="0" leftmargin="0">

  <table border="0" cellspacing="0" width="100%" height="4%" id="AutoNumber3" bgcolor="#000080" cellpadding="0" style="border-collapse: collapse" bordercolor="#111111">
    <tr>
      <td width="100%" height="25">
      <p align="center"><font face="Arial Unicode MS" size="5" color="#FFFFFF">
      Change Management</font></td>
    </tr>
  </table>
<div align="center">
  <center>
  <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse" bordercolor="#111111" width="593" height="90%" id="AutoNumber5">
    <tr>
      <td width="593" height="9" colspan="4">
      <p align="center">
      <font face="Arial Unicode MS" size="4">Enter New Change</font></td>
    </tr>
    <tr>
      <td width="120" height="9" align="left">
      <font face="Arial Unicode MS" size="2"><b>
      Request Number:</b></font></td>
      <td width="473" height="9" colspan="3">
      <font size="1" face="Arial Unicode MS">(chosen from db, displayed automatically)</font></td>
    </tr>
    <tr>
      <td width="120" height="9" align="left"><b>
      <font face="Arial Unicode MS" size="2">
      Requestor:</font></b></td>
      <td width="473" height="9" colspan="3">
      <span style="vertical-align: middle"><font face="Arial Unicode MS" size=3>
        <!-- solution from http://www.4guysfromrolla.com/webtech/020201-1.shtml -->
           <!-- displays: DOMAIN\usernam e-->
        <!-- <%Response.Write(Request.ServerVariables("auth_user"))%> -->
        <!-- To display only the username... -->
        <%
        Dim strNTUser, iPos
        strNTUser = RTrim(Request.ServerVariables("LOGON_USER"))
        iPos = Len(strNTUser) - InStr(1, strNTUser,"\",1)
        strNTUser = Right(strNTUser, iPos)
        Response.Write(strNTUSer)
        %>
      
       </font></span>
      </td>
    </tr>
    <tr>
      <td width="120" height="9" align="left"><b>
      <font face="Arial Unicode MS" size="2">
      E-mail:</font></b></td>
      <td width="473" height="9" colspan="3">
      <font size="1" face="Arial Unicode MS">(autofill based on login)</font></td>
    </tr>
    <tr>
      <td width="120" height="9" align="left"><b>
      <font face="Arial Unicode MS" size="2">
      Status:</font></b></td>
      <td width="473" height="9" colspan="3">
      <!--webbot bot="Validation" b-value-required="TRUE" --><input type="text" name="enterStatus" size="20" style="float: left"></td>
    </tr>
    <tr>
      <td width="593" height="9" colspan="4"></td>
    </tr>
    <tr>
      <td width="120" height="8"><b><font face="Arial Unicode MS" size="2">Server Name:</font></b></td>
      <td width="473" height="8" colspan="3">
      <form method="POST" action="--WEBBOT-SELF--" onSubmit="">
        <!--webbot bot="SaveResults" u-file="../_private/form_results.csv" s-format="TEXT/CSV" s-label-fields="TRUE" startspan --><input TYPE="hidden" NAME="VTI-GROUP" VALUE="0"><!--webbot bot="SaveResults" endspan i-checksum="43374" --><p>
        <input type="text" name="enterServer" size="20" style="float: left"></p>
      </form>
      </td>
    </tr>
    <tr>
      <td width="120" height="8"><b><font face="Arial Unicode MS" size="2">Production?
      (Y/N):</font></b></td>
      <td width="473" height="8" colspan="3">
      <form method="POST" action="--WEBBOT-SELF--" onSubmit="return FrontPage_Form2_Validator(this)" language="JavaScript" name="FrontPage_Form2">
        <!--webbot bot="SaveResults" u-file="../_private/form_results.csv" s-format="TEXT/CSV" s-label-fields="TRUE" startspan --><input TYPE="hidden" NAME="VTI-GROUP" VALUE="1"><!--webbot bot="SaveResults" endspan i-checksum="43406" --><p>
        <!--webbot bot="Validation" b-value-required="TRUE" --><select size="1" name="D1" style="float: left">
        <option>Yes</option>
        <option>No</option>
        </select></p>
      </form>
      </td>
    </tr>
    <tr>
      <td width="163" height="4" colspan="3"><b>
      <font face="Arial Unicode MS" size="2">
      Description Of Change:</font></b></td>
      <td width="430" height="8" rowspan="2">
      <textarea rows="5" name="enterDesc" cols="40" style="float: left"></textarea></td>
    </tr>
    <tr>
      <td width="120" height="4" colspan="2"> </td>
      <td width="43" height="4"></td>
    </tr>
    <tr>
      <td width="120" height="8">
      <p align="left"><b><font face="Arial Unicode MS" size="2">Completion
      Date:</font></b></td>
      <td width="473" height="8" colspan="3" style="float: left; position: relative">

<!--solution for the following calendar form found at http://javascript.internet.com/calendars/popup-date-pic...;

    <form name=FrontPage_Form3 style="float: left" onsubmit="return FrontPage_Form3_Validator(this)" language="JavaScript">
    <!--webbot bot="Validation" b-value-required="TRUE" --><input type=text name="datebox" size=15 value="">
        <a href="javascript:show_calendar('calform.datebox');" onmouseover="window.status='Date Picker';return true;" onmouseout="window.status=';return true;">
        <img src="show-calendar.gif" width=24 height=22 border=0></a>
    </form>
    
    </td>
    </tr>
    <tr>
      <td width="163" height="4" colspan="3"><b>
      <font face="Arial Unicode MS" size="2">Additional
      Comments:</font></b></td>
      <td width="430" height="8" rowspan="2">
      <textarea rows="3" name="enterComment" cols="40"></textarea></td>
    </tr>
    <tr>
      <td width="120" height="4" colspan="2"><b><font face="Arial Unicode MS"> </font></b></td>
      <td width="43" height="4"></td>
    </tr>
    <tr>
      <td width="593" height="16" colspan="4">
      <p align="center"><input type="submit" value="Submit" name="B1">    
      <input type="button" value="Cancel" name="B2" onClick="location.href='../change/home.htm'"></td>
    </tr>
  </table>
  </center>
</div>

</body>

</html>
zcolton (IS/IT--Management)
16 Oct 03 14:04
I have two sets of code that will spit out the email address of the currently logged in user:

1) Requires Integrated Windows Authentication only
 - Must be enabled on client (IE advanced properties)
 - A username and password of an AD account that has the rights to search the AD needs to be hardcoded


<%@ Language=VBScript %>
<%
Option Explicit
Dim strUsername,con,rs,Com,objADsPath,objDomain
%>
<html>
<head>
</head>
<body>
<%
strUsername = Request.ServerVariables("auth_user")
strUserName = Right(strUserName, Len(strUserName) - InStrRev(strUserName, "\"))
Set objDomain = GetObject ("GC://rootDSE")
objADsPath = objDomain.Get("defaultNamingContext")
Set objDomain = Nothing
Set con = Server.CreateObject("ADODB.Connection")
con.provider ="ADsDSOObject"
con.Properties("User ID") = "BURLINGTON\adsearch"
con.Properties("Password") = "adsearch"
con.open "Active Directory Provider"
Set Com = CreateObject("ADODB.Command")
Set Com.ActiveConnection = con
Com.CommandText ="select mail FROM 'GC://"+objADsPath+"' where sAMAccountname='"+strUsername+"'"
Set rs = Com.Execute
response.write rs("mail")
rs.Close
con.Close
Set rs = Nothing
Set con = Nothing
%>
</body>
</html>


2) Requires Basic Authentication
 - Prompts for username and password]
 - Domain name needs to hardcoded in line "con.Properties("User ID") =


<%@ Language=VBScript %>
<%
Option Explicit
Dim strUsername,strUsernamea,strpassword,con,rs,Com,objADsPath,objDomain
%>
<html>
<head>
</head>
<body>
<%
strUsername = Request.ServerVariables("auth_user")
strpassword = Request.ServerVariables("AUTH_PASSWORD")
strUserNamea = Right(strUserName, Len(strUserName) - InStrRev(strUserName, "\"))
Set objDomain = GetObject ("GC://rootDSE")
objADsPath = objDomain.Get("defaultNamingContext")
Set objDomain = Nothing
Set con = Server.CreateObject("ADODB.Connection")
con.provider ="ADsDSOObject"
con.Properties("User ID") = "BURLINGTON\"+strUsername
con.Properties("Password") = strpassword
con.open "Active Directory Provider"
Set Com = CreateObject("ADODB.Command")
Set Com.ActiveConnection = con
Com.CommandText ="select mail FROM 'GC://"+objADsPath+"' where sAMAccountname='"+strUsernamea+"'"
Set rs = Com.Execute
response.write rs("mail")
rs.Close
con.Close
Set rs = Nothing
Set con = Nothing
%>
</body>
</html>
LordBass (MIS)
16 Oct 03 15:36
Wow. I got it working! For reference, here's how it's working for me:

1. Code is running on an ASP in a folder with 'anonymous access' turned off in IIS, as described above to allow the 'display username' javascript to work. (As a note, I have it working without requiring 'basic authentication' and also without checking the 'integrated windows authentication' box in IE - the latter of these is not an option for us as nearly all user's desktops are locked down and cannot be changed).

2. I used the code from the second example above, and removed the following three lines of code:

strpassword = Request.ServerVariables("AUTH_PASSWORD")
con.Properties("User ID") = "BURLINGTON\"+strUsername
con.Properties("Password") = strpassword

I was able to paste in the bits about 'VBScript' and have this successfully run along with the existing javascript. May not be groundbreaking stuff, but I'm impressed at least.

Since the ASP in question is already successfully obtaining the username of the logged-on user, I guessed it should be able to query AD without extra authentication. These may not be related, but it works.

zcolton - Thank you *so much* for your direction on this. Great to see the code in action. Piece by piece I'll pick this up. :)

Cheers,
Chris
zcolton (IS/IT--Management)
16 Oct 03 22:26
Post what you ended up with. I'ld like to see the changes you made.
LordBass (MIS)
17 Oct 03 9:33
I'm pleased that this was possible to implement without hardcoding a LDAP server or any company information.. I'm reviewing the code to figure out how this works. :)

Here's my code. The section in question is bold:

<%@ Language=VBScript %>
<%
Option Explicit
Dim strUsername,strUsernamea,strpassword,con,rs,Com,objADsPath,objDomain
%>

<html>

<head>
<meta http-equiv="Content-Language" content="en-us">
<meta name="GENERATOR" content="Microsoft FrontPage 5.0">
<meta name="ProgId" content="FrontPage.Editor.Document">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Add Change</title>

<script language="JavaScript" src="../scripts/calendar.js"></script>

</head>

<body topmargin="0" leftmargin="0">

  <table border="0" cellspacing="0" width="100%" height="4%" id="AutoNumber3" bgcolor="#000080" cellpadding="0" style="border-collapse: collapse" bordercolor="#111111">
    <tr>
      <td width="100%" height="25">
      <p align="center"><font face="Arial Unicode MS" size="5" color="#FFFFFF">
      Change Management</font></td>
    </tr>
  </table>
<div align="center">
  <center>
  <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse" bordercolor="#111111" width="593" height="90%" id="AutoNumber5">
    <tr>
      <td width="593" height="9" colspan="4">
      <p align="center">
      <font face="Arial Unicode MS" size="4">Enter New Change</font></td>
    </tr>
    <tr>
      <td width="120" height="9" align="left">
      <font face="Arial Unicode MS" size="2"><b>
      Request Number:</b></font></td>
      <td width="473" height="9" colspan="3">
      <font size="1" face="Arial Unicode MS">(chosen from db, displayed automatically)</font></td>
    </tr>
    <tr>
      <td width="120" height="9" align="left"><b>
      <font face="Arial Unicode MS" size="2">
      Requestor:</font></b></td>
      <td width="473" height="9" colspan="3">
      <span style="vertical-align: middle"><font face="Arial Unicode MS" size=3>
        <!-- solution from http://www.4guysfromrolla.com/webtech/020201-1.shtml -->
           <!-- displays: DOMAIN\usernam e-->
        <!-- <%Response.Write(Request.ServerVariables("auth_user"))%> -->
        <!-- To display only the username... -->
        <%
        Dim strNTUser, iPos
        strNTUser = RTrim(Request.ServerVariables("LOGON_USER"))
        iPos = Len(strNTUser) - InStr(1, strNTUser,"\",1)
        strNTUser = Right(strNTUser, iPos)
        Response.Write(strNTUSer)
        %>
      
       </font></span>
      </td>
    </tr>
    <tr>
      <td width="120" height="9" align="left"><b>
      <font face="Arial Unicode MS" size="2">
      E-mail:</font></b></td>
      <td width="473" height="9" colspan="3">
      <font size="3" face="Arial Unicode MS">
      
<%
strUsername = Request.ServerVariables("auth_user")
strUserNamea = Right(strUserName, Len(strUserName) - InStrRev(strUserName, "\"))
Set objDomain = GetObject ("GC://rootDSE")
objADsPath = objDomain.Get("defaultNamingContext")
Set objDomain = Nothing
Set con = Server.CreateObject("ADODB.Connection")
con.provider ="ADsDSOObject"
con.open "Active Directory Provider"
Set Com = CreateObject("ADODB.Command")
Set Com.ActiveConnection = con
Com.CommandText ="select mail FROM 'GC://"+objADsPath+"' where sAMAccountname='"+strUsernamea+"'"
Set rs = Com.Execute
response.write rs("mail")
rs.Close
con.Close
Set rs = Nothing
Set con = Nothing
%>

    </font>
    </td>      
    </tr>
    <tr>
      <td width="120" height="9" align="left"><b>
      <font face="Arial Unicode MS" size="2">
      Status:</font></b></td>
      <td width="473" height="9" colspan="3">
      <!--webbot bot="Validation" b-value-required="TRUE" --><input type="text" name="enterStatus" size="20" style="float: left"></td>
    </tr>
    <tr>
      <td width="593" height="9" colspan="4"></td>
    </tr>
    <tr>
      <td width="120" height="8"><b><font face="Arial Unicode MS" size="2">Server Name:</font></b></td>
      <td width="473" height="8" colspan="3">
      <form method="POST" action="--WEBBOT-SELF--" onSubmit="">
        <!--webbot bot="SaveResults" u-file="../_private/form_results.csv" s-format="TEXT/CSV" s-label-fields="TRUE" startspan --><input TYPE="hidden" NAME="VTI-GROUP" VALUE="0"><!--webbot bot="SaveResults" endspan i-checksum="43374" --><p>
        <input type="text" name="enterServer" size="20" style="float: left"></p>
      </form>
      </td>
    </tr>
    <tr>
      <td width="120" height="8"><b><font face="Arial Unicode MS" size="2">Production?
      (Y/N):</font></b></td>
      <td width="473" height="8" colspan="3">
      <form method="POST" action="--WEBBOT-SELF--" onSubmit="return FrontPage_Form2_Validator(this)" language="JavaScript" name="FrontPage_Form2">
        <!--webbot bot="SaveResults" u-file="../_private/form_results.csv" s-format="TEXT/CSV" s-label-fields="TRUE" startspan --><input TYPE="hidden" NAME="VTI-GROUP" VALUE="1"><!--webbot bot="SaveResults" endspan i-checksum="43406" --><p>
        <!--webbot bot="Validation" b-value-required="TRUE" --><select size="1" name="D1" style="float: left">
        <option>Yes</option>
        <option>No</option>
        </select></p>
      </form>
      </td>
    </tr>
    <tr>
      <td width="163" height="4" colspan="3"><b>
      <font face="Arial Unicode MS" size="2">
      Description Of Change:</font></b></td>
      <td width="430" height="8" rowspan="2">
      <textarea rows="5" name="enterDesc" cols="40" style="float: left"></textarea></td>
    </tr>
    <tr>
      <td width="120" height="4" colspan="2"> </td>
      <td width="43" height="4"></td>
    </tr>
    <tr>
      <td width="120" height="8">
      <p align="left"><b><font face="Arial Unicode MS" size="2">Completion
      Date:</font></b></td>
      <td width="473" height="8" colspan="3" style="float: left; position: relative">

<!--solution for the following calendar form found at http://javascript.internet.com/calendars/popup-date-pic...;

    <form name=FrontPage_Form3 style="float: left" onsubmit="return FrontPage_Form3_Validator(this)" language="JavaScript">
    <!--webbot bot="Validation" b-value-required="TRUE" --><input type=text name="datebox" size=15 value="">
        <a href="javascript:show_calendar('calform.datebox');" onmouseover="window.status='Date Picker';return true;" onmouseout="window.status=';return true;">
        <img src="show-calendar.gif" width=24 height=22 border=0></a>
    </form>
    
    </td>
    </tr>
    <tr>
      <td width="163" height="4" colspan="3"><b>
      <font face="Arial Unicode MS" size="2">Additional
      Comments:</font></b></td>
      <td width="430" height="8" rowspan="2">
      <textarea rows="3" name="enterComment" cols="40"></textarea></td>
    </tr>
    <tr>
      <td width="120" height="4" colspan="2"><b><font face="Arial Unicode MS"> </font></b></td>
      <td width="43" height="4"></td>
    </tr>
    <tr>
      <td width="593" height="16" colspan="4">
      <p align="center"><input type="submit" value="Submit" name="B1">    
      <input type="button" value="Cancel" name="B2" onClick="location.href='../change/home.htm'"></td>
    </tr>
  </table>
  </center>
</div>

</body>

</html>

Thanks once again for the help!
jcaulder (Programmer)
23 Oct 03 14:18
Does anyone know what would prevent the 'department' from AD from displaying? Any time I reference the 'department' in the select clause, I get an 'unspecified error' returned from the asp page.  I can reference it in the where clause with no error.  So:

select name from 'GC://"+objADsPath+"' WHERE department ='Info*'"

works with no errors whereas

select department from 'GC://"+objADsPath+"' WHERE department ='Info*'"

returns the 'unspecified error'.

What could cause this?  Are there 'view' rights set up within AD that would prevent displaying them?

Seems very unusual that it works in the 'where' but not in the 'select'.

Thanks
jbigham (IS/IT--Management)
23 Oct 03 14:39
You may have to take into account what happens when the value is NULL. I remember adding code for this, though I don't remember if it was for department or another object.
jcaulder (Programmer)
23 Oct 03 14:58
I thought that too initially.  But in my 'where' clause in the example, you can see that I'm specifying the department='Info*' so any record returned must have a deparment like 'Info*'.  It can't have a NULL value and still be returned from the query.  The 'where' clause works correctly in referencing the 'department'.  My query as written earlier returns 8 records from AD each associated with the Information Systems department.  If I remove that part of the 'where' clause, all records are returned from AD.  So the 'where department=' works, but the 'select department' does not.

Any other ideas on what might cause it?  It sure has me stumped!

Thanks for the reply!


jbigham (IS/IT--Management)
23 Oct 03 15:03
Well, I'm no SQL guru...

but if a select works anything like a loop, you may not be able to do a check of:

Info* = NULL
Info* <> NULL
etc...

The reason I think this is we know, well almost know, that everyone probably has a name populated. Thus, this works fine. But we may not have gotten around to populating dept for everyone.

Don't know for sure though, sorry. You're welcome to have a copy of my endeavor if you wish, it's somewhat different and may/may not help. Just shoot me an email.
jcaulder (Programmer)
23 Oct 03 15:14
The thing is, I can select other NULL values such as 'telephonenumber' and I get no errors.  As soon as I reference the 'department'in the 'select', even when I know it isn't NULL, I immediately get the error.  I'm not even trying to write the recordset to html at this point.  I'm just executing the query and still get the error.  So it isn't related to displaying the results, it is related to the query itself.  It almost appears that I don't have rights to 'select' the department.  That is the only thing I can think of that would cause this.  

Does AD allow you to limit/restrict viewing rights of fields?  Can fields be blocked from running 'select' statements on them?

pReverend (Programmer)
14 Nov 03 16:24
I have the same problem...can't find any info on it and my Network Admin doesn't know.  It has nothing to do with the field being empty as I can run a query with "Description" in the select portion and I get no error when there are records with no value for that attribute.

Anyone figure this one out???
digatle (TechnicalUser)
19 Dec 03 10:08
I keep getting the following error when looking at some of these code:

Provider error '80004005'
Unspecified error
/test.asp, line 45

Line 45 is:
Set rs = Com.Execute

Is something not installed on my server correctly?

Digatle
pReverend (Programmer)
19 Dec 03 10:14
From what I've researched you have to enable "Trusted for Delegation" on the web server account and your domain must be native.  Our domain is not native...so we'll see.
digatle (TechnicalUser)
19 Dec 03 10:17
What do I need to do then to be able to use these scripts?

Digatle
pReverend (Programmer)
19 Dec 03 11:09
First thing is make sure you are on a native domain.  If you have any W98 machines on the domain then more than likely you are not.  
Enabling "Trusted for Delegation" is done under the Active Directory computer account for the web server.  I can't remember what tab it's under.
If you are not the Net Admin pass this on to him and he should know.  
I'm not 100% that this will allow your scripts to run but from what I've researched this is the starting point.
digatle (TechnicalUser)
23 Dec 03 8:11
We are still struggling with this issue pReverend.  Any other suggestions?

Digatle
zcolton (IS/IT--Management)
23 Dec 03 8:48
To all who are having problems:

Most issues are do to security. A few things to keep in mind. The account used to run the scripts needs to have the ability to search/read active directory. I configured a domain account that has those rights and configured that account for the anonymous account on the directory that contains the phonebook pages. That account also needs to have read rights on that directory and the files contain within. There other ways if you cannot make or do not want to make these changes in the server, but it would require you to hard code a username and password in the asp pages.
pReverend (Programmer)
23 Dec 03 9:48
zcolton,
I assume you can assign groups to read from this as well...that's what we did but no success.  This is on an intranet where I get the client's username from iis so I cannot use anon logon.  I compare the username with the sAMAccountName and collect info about the user that way.  This prevents them from having to logon (again) which irritates most of our users under the current process.
The only time it worked reliably was when the web server was promoted to dc.  
In your experience is it true you have to be on a native domain for these queries to work through trusted delegation?

zcolton (IS/IT--Management)
23 Dec 03 10:03
I am on a native domain, but I think I had this up and running before I switched to a native domain. My IIS server isn't a DC. It is a domain member. The lasted phonebook.zip I put up queries the global catalog (GC://) instead of LDAP. GC searches are faster than LDAP. There are this you can do to test connection. First start with the basics:

<%@ Language=VBScript %>
<%
Option Explicit
Dim objADsPath,objDomain
%>
<html>
<head>
</head>
<body>
<%
Set objDomain = GetObject ("GC://RootDSE")
objADsPath = objDomain.Get("defaultNamingContext")
Set objDomain = Nothing
Response.Write objADsPath & "<BR>"
%>
</body>
</html>

This should spit out your domain info.
pReverend (Programmer)
23 Dec 03 10:07
I can connect with no problems...it's only certain attributes like department and memberOf that hose things up.

I can return cn, mail, description, sn, ect. but there are some that return "Unspecified Error" when I include them in the query.  I tried using both LDAP and GC...same result.  I did find that GC is quicker though.
CoolNutz (MIS)
2 Feb 04 17:37
ZColton,  I hope theres still a chance you may read this.
Back in Oct 14, 2003 you posted a script having listed the departments with a "distinct" option so as to not list every dept 100 times.  I've been trying to do that for a week now and going nutz...  the script you posted worked excellent, only I need to do that in a drop down list.  I've been working with your script trying to make it work and I give up and turning to you for help.  

Thanks
CN
zcolton (IS/IT--Management)
2 Feb 04 23:05
CoolNutz,
Think I know what you want... Give me a little time and I'll post it here.

Z
zcolton (IS/IT--Management)
2 Feb 04 23:18
All Done:

<%@ Language=VBScript %>
<%
Option Explicit
response.buffer = true
Dim con,rs,Com,objADsPath,objDomain,objADOU,iLoop,bolFound,strdepartments,rsarray,rowcounter,numrows
strdepartments=""
%>
<html>
<head>
<title>Phone List</title>
</head>
<body bgcolor="#CCCCCC" topmargin="0" leftmargin="0">
<%
Set objDomain = GetObject ("GC://rootDSE")
objADsPath = objDomain.Get("defaultNamingContext")
Set objDomain = Nothing
Set con = Server.CreateObject("ADODB.Connection")
con.provider ="ADsDSOObject"
con.open "Active Directory Provider"
Set Com = CreateObject("ADODB.Command")
Set Com.ActiveConnection = con
Com.CommandText ="select department from 'GC://"+objADsPath+"' WHERE objectCategory='person' AND department='*' ORDER BY department"
Set rs = Com.Execute
rsarray=rs.getrows
rs.Close
con.close
Set rs = Nothing
Set con = Nothing
numrows=ubound(rsarray,2)

FOR rowcounter=0 to numrows
 dim myarray
 myarray=split(strdepartments,",")
 bolFound = False
 For iLoop = LBound(myarray) to UBound(myarray)
  If CStr(myarray(iLoop)) = CStr(rsarray(0,rowcounter)) Then
   bolFound = True
  End If
 Next
 IF bolFound = False Then
  If strdepartments="" then
   strdepartments=rsarray(0,rowcounter)
   Else
    strdepartments=strdepartments&","&rsarray(0,rowcounter)
  End If
 End If
NEXT

dim deparray
deparray=split(strdepartments,",")
%>
<form>
  <p><select size="1" name="department">
    <option selected>Select a Department</option>
<%For iLoop = LBound(deparray) to UBound(deparray)%>
    <option><%response.write deparray(iLoop)%></option>
<%Next%>
  </select></p>
</form>
</body>
</html>
CoolNutz (MIS)
3 Feb 04 8:14
zcolton,  you are THE MAN! thanks so much, worked perfect.

CN
peacecorp (IS/IT--Management)
18 Feb 04 10:42
Hi,

Im very new at asp and LDAP.  

My scenario:  A user opens an .asp page and some fields get populated with thier information taken from exchange server.

What im doing:
I know how to get a logon name of the local user.

1 - Im trying to search for LDAP servers on my network.
Then select the correct LDAP server (exchange server?)
2 - then in the server use the logon name to get the object that contains the attibutes of the logon user.

populating the field i know but i dont know how to do the LDAP stuff.

Can anyone help?
zcolton (IS/IT--Management)
18 Feb 04 10:46
Describe your network:
Win2k?
Exchange 2K?
We need a little more info.
peacecorp (IS/IT--Management)
18 Feb 04 10:56
oh sorry i forgot
yeah win2k and exchange 2k.

im currently trying to test out your phonebook example.
im looking at the code whre u dont have to hard code the server name.  

Is is possible to do that example using LDAP?
Also im not familiar with what objects in exchange 2k has the attributes of the users


Thanks for your help.
peacecorp (IS/IT--Management)
18 Feb 04 11:27
I was also looking at this page.

http://www.asp-help.com/articles/iis_exchange_ldap.asp

i could piece together the code with no hard coding (GC) and the object ideas together and possibly make a solution

but i have no concrete idea on how to do this
zcolton (IS/IT--Management)
18 Feb 04 13:53
So let me see if I understand:
You want to display user account info about the currently logged in user.
What info do you want to display?
peacecorp (IS/IT--Management)
19 Feb 04 9:34
On my asp form i want to populate; user real name, phone extention, email address into separate text fields.

So when the user accesses this page it will automatically fill in those information.  This asp page is part of our service desk request form.

i could post my form if you would like to see it
zcolton (IS/IT--Management)
19 Feb 04 10:31
All done:



<%@ Language=VBScript %>
<%
Option Explicit
Dim strUsername,con,rs,Com,objADsPath,objDomain,name,telephonenumber,mail
%>
<html>
<head>
</head>
<body>
<%
strUsername = Request.ServerVariables("auth_user")
strUserName = Right(strUserName, Len(strUserName) - InStrRev(strUserName, "\"))
Set objDomain = GetObject ("GC://rootDSE")
objADsPath = objDomain.Get("defaultNamingContext")
Set objDomain = Nothing
Set con = Server.CreateObject("ADODB.Connection")
con.provider ="ADsDSOObject"
con.open "Active Directory Provider"
Set Com = CreateObject("ADODB.Command")
Set Com.ActiveConnection = con
Com.CommandText ="select name,telephonenumber,mail FROM 'GC://"+objADsPath+"' where sAMAccountname='"+strUsername+"'"
Set rs = Com.Execute
name=rs("name")
telephonenumber=rs("telephonenumber")
mail=rs("mail")
rs.Close
con.Close
Set rs = Nothing
Set con = Nothing
response.write name&"<br>"
response.write telephonenumber&"<br>"
response.write mail&"<br>"
%>
</body>
</html>
peacecorp (IS/IT--Management)
19 Feb 04 10:39
Thanks alot.  you are very helpful. I want to get u some coffee.  :)

I have a question.
Request.ServerVariables("LOGON_USER")

when using that line, i ran it locally on my computer and it did not pick up any value.  Why is that?
zcolton (IS/IT--Management)
19 Feb 04 10:50
What authentication methods are you using for this web page?
peacecorp (IS/IT--Management)
19 Feb 04 11:07
im not sure.  how could i found out? should i ask my network admin.

this webpage is accessed internally on our intranet
zcolton (IS/IT--Management)
19 Feb 04 11:10
To populate the server variable "LOGON_USER" anonymous access must be removed. It will only work with basic or intergrated windows authentication.
peacecorp (IS/IT--Management)
19 Feb 04 11:14
Is that why you used auth_user? Since it is able to retrieve the user regardless of anonymous access?
zcolton (IS/IT--Management)
19 Feb 04 11:29
Actually auth_user and logon_user act the same way
peacecorp (IS/IT--Management)
19 Feb 04 11:54
Whats the difference between GC and LDAP?

zcolton (IS/IT--Management)
19 Feb 04 12:30
GC is global catalog
searching the GC is faster that LDAP
pReverend (Programmer)
19 Feb 04 13:05
How secure is this method?  I'm using it for an intranet site that might have a need to move through an approval proceedure and I want to make sure it will be secure.  Is there any way to spoof that server variable.  I can't see how...but I want to check.

Thanks
zcolton (IS/IT--Management)
19 Feb 04 13:11
I believe GC access is read only
pReverend (Programmer)
19 Feb 04 19:04
no...I meant is there any way to spoof the server variables...like "auth_user".  I can't hink of any but I'm not an expert.
zcolton (IS/IT--Management)
20 Feb 04 8:32
What do you mean by "spoof the server variables"?
pReverend (Programmer)
20 Feb 04 12:56
I mean is there any way to send false identification to the server so that the server variable "auth_user" is read as another account?
peacecorp (IS/IT--Management)
23 Feb 04 11:26
Zcolton i have a question.

the code that u gave me if i try to run locally on my computer it says

Error Type:
Provider (0x80040E37)
Table does not exist.

what does this mean? im such a newb
zcolton (IS/IT--Management)
23 Feb 04 11:39
pReverend: I am not sure if that can be done.

peacecorp: These pages need to run on a web server. If you have a web server running on your machine and the machine is a domain member it should work.
peacecorp (IS/IT--Management)
24 Feb 04 9:53
i turned off anonymous authentication and checked on intergrated windows authentication.

i still get a error

Error Type:
Provider (0x80040E37)
Table does not exist.

its erroring on the line:
Set rs = Com.Execute
zcolton (IS/IT--Management)
24 Feb 04 10:05
Try this code first:
If your webserver can access your domain this should show you your domain name

CODE


<%@ Language=VBScript %>
<%
Option Explicit
Dim objADsPath,objDomain
%>
<html>
<head>
</head>
<body>
<%
Set objDomain = GetObject ("GC://RootDSE")
objADsPath = objDomain.Get("defaultNamingContext")
Set objDomain = Nothing
Response.Write objADsPath & "<BR>"
%>
</body>
</html>
peacecorp (IS/IT--Management)
24 Feb 04 10:11
domain works, and username sorta i did a test on it and that is fine. i even outputed teh com.CommandText and it looks flawless.  just when it tries to do execute it doesnt work

sample output of ur original code minus the com.execute and on.  i also changed it to output the commandText

output
---------------------------------------------
NTam
DC=sandc,DC=ws
select name,telephonenumber,mail from 'GC://DC=sandc,DC=ws' where sAMAccountname='NTam'
zcolton (IS/IT--Management)
24 Feb 04 10:39
Are you running the latest version of MDAC on the server?
peacecorp (IS/IT--Management)
24 Feb 04 10:42
what version would i need to have? and how can i check?
zcolton (IS/IT--Management)
24 Feb 04 11:08
I found your problem. Turn off Integergrated Windows authentication and try basic. Let me know if that works.
zcolton (IS/IT--Management)
24 Feb 04 11:21
OR --- You will need to hard code a domain account and password that has access to active directory:
That is what I usually do. I created a very low level domain account that as no access real network access except reading the active directory. If you plan on using this web pages in an intranet, with domain users logged in the access theses pages, that might be the easiest method for you.

CODE


<%@ Language=VBScript %>
<%
Option Explicit
Dim strUsername,con,rs,Com,objADsPath,objDomain,name,telephonenumber,mail
%>
<html>
<head>
</head>
<body>
<%
strUsername = Request.ServerVariables("auth_user")
strUserName = Right(strUserName, Len(strUserName) - InStrRev(strUserName, "\"))
Set objDomain = GetObject ("GC://rootDSE")
objADsPath = objDomain.Get("defaultNamingContext")
Set objDomain = Nothing
Set con = Server.CreateObject("ADODB.Connection")
con.provider ="ADsDSOObject"
con.Properties("User ID") = "some user name"
con.Properties("Password") = "the password"
con.Properties("Encrypt Password") = False
con.open "Active Directory Provider"
Set Com = CreateObject("ADODB.Command")
Set Com.ActiveConnection = con
Com.CommandText ="select name,telephonenumber,mail FROM 'GC://"+objADsPath+"' where sAMAccountname='"+strUsername+"'"
Set rs = Com.Execute
name=rs("name")
telephonenumber=rs("telephonenumber")
mail=rs("mail")
rs.Close
con.Close
Set rs = Nothing
Set con = Nothing
response.write name&"<br>"
response.write telephonenumber&"<br>"
response.write mail&"<br>"
%>
</body>
</html>
peacecorp (IS/IT--Management)
24 Feb 04 11:26
ok im gonna work with these 2 possible solutions and i will tell u how it goes later today thanks
peacecorp (IS/IT--Management)
24 Feb 04 13:58
Hey,

ok i tested things in steps:
STEP 1:  WORKS fine
<%@ Language=VBScript %>
<%
Option Explicit
Dim strUsername,con,rs,Com,objADsPath,objDomain,name,telephonenumber,mail
%>
<html>
<head>
</head>
<body>
<%
strUsername = Request.ServerVariables("auth_user")
response.write strUsername&"<br>"
strUserName = Right(strUserName, Len(strUserName) - InStrRev(strUserName, "\"))
Set objDomain = GetObject ("GC://rootDSE")
objADsPath = objDomain.Get("defaultNamingContext")
Set objDomain = Nothing
Set con = Server.CreateObject("ADODB.Connection")
con.provider ="ADsDSOObject"
con.open "Active Directory Provider"
Set Com = CreateObject("ADODB.Command")
Set Com.ActiveConnection = con

response.write strUsername&"<br>"
response.write objADsPath&"<br>"

Com.CommandText ="select name,telephonenumber,mail FROM 'GC://"+objADsPath+"'

where sAMAccountname='"+strUsername+"'"


%>
</body>
</html>

STEP 2: i get a 500 http error

<%@ Language=VBScript %>
<%
Option Explicit
Dim strUsername,con,rs,Com,objADsPath,objDomain,name,telephonenumber,mail,WshShell
%>
<html>
<head>
</head>
<body>
<%

strUsername = Request.ServerVariables("auth_user")
response.write strUsername&"<br>"
strUserName = Right(strUserName, Len(strUserName) - InStrRev(strUserName, "\"))
Set objDomain = GetObject ("GC://rootDSE")
objADsPath = objDomain.Get("defaultNamingContext")
Set objDomain = Nothing
Set con = Server.CreateObject("ADODB.Connection")
con.provider ="ADsDSOObject"
con.open "Active Directory Provider"
Set Com = CreateObject("ADODB.Command")
Com.ActiveConnection = con
Set rs = Server.CreateObject("ADODB.Recordset")


response.write strUsername&"<br>"
response.write objADsPath&"<br>"

Com.CommandText ="select name,telephonenumber,mail from 'GC://"+objADsPath+"'where sAMAccountname='"+strUsername+"'"

response.write Com.CommandText&"<br>"


Set rs = Com.Execute
name=rs("name")
telephonenumber=rs("telephonenumber")
mail=rs("mail")
rs.Close
con.Close
Set rs = Nothing
Set con = Nothing

response.write name&"<br>"
response.write telephonenumber&"<br>"
response.write mail&"<br>"

%>
</body>
</html>


Is it possible that the com.CommandText = "..."
is some how not correct?
zcolton (IS/IT--Management)
24 Feb 04 14:05
There should be a space before the "WHERE" in the Com.Commandtext
peacecorp (IS/IT--Management)
24 Feb 04 15:12
i tried it again....but it still gives teh same error.

Is it possible that the com.CommandText = "..."
is some how not correct?

like my domain is correct i asked my network admin and it contains all teh correct data could it be the values its trying to get like name, telephonenumber, mail?
zcolton (IS/IT--Management)
24 Feb 04 15:17
To get a more specific error message turn off friendly error messages in IE. It's under the advanced tab. That might give us better insight as to why it is not working.
peacecorp (IS/IT--Management)
24 Feb 04 15:39
this is my error message:

TORONTO\NTam
NTam
DC=sandc,DC=ws
select name,telephonenumber,mail from 'GC://DC=Toronto,DC=sandc,DC=ws' where sAMAccountname='NTam'

Provider error '80040e37'

Table does not exist.

/helpdesk/test2.asp, line 34


the first 4 lines are just output....i had to hardcode part of the domain name
zcolton (IS/IT--Management)
24 Feb 04 16:41
What did you set the security as?
peacecorp (IS/IT--Management)
25 Feb 04 9:38
currently at custom level at medium default levels
zcolton (IS/IT--Management)
25 Feb 04 17:01
I meant on the web server
peacecorp (IS/IT--Management)
26 Feb 04 7:59
haha sorry.

i took off anonymous.
i have integrated windows authentication on.

peacecorp (IS/IT--Management)
27 Feb 04 11:52
question...if i do a

LDAP://sandc.ws in a web browser

it asks me to enter name or email to search in teh directory...i enter ny email and it says for me to check my connection.

is this normal?

im still trying to figure out why this thing donesnt work....
peacecorp (IS/IT--Management)
27 Feb 04 12:29
damn k i guess that last message was uselless since it has ntohing to do with it.....

peacecorp (IS/IT--Management)
27 Feb 04 14:28
would this code ahve a problem if there are 3 LDAP servers on our network?
peacecorp (IS/IT--Management)
1 Mar 04 13:28
ok i got it to work...here is my code
i had to use basic authentication.
is there a way so that the user doesnt have to keep entering thier user name and login?

<%@ Language=VBScript %>
<%
Option Explicit
Dim strUsername,con,rs,Com,objADsPath,objDomain,name,telephonenumber,mail,WshShell
%>
<html>
<head>
</head>
<body>
<%

strUsername = Request.ServerVariables("auth_user")
response.write strUsername&"<br>"
strUserName = Right(strUserName, Len(strUserName) - InStrRev(strUserName, "\"))
Set objDomain = GetObject ("GC://rootDSE")
objADsPath = objDomain.Get("defaultNamingContext")
Set objDomain = Nothing
Set con = Server.CreateObject("ADODB.Connection")
con.provider ="ADsDSOObject"
con.open "Active Directory Provider"
Set Com = CreateObject("ADODB.Command")
Com.ActiveConnection = con
Set rs = Server.CreateObject("ADODB.Recordset")


response.write strUsername&"<br>"
response.write objADsPath&"<br>"

Com.CommandText ="select name,telephonenumber,mail from

'LDAP://OU=accounts,DC=toronto,"+objADsPath+"' where sAMAccountname='"+strUsername+"'"

response.write Com.CommandText&"<br>"

Set rs = Com.Execute
name=rs("name")
telephonenumber=rs("telephonenumber")
mail=rs("mail")
rs.Close
con.Close
Set rs = Nothing
Set con = Nothing

response.write name&"<br>"
response.write telephonenumber&"<br>"
response.write mail&"<br>"

%>
</body>
</html>

Alvan (Programmer)
2 Mar 04 1:55
pReverend: did you get an answer of your problem, "Unspecified Error" when you include department in your LDAP query?

I got the same problem too. Could you help me?
zcolton (IS/IT--Management)
2 Mar 04 15:13
The only way to make it so that the user is not initially prompted for a username and password is to use intergrated authentication. To successfully use this authentication method much needs to be taken into account. An article explaining some of this is located at:
http://www.serverwatch.com/tutorials/article.php/1478231

I hope this helps
peacecorp (IS/IT--Management)
2 Mar 04 15:17
zcolton

thanks for all your help i learned a few things from this thread.  

unfortunately after reviewing with my coworker and my boss we are not going to be useing the LDAP searches.

Thanks for you time.
Alvan (Programmer)
3 Mar 04 3:48
zcolton,

could you help me, how to view department field using LDAP?
everytime I tried to get department data, I got "Unspecified Error".

here is my script.


<%
sub getXdata(xlogin)
Set cnvt = CreateObject("ADs.ArrayConvert")
set con=createobject("ADODB.Connection")
set rsLDAP = Server.CreateObject("ADODB.RecordSet")

con.provider="ADSDSOObject"
con.open

strSQL="<LDAP://dc=corp,dc=xxxxxxxxx,dc=com>;" &_
       "(&(objectClass=user)(sAMAccountName="&xlogin &"));" &_
       "mobile,mail,name,title,physicalDeliveryOfficeName,l,co,department;subtree"
        
rsldap.open strSQL,con,0,1,&H0001

while not rsldap.eof
For intLoop = 0 To rsldap.Fields.Count - 1
    if rsLDAP(intLoop).type=12 and not isnull(rsLDAP(intLoop).value) then
        cnvtvalue=cnvt.CStrArray(rsldap(intLoop).value)
        for each itemvalue in cnvtvalue
            select case intLoop
            case 0    xHP=itemvalue
            case 1    xmail=itemvalue
            case 2    xname=itemvalue
            case 3    xpos=itemvalue
            case 4    xloc=itemvalue
            case 5    xdept=itemvalue
            end select
        next
    else
        select case intLoop
        case 0    xHP=rsldap(intLoop).value
        case 1    xmail=rsldap(intLoop).value
        case 2    xname=rsldap(intLoop).value
        case 3    xpos=rsldap(intLoop).value
        case 4    xloc=rsldap(intLoop).value
        case 5    xdept=rsldap(intLoop).value
        end select
    end if
next    
rsldap.movenext
wend

rsldap.close
con.close
end sub
%>
zcolton (IS/IT--Management)
3 Mar 04 6:02
Instead of objectClass=user try objectCategory=person but I don't think it will make a differnece. I have noticed that some people have been getting errors retrieving the department field as if it was a security problem even though other fields can be retrieved. I have never ran into the problem.
Alvan (Programmer)
3 Mar 04 21:54
Zcolton,

Thanks your response. You are right, this is security problem. After I changed setting of Application protection of IIS to "Low (IIS Process)". The problem is solved.

Thanks man.
CoolNutz (MIS)
12 Mar 04 12:28
ZColton,

Need your expertise again...   I'm pulling user information from ADS with no problem, but 1 thing I need to pull is the manager field, now thats simple, problem is im getting the full DN for the manager field, when all I want is the givenName and sn.  I get OU=...,CN=..., and so forth, I figured a second query but that doesnt seem to be working for me.  Any thoughts?  

Thanks
CN
HisMightiness (Programmer)
17 Mar 04 14:16
zcolton, first of all I want to express how impressed I am with you helping so many people.  I have frequented many forums in the past year, but I have never seen anyone as helpful are you are in this one thread alone.

As with many of the previous Posters, I am new to this portion of ASP.  Anyway, what exactly needs to be done to your phonebook files in order to allow them to work like the NJ school example in one of the posts above?  One of your posts mention that nothing needs to be done now because it is dynamically done for us.  However, when I have loaded your files into my directory, nothing happens.  I get no errors, and all of the pages simply display the default message at the top of the screen.
HisMightiness (Programmer)
17 Mar 04 14:18
I am sorry.  I forgot to add the basics.  I created a director on my Win2kAdv Web Server.  I checked basic authentication instead of windows integrated.  I also had my Admin make sure that my anonymous account has the read-only access needed (he thinks it is done right anyway).  I have not altered your code in anyway.  We are running Active Directory.  What else do you need to know?
zcolton (IS/IT--Management)
17 Mar 04 21:03
HisMightiness,
Is you IIS server internet or intranet? - Is there anyway I can see the exact output you are getting?
A few comments -
Do you have the department field populated on your accounts?
Is your IIS server a domain member or controler?
Either go with Basic Authentication or anonymous.
For testing purposes: first set to basic, when it prompts for username and password, type in your domain username and password. See what happens. Then try using the username and password of the other domain account - the one that will be used as the anonymous account.

------------------------------------------------------------
CoolNutz,
I have not yet had the chance to take a look at your problem. I will get back to you. It's a bit busy around the office. I'm the only netadmin, 9 Win2k Servers, 1600 win98SE workstations, and I am migrating all 98 to XP this summer for next school year. I have been busy designing the entire AD tree fully configured with GPOs (and of course any and all software deployed will be done through GPO's only. - that's a lot of custom msi's for me to create - but that would be a different thread.)
fredb23 (Programmer)
18 Mar 04 4:58
Hello people,
I've done a simple asp identification form that check if a user exist against Active directory.
It takes username and password from the form then submit an sql query like this :
strSQL = "SELECT cn FROM 'GC://"+domainName+"' WHERE objectCategory='person' AND sAMAccountname ='"+userName+"' "
It works fine and return the complete name of the user.
Question: how can I know what group this user is a member of ?? (wich directory in the domain is he in)
What should be the sql ??
Thanks a lot for your time.
zcolton (IS/IT--Management)
18 Mar 04 8:17
fredb32,
group membership and the ou that the user is in are two completely different things.
Are you looking to get one of these or both?
CoolNutz (MIS)
18 Mar 04 8:20
Hey Z,

Anytime you get a chance is fine. Does seem like you got lots to do.  I do appreciate the help though!

Thanks
CN
zcolton (IS/IT--Management)
18 Mar 04 8:38
CoolNutz,
What code are you using to retrieve manager?
CoolNutz (MIS)
18 Mar 04 8:44
Z,

Im just adding the manager to the attributes it looks up on the user.

usrAttributes = "givenName,sn,manager"

CN
zcolton (IS/IT--Management)
18 Mar 04 9:51
CoolNutz,
All done:

CODE

Set objDomain = GetObject ("GC://rootDSE")
objADsPath = objDomain.Get("defaultNamingContext")
Set objDomain = Nothing
Set con = Server.CreateObject("ADODB.Connection")
con.provider ="ADsDSOObject"
con.open "Active Directory Provider"
Set Com = CreateObject("ADODB.Command")
Set Com.ActiveConnection = con
Com.CommandText ="select manager FROM 'GC://"+objADsPath+"' where sAMAccountname='"+strUsername+"'"
Set rs = Com.Execute
manager=rs("manager")
rs.Close
managercn=(split((split(manager,",OU="))(0),"="))(1)
managercn=replace(managercn,"\","")
Com.CommandText="select sn,givenName FROM 'GC://"+objADsPath+"' where name='"+managercn+"'"
Set rs = Com.Execute
sn=rs("sn")
givenname=rs("givenName")
rs.Close
con.Close
Set rs = Nothing
Set con = Nothing
zcolton (IS/IT--Management)
18 Mar 04 9:59
CoolNutz,
change:

CODE

managercn=(split((split(manager,",OU="))(0),"="))(1)
to:

CODE

managercn =Left((split(manager,"="))(1),(Len((split(manager,"="))(1))-3))
CoolNutz (MIS)
18 Mar 04 10:18
Z,

Once again you have come through!  thanks a bunch!
I'll let you know how it goes.

CN
CoolNutz (MIS)
18 Mar 04 10:51
Z,  

I tried to bring in your code into my code...  guess i must have screwed up some where.  I keep getting this error

Microsoft VBScript runtime error '800a01a8'
Object required: ''
/forms/formshome.asp, line 39

Here is my code....

user = Request.ServerVariables("Auth_User")
Set RootDSE = GetObject("LDAP://RootDSE")
DomainADsPath = RootDSE.Get("defaultNamingContext")
Set RootDSE = Nothing
Set Con = Server.CreateObject("ADODB.Connection")
Con.Provider = "ADsDSOObject"
Con.Open "ADProvider"
Set Cmd = Server.CreateObject("ADODB.Command")
Set Cmd.ActiveConnection = Con

usrAttributes = "givenName,sn,manager"

usrADOQuery = "<LDAP://" & DomainADsPath & ">;(&(objectCategory=person)(objectClass=*)(name=" & user & "));" + usrAttributes + ";subtree"
Cmd.CommandText = usrADOQuery

Set rs = Cmd.Execute
loginame = rs.Fields("givenName") & " " & rs.Fields("sn")
Session("loginame")=loginame
manager=rs("manager")
rs.Close

managercn =Left((split(manager,"="))(1),(Len((split(manager,"="))(1))-3))
managercn=replace(managercn,"\","")
--> Line 39 Com.CommandText="select sn,givenName FROM 'GC://"+objADsPath+"' where name='"+managercn+"'"
Set rs = Com.Execute
sn=rs("sn")
givenname=rs("givenName")

rs.Close
Con.Close
Set rs = Nothing
Set Con = Nothing

I know your busy, so when you get a chance, if you have any ideas, please let me know.

Thanks
fredb23 (Programmer)
18 Mar 04 11:27
Anyone's willing to help me ?
please ..
cheers
zcolton (IS/IT--Management)
18 Mar 04 11:34
fredb23,
I did reply to you with a question:

group membership and the ou that the user is in are two completely different things.
Are you looking to get one of these or both?
zcolton (IS/IT--Management)
18 Mar 04 11:39
CoolNutz:

Done:

CODE

<%@ Language=VBScript %>
<%
Option Explicit
Dim user,RootDSE,DomainADsPath,Con,Cmd,usrAttributes,usrADOQuery,rs,loginame,manager,managercn,mgrAttributes,mgrADOQuery,mgrsn,mgrgivenname
%>
<html>
<head>
</head>
<body>
<%
user = Request.ServerVariables("Auth_User")
user = Right(user, Len(user) - InStrRev(user, "\"))
Set RootDSE = GetObject("LDAP://RootDSE")
DomainADsPath = RootDSE.Get("defaultNamingContext")
Set RootDSE = Nothing
Set Con = Server.CreateObject("ADODB.Connection")
Con.Provider = "ADsDSOObject"
Con.Open "ADProvider"
Set Cmd = Server.CreateObject("ADODB.Command")
Set Cmd.ActiveConnection = Con

usrAttributes = "givenName,sn,manager"

usrADOQuery = "<LDAP://" & DomainADsPath & ">;(&(objectCategory=person)(objectClass=*)(sAMAccountname=" & user & "));" + usrAttributes + ";subtree"

Cmd.CommandText = usrADOQuery

Set rs = Cmd.Execute
loginame = rs.Fields("givenName") + " " + rs.Fields("sn")
'Session("loginame")=loginame
manager=rs.Fields("manager")
rs.Close

managercn =Left((split(manager,"="))(1),(Len((split(manager,"="))(1))-3))
managercn=replace(managercn,"\","")

mgrAttributes = "givenName,sn"
mgrADOQuery = "<LDAP://" & DomainADsPath & ">;(&(objectCategory=person)(objectClass=*)(name=" & managercn & "));" + mgrAttributes + ";subtree"

Cmd.CommandText = mgrADOQuery

Set rs = Cmd.Execute
mgrsn=rs.Fields("sn")
mgrgivenname=rs.Fields("givenName")

rs.Close
Con.Close
Set rs = Nothing
Set Con = Nothing

response.write mgrsn&"<br>"
response.write mgrgivenname&"<br>"
%>
</body>
</html>
CoolNutz (MIS)
18 Mar 04 11:44
Z, again PERFECT! thanks.  But just for knowledge or curiousity, what was the problem?

Thanks
CN
zcolton (IS/IT--Management)
18 Mar 04 11:53
I saw a couple of problems:
The small section of script I gave you was written so that the queries are writen in a SQL format. Your queries are being done in a LDAP format. With that there are a few small differences when extracting records, etc.
Plus, in your usrADOQuery line i had to change
(name=" & user & ")
to
(sAMAccountname=" & user & ")
The user variable you have defined is not the LDAP field "name", it is "sAMAccountname"
It is possible the these two values are identical on your setup.
CoolNutz (MIS)
18 Mar 04 11:58
Learn something new everyday.  
Youve been a great help Z.

Thanks!
CN
fredb23 (Programmer)
18 Mar 04 13:00
oops, sorry Zcolton, i did miss your reply ...

yes, its the OU the user is in i'm trying to retrieve.

thanks a lot
zcolton (IS/IT--Management)
18 Mar 04 13:04
fredb23,
the field you want to retrieve is adspath

CODE

strSQL = "SELECT adspath FROM GC://"+domainName+"' WHERE objectCategory='person' AND sAMAccountname ='"+userName+"' "
HisMightiness (Programmer)
18 Mar 04 14:38
The department fields do have something in them.  It is only for the intranet, so I cannot get you to view it.  The server is a member, not controller.  Anonymous is still on by default, but Windows Integrated was checked as well.  I already set that to Basic, so both are checked.  Is it necessary for only one?
zcolton (IS/IT--Management)
18 Mar 04 16:57
HisMightiness,
For testing purposes only use one (basic). Integrated must not be checked. Make those changes and let me know what happens. If it doesn't seem to work, there are a few tests we can do.
fredb23 (Programmer)
19 Mar 04 4:37
Nice one Zcolton ! thanks
Adspath, as the name says, return the full path of the AD user so i get something like :
LDAP://CN=some user name,OU=W2000 XP,OU=computers and users,OU=Informatique,OU=society,DC=some domain,DC=net

I can work with that string to extract the information i need.

Out of curiosity what would be the field for group membership ?

cheers
zcolton (IS/IT--Management)
19 Mar 04 9:29
fredb23,
"memberOf" gives you an array of the groups that a user is in. Each item in the array is the full adspath of each group. The only group not listed is the Primary Group - (usually "Domain Users")
HisMightiness (Programmer)
19 Mar 04 15:12
zcolton,

I tried your suggestion, and I am still getting the same result (no result).  What would be the next step to try?
zcolton (IS/IT--Management)
19 Mar 04 15:16
His,
Try this first:

CODE

<%@ Language=VBScript %>
<%
Option Explicit
Dim objADsPath,objDomain
%>
<html>
<head>
</head>
<body>
<%
Set objDomain = GetObject ("GC://RootDSE")
objADsPath = objDomain.Get("defaultNamingContext")
Set objDomain = Nothing
Response.Write objADsPath & "<BR>"
%>
</body>
</html>

This should display your root adspath. This will first verify that you are connecting to the global catalog.
HisMightiness (Programmer)
19 Mar 04 15:27
zcolton,

It gave me the two DC values.  Do you want me to try plugging them in to your code?
zcolton (IS/IT--Management)
19 Mar 04 19:58
So you can see the active directory. Next step is to query it.

CODE

<%@ Language=VBScript %>
<%
Option Explicit
Dim con,rs,Com,objADsPath,objDomain
%>
<html>
<head>
</head>
<body bgcolor="#CCCCCC">
<%
Set objDomain = GetObject ("GC://RootDSE")
objADsPath = objDomain.Get("defaultNamingContext")
Set objDomain = Nothing
Set con = Server.CreateObject("ADODB.Connection")
con.provider ="ADsDSOObject"
con.open "Active Directory Provider"
Set Com = CreateObject("ADODB.Command")
Set Com.ActiveConnection = con
Com.CommandText ="select department from 'GC://"+objADsPath+"' WHERE department ='*'"
Set rs = Com.Execute

Do While Not rs.EOF Or rs.BOF

Response.Write rs("department") & "<BR>"

rs.MoveNext
Loop
rs.Close

con.Close
Set rs = Nothing
Set con = Nothing
%>
</body>
</html>

This should give you a list of every department value you have configured in your user accounts.
HisMightiness (Programmer)
20 Mar 04 0:13
Wow!  zcolton, it is working now!  You're a genius!  Thanks a lot.  I think I got it from here now...  I appreciate your generosity and help.
Tangoblue (TechnicalUser)
12 Apr 04 14:54
Hi Zcolton!

I'm pretty new with doing web development. I have a main website with a link to the intranet. My boss want me to make that link authenticate through LDAP before letting them anyone in. I have no idea how to start this process. Could you tell me what are the steps that I must do first?
What are the infomation that you need to help me out?

Basically I just want my link to authenticate with LDAP and let the user in.

I currently using ASP and IIS.

Thank for the help in advance.
-Dave
zcolton (IS/IT--Management)
12 Apr 04 19:00
Tangoblue,
The answer to your question is simpler than you think. It will take NO special coding on your part. You have only two steps:
1)Configure the security in IIS of the site you wish to protect to basic authentication only. Remove ALL other selections
2) Motify the NTFS security permisions of those folders to allow only the users and/or groups to read/execute those pages
That's all..
If you are looking for high security, I recommned doing some research of SSL
-zcolton
Tangoblue (TechnicalUser)
10 May 04 16:13
Hi Zcolton,

I hope you are still here. I was assigned onto another project, but now I'm back on this one.  To refresh, I'm still trying to do the above posting. To authenticate a webpage through LDAP. In my last posting, I forgot to mentioned that I want it to authenticate it with Netscape LDAP server.  Could you show me the code on how to connect to the server and authenticate it with the username and password. I'm currently using ASP and IIS.
fandrad (Programmer)
21 May 04 13:08
I cant see the employeeID field. What can be? Please help me!!
My code:

<%@ Language=VBScript %>
<%
Option Explicit
Dim con,rs,Com,objADsPath,objDomain
%>
<html>
<head>
</head>
<body bgcolor="#CCCCCC">
<%
Set objDomain = GetObject ("GC://RootDSE")
objADsPath = objDomain.Get("defaultNamingContext")
Set objDomain = Nothing
Set con = Server.CreateObject("ADODB.Connection")
con.provider ="ADsDSOObject"
con.open "Active Directory Provider"
Set Com = CreateObject("ADODB.Command")
Set Com.ActiveConnection = con
Com.CommandText ="select employeeID from 'GC://"+objADsPath+"' WHERE  sAMAccountname = 'fandrad'"
Set rs = Com.Execute

Do While Not rs.EOF Or rs.BOF

Response.Write rs("employeeID") & "<BR>"

rs.MoveNext
Loop
rs.Close

con.Close
Set rs = Nothing
Set con = Nothing
%>
</body>
</html>
zcolton (IS/IT--Management)
21 May 04 13:30
Tangoblue:
Unfortunatly, I am not familiar with Netscape LDAP.

fandrad,
Try throwing the query at LDAP instead of GC
The global catalog does not have all fields replicated to it. If it turns out that you can get to through LDAP, you can add that field to the GC replication. M$ has a knowledgebase article explaining how to to that. I do not know which one off hand. You should still do a GC search when you put this code into production. GC searches are always faster (assuming the field is available.)

-zcolton
fandrad (Programmer)
21 May 04 15:30
I try with ldap but show a error "Unspecified error" the employeeId field has a value.
I have the following schema:
controller domain : Windows 2003 standar edition
Web server: Windows 2000

I try all and i dont know what could be ...1
CoolNutz (MIS)
27 May 04 16:28
Z,

They got me at it again...  Im sorry to bother you yet again...  If im asking here its that I have already exhausted all my books and google searches.  

Anyways, what I need to do is enumerate a specific distribution list from exchange, any samples/help you may have, I would greatly appreciate.

Thanks again
CN
zcolton (IS/IT--Management)
27 May 04 17:07
CoolNutz,
What kind of distribution list? Is it a personal or system list? If it is a system list:

CODE

<%@ Language=VBScript %>
<%
Option Explicit
Dim objGroup,objMember,groupldap
%>
<html>
<head>
</head>
<body bgcolor="#CCCCCC">
<%
groupldap="cn=groupname,dc=domain,dc=com"
Set objGroup = GetObject ("LDAP://"&groupldap&"")%>
<table border="0" cellpadding="0" bgcolor="#CCCCCC">
<%For each objMember in objGroup.Members%>
<tr><td><b><font face='Tahoma' size='2'><% response.write objMember.Name%></b></td></tr>
<%Next
Set objGroup=nothing%>
</table>
</body>
</html>

Replace the textstring for groupldap to match the distribution list.

Zac
CoolNutz (MIS)
28 May 04 8:13
Zac,

thanks for the quick response.  I just get an error.
It is a System list, actually an exchange 2k3 distribution list.

error '80072032'
/tests/distlist.asp, line 14

Line 14 is the GetObject action.

Here's the code as I have it.

<%@ Language=VBScript %>
<%
Option Explicit
Dim objGroup,objMember,groupldap
%>
<html>
<head>
</head>
<body bgcolor="#CCCCCC">
<%
groupldap="cn=#all_managers,dc=<my domain>,dc=com"
Set objGroup = GetObject ("LDAP://"&groupldap&"")%>
<table border="0" cellpadding="0" bgcolor="#CCCCCC">
<%For each objMember in objGroup.Members%>
<tr><td><b><font face='Tahoma' size='2'><% response.write objMember.Name%></b></td></tr>
<%Next
Set objGroup=nothing%>
</table>
</body>
</html>

And for whatever reason I have never been able to use the Option Explicit

I always get an error with it.

I really appreciate the help!

CN
zcolton (IS/IT--Management)
28 May 04 9:00
CN,
Verify the group. Is there really a '#' in the name? And is the group located in the root? I've tested this page with one of my lists:
cn=staff,cn=users,dc=<domain name>,dc=org

Option Explicit is really a good thing to have. It is quite usefull while debuging. It requires that variables be declared. If you mistype something, an option explicit is not set, it will identify items as variables if it is not recognized.
CoolNutz (MIS)
28 May 04 9:32
Z,

Unfortunately all of our dist lists have #s in front of them, I can only assume its to keep them at the top of the contact lists, not really my dept so i have no say in it.  anyways, no I realized it wasnt in the group and i made the change and heres what i got

groupldap="OU=DISTLIST,CN=testlist,DC=<mydomain>,DC=ORG"

I verified it with one of our M$ specialist back there and it is correct, but im still getting the error. So to test the # theory he made a testlist for me and see how that goes.

As for the Option Explicit command, I would like to use it, but it gives me an error when I hit the page.

Microsoft VBScript compilation error '800a0400'

Expected statement

/tests/distlist.asp, line 5

Option Explicit
^


Ill post another msg in a few mins, when Exchange has had time to process the new list.

Thanks
CN
CoolNutz (MIS)
28 May 04 10:02
Z,

No luck, still geting the error...

Actually the number changed this time.

error '80072030'
/tests/distlist.asp, line 14


Any thoughts?

CoolNutz (MIS)
28 May 04 10:10
Z,

Got it, the problem was in the order of "cn=,dn=,"

Went from

groupldap="OU=DISTLIST,CN=testlist,DC=<mydomain>,DC=ORG"

to

groupldap="CN=testlist,OU=DISTLIST,DC=<mydomain>,DC=ORG"

And that seemed to work.

no for each member it displays

CN=<member name>
CN=<Member name>

...etc


How can i get rid of the CN= for each one?

Thanks
Mike

And the # still doesnt work, but ill find a workaround i guess.


zcolton (IS/IT--Management)
28 May 04 10:23
CN,

CODE

<%@ Language=VBScript %>
<%
Option Explicit
Dim objGroup,objMember,groupldap
%>
<html>
<head>
</head>
<body>
<%
groupldap="cn=groupname,dc=domain,dc=com"
Set objGroup = GetObject ("LDAP://"&groupldap&"")%>
<%For each objMember in objGroup.Members%>
<font face='Tahoma' size='2'><% response.write objMember.cn%><br>
<%Next
Set objGroup=nothing%>
</body>
</html>

To change what is displayed change the .cn to whatever field you want.

Z
CoolNutz (MIS)
28 May 04 11:18
I dont know what to say,   youve come through again!

You should be working for M$, they need someone that knows what they are doing.

Thanks again Z!
zcolton (IS/IT--Management)
28 May 04 11:23
CN,

If I worked for M$, I'ld have to include 300 lines of useless code, charge you lots of money for something that doesn't work and blame it on your system. But then I'll release a sevice pack that fixes the app and breaks everything else you have running.

Z
CoolNutz (MIS)
28 May 04 11:39
LOL

Maybe you should just stay where you are...

HAHAHAHAHAAAA


CN
CoolNutz (MIS)
2 Jun 04 11:43
Z,

Is there a way to do that last query in SQL?

This is what I have, but gives me a Type mismatch or no data at all.

<%
Set con = Server.CreateObject("ADODB.Connection")
con.provider ="ADsDSOObject"
con.open "Active Directory Provider"
Set Com = CreateObject("ADODB.Command")
Set Com.ActiveConnection = con
Com.CommandText ="SELECT Member FROM 'LDAP://CN=\#All_Management,OU=DISTLIST,DC=<my domain>,DC=ORG'"
Set rs = Com.Execute
Do While Not rs.EOF
response.write rs("Member") & ("<BR>")
     rs.MoveNext
     Loop
     rs.Close
con.Close
Set rs = Nothing
Set con = Nothing
%>

Thanks yet again!
CN
zcolton (IS/IT--Management)
2 Jun 04 13:44
CoolNutz,

Q: Is there a way to do that last query in SQL?

A: Nope

Z
CoolNutz (MIS)
2 Jun 04 13:45
well using the LDAP then, is there any way to sort the results?
zcolton (IS/IT--Management)
2 Jun 04 13:50
CoolNutz:

Here's what you will need to do: (I'll get back to you with the code later)
Dump the recordset into an array. Close the recordset. The connection will no longer be needed. Right a function to sort that array. I've done it before. I have to go searching through my old code.

Z
CoolNutz (MIS)
2 Jun 04 13:52
i'll give it a shot, but a sample would be great.

Thanks, greatly appreciated.  
YOUR A PATIENT MAN!

CN
zcolton (IS/IT--Management)
2 Jun 04 15:06
CN,

CODE

<%@ Language=VBScript %>
<%
Option Explicit
response.buffer=true
Dim objGroup,objMember,groupldap,iLoop,tempstr,temparray,sortarray
%>
<html>
<head>
<script language=JScript runat=server>
    function SortVBArray(arrVBArray) {
        return arrVBArray.toArray().sort().join('\b');
    }
</script>
</head>
<body>
<%
groupldap="cn=groupname,dc=domain,dc=com"
Set objGroup = GetObject ("LDAP://"&groupldap&"")
tempstr=""
For each objMember in objGroup.Members
 if tempstr<>"" then
  tempstr=tempstr&"#"
 end if
 tempstr=tempstr&objMember.CN
next
Set objGroup=nothing
temparray=split(tempstr,"#")
SortArray = Split(SortVBArray(temparray), Chr(8))
For iLoop = LBound(SortArray) to UBound(SortArray)
response.write SortArray(iLoop)%><br>
<%next%>
</body>
</html>

Z
HisMightiness (Programmer)
9 Jun 04 13:30
Hey zColton, it is me again.  We are now upgrading our entire intranet to ASP.Net.  Do you have an equivalent example of your phonebook in VB.Net?
zcolton (IS/IT--Management)
14 Jun 04 8:21
HM,
I have nothing written in .NET
HisMightiness (Programmer)
14 Jun 04 8:56
Thanks Z...  I thought it was worth a shot.  :)
AaronA123 (Programmer)
15 Jun 04 16:17
I have looked through this entire thread, but nothing really seems to be geared towards what I need...at least I don't think so.  I am a complete newby at LDAP.

I am trying to connect to LDAP with ASP and I have ALMOST gotten it to work, but not completely.  Can someone take a look at my two samples of code and give me pointers please?

---------------------------------------------
SAMPLE #1
  :: Returns error "Table does not exist."

  Set conn = CreateObject("ADODB.Connection")
  conn.Provider = "ADSDSOObject"
  conn.Open "ADs Provider", _
            "uid="& UserID &",ou=unt,o=people", _
            Password


  str = "SELECT emplid "&_
        "FROM 'LDAP://id.unt.edu:389/o=unt/ou=people' "&_
        "WHERE uid = '"& UserID &"'"
  Set rs = conn.Execute(str)

---------------------------------------------
SAMPLE #2
  :: Returns error "The Active Directory property cannot be found in the cache."

testpath = "LDAP://id.unt.edu:389/uid="& UserID &",ou=people,o=unt"
set usr = GetObject(testpath)

usr.GetInfo

emplid = usr.Get("emplid")
response.write emplid


In sample #2, I know that the field I am requesting is only accessible to an autheticaed user, I just don't know how to pass in the password.

Aaron


Helpful Member!  Summersl (Programmer)
16 Jun 04 9:39
Hi all,

This is some simple code to get your login name & email address from active directory. It took me ages to work out the code. But it uses alot less code than I used to use.

Set objSysInfo = CreateObject("ADSystemInfo")
Set adsUser = GetObject("LDAP://" & objSysInfo.username)
User=adsUser.CN
Email=adsUser.EmailAddress
Response.write User
Response.write Email
almoes (Programmer)
23 Jun 04 11:28
refering to the original question of the post...is it anyway possible to use this object with a standard LDAP server?? I would appreciate if somebody clarifies this for me because I am getting tones of different errors and don't know if its even possible to do. thanxs!
zcolton (IS/IT--Management)
23 Jun 04 11:49
What do you consider a standard LDAP server?
almoes (Programmer)
23 Jun 04 11:51
One that allows ldap queries. Its not Active Directory and not a domain controler, only a win2k paltform running a directory server supporting LDAP queries.
zcolton (IS/IT--Management)
23 Jun 04 13:21
Code for connecting to and quering an ldap server is dependant upon the ldap server. You can use the examples here to give you a roadmap as to what to do, but you will need to do research on the ldap server you are running to make any custom changes to fit your needs.
almoes (Programmer)
24 Jun 04 4:00
So then the ADODB object is not useful?
zcolton (IS/IT--Management)
24 Jun 04 8:00
It may be easier us to provide you with the help you need if you let us know what ldap server you are running.
almoes (Programmer)
24 Jun 04 8:29
Its the DC directory of Cisco CallManager. Its a propietary directory but it supports ldap queries on port 8404. I tried the following pieces of code and got different errors:

code 1:

<%
function exeQuery(queryStr) {

try
    {var oConn = new ActiveXObject("ADODB.Connection");}
  catch(err)
    {Response.write("Err: " + err.number.toString(16) + " desc: " + err.description);}
try
    {oConn.Open (cst);}
  catch(err)
    {Response.write("Err: " + err.number.toString(16) + " desc: " + err.description);}
try
    {oConn.Execute(queryStr);}
  catch(err)
    {Response.write("Err: " + err.number.toString(16) + " desc: " + err.description);}

try
    {oConn.Close();}
  catch(err)
    {Response.write("Err: " + err.number.toString(16) + " desc: " + err.description);}
}

var cst="Provider=ADSDSOObject;User ID=Directory Manager;Password=cisco;"

var str="SELECT cn FROM 'LDAP://172.17.17.115:8404/ou=Users,o=cisco.com' WHERE objectClass='ciscoocUser'";

exeQuery(str);
%>

error 1: table does not exist.

code 2:

<%
SQLStmt = "SELECT cn " & _
          "FROM 'LDAP://172.17.17.115:8404/o=cisco.com/ou=Users' " & _
          "WHERE objectClass='ciscoocUser'"

Set Conn = CreateObject("ADODB.Connection")
Conn.Provider = "ADSDSOObject"

Conn.Open "ADs Provider", _
          "cn=Directory Manager,o=cisco.com", _
          "cisco"

set rs= CreateObject("ADODB.Recordset")
rs.Open SQLStmt, Conn, 3,4,1
output=""

if rs.EOF Or rs.BOF then
    Response.write("empty")
else
    Response.write("non_empty" & rs.RecordCount)
        rs.MoveFirst
        Do
            output= output & rs.Fields("cn").Value & " "
            rs.MoveNext
        Loop While (Not rs.EOF)

end if

If (Conn.Errors.Count > 0) Then
        Response.write ("Error: " & Conn.Errors(1).Description)
    End If

Response.write("output: " & output)

%>

error 2: Unspecified error, line 14

I was trying different combinations and languages :-S

zcolton (IS/IT--Management)
24 Jun 04 8:59
Your best bet to find the answer would be to find a Cisco support/user forum.
almoes (Programmer)
24 Jun 04 9:08
no chance! it supports standard ldap queries, i'm sure its not a problem. Anyway you did not answer my original question, can the ADODB object be used to connecting to any other directory apart from Active Directory?
zcolton (IS/IT--Management)
24 Jun 04 9:19
Sorry,
The ADODB object can be used.
I have no examples for the cisco ldap server though.
almoes (Programmer)
24 Jun 04 9:21
No problem! Ok thats a start, to know it can be used, i can troubleshoot more. I still have another doubt, I was reading around that to run the script with the ADODB object you need to run the ADSI in the machine, is this true?
zcolton (IS/IT--Management)
24 Jun 04 9:24
Yes. I've come across the same info.
almoes (Programmer)
24 Jun 04 9:27
I thought this was the problem, ADSI is not installed on my server :-[ If somebody that reads this and knows for sure that ADSI DOESN'T need to be installed, I would appreciate a post.
CoolNutz (MIS)
24 Jun 04 9:55
Hey Z,  hope all is well, I see almoes is keeping you on your toes...   quick question, trying to figure out if a user is a member of a dist list, this is what I got so far, no errors, but its not giving me the correct results, am i doing it right?

SET mgrVerify = con.Execute("SELECT displayName from 'LDAP://CN=\#ALL_MANAGEMENT,OU=DISTLIST,DC=<mydomain>,DC=ORG' WHERE displayName = '" & formuser & "'")
    If mgrVerify.EOF Then
        Response.write("Not a Manager")
Else
        Response.write ("Manager")
End If

formuser is "displayName" and pulled earlier in the app from and made from a session variable, and if i do a response.write(formuser) it is correct.

Any thoughts?

Thanks
CN
rescueswimmer (MIS)
30 Jul 04 12:48
Would it be possible to use the Insert SQL statement to create Actice Directory objects?
I'd like to do this from an asp page.
thanks!
zcolton (IS/IT--Management)
19 Aug 04 8:51
CN

This code will list all groups a user is a member of:

CODE

<%@ Language=VBScript %>
<%
Option Explicit
Dim strUsername,con,rs,Com,objADsPath,objDomain,membership,group
%>
<html>
<head>
</head>
<body>
<%
strUsername = "<put the user name in here>"
strUserName = Right(strUserName, Len(strUserName) - InStrRev(strUserName, "\"))
Set objDomain = GetObject ("GC://rootDSE")
objADsPath = objDomain.Get("defaultNamingContext")
Set objDomain = Nothing
Set con = Server.CreateObject("ADODB.Connection")
con.provider ="ADsDSOObject"
con.open "Active Directory Provider"
Set Com = CreateObject("ADODB.Command")
Set Com.ActiveConnection = con
Com.CommandText ="select memberof FROM 'GC://"+objADsPath+"' where sAMAccountname='"+strUsername+"'"
Set rs = Com.Execute
membership=rs("memberof")
rs.Close
con.Close
Set rs = Nothing
Set con = Nothing
For each group in membership
 response.write group&"<br>"
Next
%>
</body>
</html>

When you get the array of groups you can just search the array for the membership you are looking for.
Sorry It took so long to respond. I've been quite busy this summer. I run a network for a k-12 school district. My summer consists of complete network/workstation/server overhauls.

Z
zcolton (IS/IT--Management)
19 Aug 04 8:54
rescueswimmer,

LDAP queries are read only.

zcolton
zcolton (IS/IT--Management)
19 Aug 04 8:56
rescueswimmer,

Let me clarify before I get shot down:
LDAP quesries done with the methods of SQL statements are read only.

zcolton
CoolNutz (MIS)
19 Aug 04 9:02
Hey Z,

Thanks for the response.  No problem with the delay.  Wasnt a show stopper.  I'll give that a shot and see what happens.  Good luck with this school year!

CN
HisMightiness (Programmer)
13 Sep 04 10:22
FYI - I have finally come up with a .Net version of your address book.  However, it is not exactly the same.  I can post or e-mail the source code if anyone needs it.  It could at least be a starting point for you since I am quite a novice at accessing Active Directory via .Net.  

Will
http://www.ServiceRank.com/

zcolton (IS/IT--Management)
13 Sep 04 11:32
Please send me a copy. I would love to see what you have.

zcolton@burltwpsch.org
webdevnr (Programmer)
12 Nov 04 9:30
I am looking for the code from FREDB23. Here is his text.
---Hello people,
I've done a simple asp identification form that check if a user exist against Active directory.
It takes username and password from the form then submit an sql query like this :
strSQL = "SELECT cn FROM 'GC://"+domainName+"' WHERE objectCategory='person' AND sAMAccountname ='"+userName+"' "
It works fine and return the complete name of the user.
Question: how can I know what group this user is a member of ?? (wich directory in the domain is he in)
What should be the sql ??
Thanks a lot for your time.---
I have the user form, I am looking for the asp script.
zcolton (IS/IT--Management)
12 Nov 04 9:57
List groups user is member of:

CODE

strSQL="select memberof FROM 'GC://"+objADsPath+"' where sAMAccountname='"+strUsername+"'"
memberof retruns an array, so you will need to grab each item in the array

CODE

membership=recordset("memberof")
For each group in membership
 response.write group&"<br>"
Next

To get Active Directory Path of user:

CODE

strSQL="select AdsPath from 'GC://"+domainName+"' WHERE sAMAccountname ='"+userName+"'"


zcolton
zcolton (IS/IT--Management)
12 Nov 04 9:59
Correction

CODE

strSQL="select memberof FROM 'GC://"+domainName+"' where sAMAccountname='"+strUsername+"'"

Just want to keep the code consistant to yours..

z
webdevnr (Programmer)
12 Nov 04 10:40
Used the following code and looks like I have to correct a security setting in IIS to finish testing.  I get the 'table does not exist' error message.  To recap what I am trying to accomplish.  I want to have a page on our intranet that a user can access based on their active directory group status.  I don't want them to have to enter in their user information all over again.  Am I heading in the right direction with the following code?

<%@ Language=VBScript %>
<%
Option Explicit
Dim strUsername,con,rs,Com,objADsPath,objDomain,membership,group
%>
<html>
<head>
</head>
<body>
<%
strUsername = Request.ServerVariables("auth_user")
strUserName = Right(strUserName, Len(strUserName) - InStrRev(strUserName, "\"))
Set objDomain = GetObject ("GC://rootDSE")
objADsPath = objDomain.Get("defaultNamingContext")
Set objDomain = Nothing
Set con = Server.CreateObject("ADODB.Connection")
con.provider ="ADsDSOObject"
con.open "Active Directory Provider"
Set Com = CreateObject("ADODB.Command")
Set Com.ActiveConnection = con
Com.CommandText ="select memberof FROM 'GC://"+objADsPath+"' where sAMAccountname='"+strUsername+"'"
Set rs = Com.Execute
membership=rs("memberof")
rs.Close
con.Close
Set rs = Nothing
Set con = Nothing
For each group in membership
 response.write group&"<br>"
Next
%>
</body>
</html>
zcolton (IS/IT--Management)
12 Nov 04 11:06
Let me see if I understand:
You want to restrict access based on the security group they are in?
You don't need to code anything in the pages. Set the NTFS file security permissions on the folders/files just like you would on any other network resource. Set the IIS authentication method for the folder to be Windows Integrated (disable all others). When you do this, you will need to make sure that the client's browser can support it and it is enabled.

zcolton
webdevnr (Programmer)
12 Nov 04 11:18
Z,

Not restrict access, I want to redirect them to certain pages based on the group they are in.

Here is the rough case statement.  I would replace admin with different groups.

<%If group="" then
Response.Redirect("invalid.asp")
%>

<%end if
select case lcase(group)
case "admin","admin"
  response.Redirect("admin.asp")
case "admin"
  response.Redirect("page1.asp")
case "admin"
  response.Redirect("page2.asp")
end select%>
zcolton (IS/IT--Management)
12 Nov 04 11:37
OK Now I understand. I have a few pages that does that:
Here is some of my code:

CODE

username=Request.ServerVariables("AUTH_USER")
username=lcase(Right(username, Len(username) - InStrRev(username, "\")))
set ADSysInfo = CreateObject("ADSystemInfo")
set CurrentUser = GetObject("LDAP://" & ADSysInfo.UserName)
if IsArray(CurrentUser.MemberOf) then
 strGroups = LCase(Join(CurrentUser.MemberOf))
 else
  strGroups = LCase(CurrentUser.MemberOf)
end if
set ADSysInfo = nothing
set CurrentUser = nothing

if instr(strGroups, "cn=cst") then
 cstcheck=1
end if
A few things to keep in mind. This is for security group membership, NOT the AD OU they are in. That is two different things all together. Also, you will need to take a look at the names of the security group. For what I have the complete list of groups a user is a member of is join into a string. I then search that string for the name of the security group. You'll need to do some testing to see what this gives you in your environment. But this should get you pointed in the right direction.

zcolton
webdevnr (Programmer)
12 Nov 04 12:25
Would this pull the Organizational Units?

SQLStmt = "Select cn " & _
          "From 'LDAP://LDAPSERVER:10003/o=microsoft/ou=members' " & _
          "Where objectClass='*'"
zcolton (IS/IT--Management)
12 Nov 04 12:38
To get AD Path or user:

CODE

strSQL="select AdsPath FROM 'GC://"+domainName+"' where sAMAccountname='"+strUsername+"'"
1888888 (Programmer)
9 Feb 05 7:36
Does anyone know how to authenticate a user in asp with LDAP, I can connect to the LDAP server and display the users and details but can't figure out how to check if the user is logged in.
zcolton (IS/IT--Management)
9 Feb 05 12:05
1888888,
I'm not clear what you want to do. But here is a simple asp form that does authentication:

CODE

<%@ Language=VBScript %>
<%
on error resume next
fsCompletted = Request.QueryString("f")

If fsCompletted = 1 Then
  ResultHTML = ProcessForm
  else
   ResultHTML = "<br>"
End If

Function ProcessForm
 on error resume next
 const ADS_SECURE_AUTHENTICATION=&h0001
 oUsername=Request.Form("username")
 oPassword=Request.Form("password")
 DN="LDAP://SERVERNAME/cn=users,dc=microsoft,dc=com"
 Set MyNamespace = GetObject("LDAP:")
 Set X = MyNamespace.OpenDSObject(DN, oUserName, oPassword, ADS_SECURE_AUTHENTICATION)
 if err.number=0 then
  HTML = "<p>Authenticated</p>"
  else
  HTML = "<p>Not Authenticated</p>"
 end if
 Set MyNamespace = Nothing
 Set X = Nothing
 ProcessForm=HTML
End Function

PostURL = Request.ServerVariables("SCRIPT_NAME") & "?f=1"

%>  
<HTML>
<HEAD>
</HEAD>
<BODY>
<%=ResultHTML%>
<%
if request.querystring("f")="" then
%>

<form method="post" Action="<%=PostURL%>">
<p>Username : <input type="text" Name="username" Size=10></p>
<p>Password : <input type="password" Name="password" Size=10></p>
<input Name=SubmitButton Value="Authenticate User" Type=submit>
</form>

<%end if%>

</BODY>
</HTML>

You will need to modify the DN string to match your domain.

zcolton
1888888 (Programmer)
10 Feb 05 4:16
Thanks for that zcolton this all works great on my machine but when I gave the link to others it doesn't work.  Any ideas as to why.  Its says it can't authenticate the user, however it works fine for me because iis is on my computer.  Thanks for your help!
zcolton (IS/IT--Management)
10 Feb 05 11:25
1888888

The user name must be entered as DOMAIN\username
Try it and let me know

Z
AS14 (Programmer)
10 Feb 05 21:38
Hi can someone help with writing data to LDAP using ASP.
1888888 (Programmer)
14 Feb 05 4:33
zcolton that worked perfectly thanks for your help!
1888888 (Programmer)
16 Feb 05 4:15
hi zcolton,

The authorisation of the user works for any computer but I still seem to have problems getting the ldap info like name, email from other computers works fine from my because I am hosting IIS, do you have any ideas.  It says it can't find table, I have the anomyous access switched off.

Thanks
18888888
zcolton (IS/IT--Management)
16 Feb 05 10:23
1814,

You can't write data through LDAP. LDAP connections are read only. You will need to use an alternate method. What do you want to be able write?

1888888,

Please give me a full description of what you want to do and I can tell you what you need to change.

zcolton
zcolton (IS/IT--Management)
16 Feb 05 11:19
1888888,

I think I have what you're looking for. No customizations required. It's generic, but it does require that the IIS server is at least a domain member. The usernmae field will accept DOMAIN\username or username@domain.com. If the username and password authenticates, so user info is displayed.

CODE

<%@ Language=VBScript %>
<%
fsCompletted = Request.QueryString("f")

If fsCompletted = 1 Then
  ResultHTML = ProcessForm
  else
   ResultHTML = "<br>"
End If

Function ProcessForm
 on error resume next
 oUsername=Request.Form("username")
 oPassword=Request.Form("password")
 strUserName = Right(oUsername, Len(oUsername) - InStrRev(oUsername, "\"))
 if InStr(strUserName, "@")>0 then
  strUserName = Left(strUserName, InStr(strUserName, "@")-1)
 end if
 Set objDomain = GetObject("GC://rootDSE")
 objADsPath = objDomain.Get("defaultNamingContext")
 Set objDomain = Nothing
 Set con = Server.CreateObject("ADODB.Connection")
 con.provider ="ADsDSOObject"
 con.Properties("User ID") = oUsername
 con.Properties("Password") = oPassword
 con.Properties("Encrypt Password") = False
 con.open "Active Directory Provider"
 Set Com = CreateObject("ADODB.Command")
 Set Com.ActiveConnection = con
 Com.CommandText ="select name,telephonenumber,mail FROM 'GC://"+objADsPath+"' where sAMAccountname='"+strUsername+"'"
 Set rs = Com.Execute
 if err.number=0 then
  HTML = "<p>"+rs("name")+"<br>"+rs("telephonenumber")+"<br>"+rs("mail")+"</p>"
  else
   HTML = "<p>Not Authenticated</p>"
 end if
 rs.Close
 con.Close
 Set rs = Nothing
 Set con = Nothing
 ProcessForm=HTML
End Function

PostURL = Request.ServerVariables("SCRIPT_NAME") & "?f=1"

%>  
<HTML>
<HEAD>
</HEAD>
<BODY>
<%=ResultHTML%>
<%
if request.querystring("f")="" then
%>

<form method="post" Action="<%=PostURL%>">
<p>Username : <input type="text" Name="username" Size=10></p>
<p>Password : <input type="password" Name="password" Size=10></p>
<input Name=SubmitButton Value="Authenticate User" Type=submit>
</form>

<%end if%>

</BODY>
</HTML>

zcolton
1888888 (Programmer)
17 Feb 05 4:00
zcolton

that works really well thanks again for you help!

18888888
AV12 (Programmer)
21 Feb 05 8:10
Hi Can someone help me with converting belwo JAVA code to ASP and Write to LDAP. I really appreciate your help on this.

URL url = new URL("https://" + ldapProps.getProperty("host") + ":" + ldapProps.getProperty("port") + "/CON?app
=ApplicationName&uid=" + ldapProps.getProperty("sess_user") + "&pwd=" + ldapProps.getProperty("sess_pwd") + "&rtype=nvpairs");
                StringBuffer sb = new StringBuffer();
                InputStreamReader isr = new InputStreamReader(url.openStream());
                char[] data = new char[4096];
                int n = 0;
                while((n=isr.read(data, 0, 4096)) != -1)
                        sb.append(data, 0, n);
                isr.close();
                String xmlInput = "<?xml version=\"1.0\"?>\n" + sb.toString();
                DOMParser parser = (DOMParser)Class.forName("org.apache.xerces.parsers.DOMParser").newInstance();
                parser.parse(new InputSource(new StringReader(xmlInput)));
                Document doc = parser.getDocument();
                if(doc.hasChildNodes()){
                        Node top = doc.getFirstChild();
                        String name = top.getNodeName();
                        if(name.equals("CON")){
                                boolean found = false;
                                if(top.hasChildNodes()){
                                        for(Node ch = top.getFirstChild();ch != null; ch = ch.getNextSibling()){
                                                if(ch.getNodeName().equals("sess")){
                                                        sessionId = ch.getFirstChild().getNodeValue();
                                                        found = true;
                                                }
                                                if(ch.getNodeName().equals("reason")){
                                                        if(ch.getFirstChild().getNodeValue().equals("user already in session")
){
                                                                found = true;
                                                                expireSession();
                                                        }
                                                }
                                        }
                                }
                                if(!found)
                                        throw new Exception("Session ID could not be obtained:\n" + xmlInput);
                        }
                }
        }


Adding User to the group in LDAP


{
      String usr = "/AUG?app=%sess%&grp=" + gname + "&uid=" + userid + "&pwd=”+password+”&rtype=nvpairs";

      Object[] st = WeisXMLParser.TagIdValues(usr, "status");
      for(int i=0; i<st.length; i++){
        System.out.println((new java.util.Date()).toString() + " " + (String)st[i]);
      }

      if(((String)st[0]).equals("OK")){
        System.out.println((new java.util.Date()).toString() + " successful to get the result ");
        return true;
      }else{
        Object[] reason = WeisXMLParser.TagIdValues(usr, "reason");
        description = (String) reason[0];
        return false;
      }
    }catch(Exception e){
        e.printStackTrace();
        return false;
      }
zcolton (IS/IT--Management)
21 Feb 05 9:22
Avanika,

Wrong forum. Also, LDAP is read-only. You can not write to anything using LDAP.

zcolton
plasma2 (IS/IT--Management)
28 Feb 05 7:17

zcolton, love your work, thanks for a great little tool.

just wonding if you could help me custamise the list.asp page to display all users in the "Department" ( i am guessing that is the only one you need to change).

I still want the letters across the top to allow staff to Drill down. but it would be good to see the full list shen it is selected.


thanks in advance

Scott
zcolton (IS/IT--Management)
1 Mar 05 14:27
plasma2,...

Working on it. I will get back to you when finished.

zcolton
plasma2 (IS/IT--Management)
1 Mar 05 14:37
thanks Heaps

In the last few nights i have been having a little play and come up with

https://portal.scania.com.au/ldap/

how ever it is very messy (i just cut and pasted till it worked)

thanks heaps

Scott
zcolton (IS/IT--Management)
2 Mar 05 14:01
To all:

I've updated some code in my ASP phonebook.
You can now view a list of all users by selecting "*" in the alphabet listing. I also changed the sendmail feature to use CDO instead of JMAIL.

The new zip file containing the entire phonebook is at:
http://www.burltwpsch.org/users/zcolton/tools/phonebook.zip

If there are any other requests please let me know.

zcolton
CityWebGuy (MIS)
4 Mar 05 16:17
zcolton,

I have found all your postings to be every helpful.  I was wondering if you could help me.  I have the following code

SET obSys = CreateObject("ADSystemInfo")
SET adsUser = GetObject("LDAP://" & obSys.username)
FOR EACH group in adsUser.MemberOf
 response.write (group & "<BR>")
NEXT

and it returns a listing of all the groups in the following format.

CN=Domain Users,CN=Users,DC=opc,DC=local

Here is my question is there a way to get LDAP to return just the group names?  Like "Domain Users" instead of the line above?
savvy95 (TechnicalUser)
4 Mar 05 18:08
This Post is JUST what all Network admin should read.  Except I have a problem with zcolton's generic script.  How can I request other information such as description, ou, msExchHomeServerName, and such?  When I run the wonderful script, with modifications, I get a blank(white) page.  Any help would be appreciated.
zcolton (IS/IT--Management)
4 Mar 05 18:37
CityWebGuy,
The easiest way would be to cut off the portions you don't want to use. Rip off the 'CN=' and then split the string by using the commas. You first value in the array is the name only. If you would like I can put the code together for you.

Savvy95,
Please post the modified code so that I can take a look at it.

zcolton
plasma2 (IS/IT--Management)
5 Mar 05 23:07
zcolton,

Thanks for thoses changes IT all works great. I am also trying to do somthing simular to CityWebGuy, using your earlyer posted code, so if you could show us how to change that so it only shows the group names it would be great( code attached bellow.

also would it also be easy to add a button that would give us a list of groups in the system in the list box and show us the group membership in the right? (ie. same as user + deatil)

thanks one again for all your work

Scott

<%@ Language=VBScript %>
<%
Option Explicit
Dim strUsername,con,rs,Com,objADsPath,objDomain,membership,group
%>
<html>
<head>
</head>
<body>
<%
strUsername = request.queryString("user")
strUserName = Right(strUserName, Len(strUserName) - InStrRev(strUserName, "\"))
Set objDomain = GetObject ("GC://rootDSE")
objADsPath = objDomain.Get("defaultNamingContext")
Set objDomain = Nothing
Set con = Server.CreateObject("ADODB.Connection")
con.provider ="ADsDSOObject"
con.open "Active Directory Provider"
Set Com = CreateObject("ADODB.Command")
Set Com.ActiveConnection = con
Com.CommandText ="select memberof FROM 'GC://"+objADsPath+"' where sAMAccountname='"+strUsername+"'"
Set rs = Com.Execute
membership=rs("memberof")
rs.Close
con.Close
Set rs = Nothing
Set con = Nothing
For each group in membership
 response.write group&"<br>"
Next
%>

</body>
</html>
savvy95 (TechnicalUser)
7 Mar 05 8:14
Here's the script that doesn't work.  When I use it a blank (white) page appears with nothing on it.  If I use the original without "description" I get name telephone and email.  All your help is appreciated


<%@ Language=VBScript %>
<%
fsCompletted = Request.QueryString("f")

If fsCompletted = 1 Then
  ResultHTML = ProcessForm
  else
   ResultHTML = "<br>"
End If

Function ProcessForm
 on error resume next
 oUsername=Request.Form("username")
 oPassword=Request.Form("password")
 strUserName = Right(oUsername, Len(oUsername) - InStrRev(oUsername, "\"))
 if InStr(strUserName, "@")>0 then
  strUserName = Left(strUserName, InStr(strUserName, "@")-1)
 end if
 Set objDomain = GetObject("GC://rootDSE")
 objADsPath = objDomain.Get("defaultNamingContext")
 Set objDomain = Nothing
 Set con = Server.CreateObject("ADODB.Connection")
 con.provider ="ADsDSOObject"
 con.Properties("User ID") = oUsername
 con.Properties("Password") = oPassword
 con.Properties("Encrypt Password") = False
 con.open "Active Directory Provider"
 Set Com = CreateObject("ADODB.Command")
 Set Com.ActiveConnection = con
 Com.CommandText ="select name,telephonenumber,mail,description FROM 'GC://"+objADsPath+"' where sAMAccountname='"+strUsername+"'"
 Set rs = Com.Execute
 if err.number=0 then
  HTML = "<p>"+rs("name")+"<br>"+rs("telephonenumber")+"<br>"+rs("mail")+"<br>"+rs("description")+"</p>"
  else
   HTML = "<p>Not Authenticated</p>"
 end if
 rs.Close
 con.Close
 Set rs = Nothing
 Set con = Nothing
 ProcessForm=HTML
End Function

PostURL = Request.ServerVariables("SCRIPT_NAME") & "?f=1"

%>  
<HTML>
<HEAD>
</HEAD>
<BODY>
<%=ResultHTML%>
<%
if request.querystring("f")="" then
%>

<form method="post" Action="<%=PostURL%>">
<p>Username : <input type="text" Name="username" Size=50></p>
<p>Password : <input type="password" Name="password" Size=10></p>
<input Name=SubmitButton Value="Authenticate User" Type=submit>
</form>

<%end if%>

</BODY>
</HTML>
zcolton (IS/IT--Management)
7 Mar 05 10:19
To all of those having problems retrieving the value of "description" when grabbed from user details:

Though it may seem that the feild should just be a simple string it is actually an array. After creating a recordset including description, set a variable equal to the field and use the index 0 to display the value. Example:
(This is not complete code, only an example or usage.)

CODE

Com.CommandText ="select description FROM 'GC://"+objADsPath+"' where sAMAccountname='"+strUsername+"'"
Set rs = Com.Execute
descriptionarray=rs("description")
descriptionstring=description(0)

zcolton
zcolton (IS/IT--Management)
7 Mar 05 10:52
plasma2,

To display group names:

CODE

For each group in membership
 newgroup=split(group,"=")
 response.write left(newgroup(1), len(newgroup(1))-3)&"<br>"
Next

zcolton
CityWebGuy (MIS)
7 Mar 05 10:58
zcolton,

Thanks for the reply.  I was able to split the string into the array and search that array.

I figured I would have to do something like that I just wanted to make sure there was no other way to just pull the name straight out with a LDAP query.

Thanks

savvy95 (TechnicalUser)
7 Mar 05 12:20
I'm sorry guys for bothering you, but I i'd like some help.  Where do I put your wonderful code into the asp page?
zcolton (IS/IT--Management)
7 Mar 05 12:33
savvy95
Which code and which page? Also, here is an asp page that will list all groups in AD. Each will be a hyperlink. Click the link and it will list all users that are members of that group:

CODE

<%@ Language=VBScript %>
<%
response.buffer = true
SUB CloseAll
   rs.close
   set rs=nothing
   con.close
   set con=nothing
END SUB
%>
<html>
<head>
</head>
<body>
<%
groupdsn=request.querystring("group")
if groupdsn="" then
 Set objDomain = GetObject ("GC://rootDSE")
 objADsPath = objDomain.Get("defaultNamingContext")
 Set objDomain = Nothing
 Set con = Server.CreateObject("ADODB.Connection")
 con.provider ="ADsDSOObject"
 con.open "Active Directory Provider"
 Set Com = CreateObject("ADODB.Command")
 Set Com.ActiveConnection = con
 Com.CommandText ="select adspath,name from 'GC://"+objADsPath+"' WHERE objectCategory='Group' ORDER BY name"
 Set rs = Com.Execute
 if rs.EOF then
  Call CloseAll
  response.write "No Groups Found."
  else
   rsarray=rs.getrows
   Call CloseAll
   numrows=ubound(rsarray,2)
   for rowcounter=0 to numrows
    response.write "<a href='"+Request.ServerVariables("SCRIPT_NAME")+"?group="+rsarray(1,rowcounter)+"'>"+rsarray(0,rowcounter)+"</a><br>"
   next
 end if
 else
 set objgroup=GetObject(groupdsn)
 response.write "<b>Members of "+groupdsn+"</b><br>"
 For each objMember in objGroup.Members
  response.write objMember.cn+"<br>"
 Next
 Set objGroup=nothing
end if
%>
</body>
</html>

zcolton
savvy95 (TechnicalUser)
7 Mar 05 12:47
Thank you again, BUT.. it doesn't work for me. I get

Error Type:
Provider (0x80040E37)
Table does not exist.
/UserPortal/groups.asp, line 27

What in the world am I doing wrong?


CityWebGuy (MIS)
7 Mar 05 12:53
savvy95

That seems to me like you are having permission issues accessing the information.  That is the Error I got when I did not have my permission set correctly to access the
GC.

savvy95 (TechnicalUser)
7 Mar 05 13:03
OK. That might be it. I'll take a look.  I'm in the Domain Admins group though.
zcolton (IS/IT--Management)
7 Mar 05 13:10
savvy95,
My last asp page I posted does need to run under the context of a domain user. If you are running these on your web server, be sure that you are not accessing it under the user context of the IUSR_ anonymous account.

zcolton
savvy95 (TechnicalUser)
7 Mar 05 16:07
I found this:

http://www.Planet-Source-Code.com/vb/scripts/ShowCode.asp?txtCodeId=54250&amp;lngWId=1

Now I only need to assign permissions as to what can be created, modified, deleted and constraints.

thanx for your help
plasma2 (IS/IT--Management)
30 Mar 05 8:46
Zcolton,

I am trying to use the otherTelephone field on my page but i keep getting the following error

"Response object error 'ASP 0106 : 80020005'
Type Mismatch
/phone/info.asp, line 0
An unhandled data type was encountered. "

<%@ Language=VBScript %>
<%
Option Explicit
response.buffer = true
Dim con,rs,Com,user,objADsPath,objDomain,objADOU,objRootOU,objothertelephone,newothertelephone
%>
<html>
<head>
<style type="text/css" media="screen, tv, projection"> @import "phonebook.css"; </style>
</head>
<body bgcolor="#DFDFDF" topmargin="0">
<%
user = request.queryString("user")
If user <> "" Then
objRootOU="ou=staff,"
Set objDomain = GetObject ("GC://rootDSE")
objADsPath = objDomain.Get("defaultNamingContext")
Set objDomain = Nothing
Set con = Server.CreateObject("ADODB.Connection")
con.provider ="ADsDSOObject"
con.open "Active Directory Provider"
Set Com = CreateObject("ADODB.Command")
Set Com.ActiveConnection = con
Com.CommandText ="select otherTelephone, name, department, title, mail, wwwhomepage, telephonenumber, mobile, facsimileTelephoneNumber, physicalDeliveryOfficeName, sAMAccountname, company from 'GC://"+objRootOU+objADsPath+"' where sAMAccountname='"+user+"'"
Set rs = Com.Execute

%>
<table border="0" cellpadding="0" bgcolor="#DFDFDF">
<tr><td id="userinfo" colspan="2"><b><% response.write rs("name")%></b> - <% response.write rs("company")%></td></tr>
<tr><td id="userinfo">Title: </td><td><% response.write rs("title")%></tr>
<tr><td id="userinfo">Branch: </td><td><% response.write rs("department")%></tr>
<tr><td id="userinfo">Office: </td><td><% response.write rs("physicalDeliveryOfficeName")%></tr>
<tr><td id="userinfo">E-mail Address: </td><td><A href="mailto:<% response.write rs("mail")%>"><% response.write rs("mail")%></td></tr>
<tr><td id="userinfo">Phone Extension: </td><td><% response.write rs("telephonenumber")%>, <% response.write rs("otherTelephone")%></tr>
<tr><td id="userinfo">Mobile Number: </td><td><% response.write rs("mobile")%></tr>
<tr><td id="userinfo">Fax Number: </td><td><% response.write rs("facsimileTelephoneNumber")%></tr>

</table>

<%
rs.Close
con.Close
Set rs = Nothing
Set con = Nothing
Else%>
<p><br>Click on the name<br>of the person for<br>contact info.</p>
<%End If%>
</body>
</html>



Thanks Heaps
zcolton (IS/IT--Management)
31 Mar 05 10:56
Plasma2,

otherTelephone is an array

CODE

<%@ Language=VBScript %>
<%
response.buffer = true
%>
<html>
<head>
<style type="text/css" media="screen, tv, projection"> @import "phonebook.css"; </style>
</head>
<body bgcolor="#DFDFDF" topmargin="0">
<%
user = request.queryString("user")
If user <> "" Then
objRootOU="ou=staff,"
Set objDomain = GetObject ("GC://rootDSE")
objADsPath = objDomain.Get("defaultNamingContext")
Set objDomain = Nothing
Set con = Server.CreateObject("ADODB.Connection")
con.provider ="ADsDSOObject"
con.open "Active Directory Provider"
Set Com = CreateObject("ADODB.Command")
Set Com.ActiveConnection = con
Com.CommandText ="select otherTelephone, name, department, title, mail, wwwhomepage, telephonenumber, mobile, facsimileTelephoneNumber, physicalDeliveryOfficeName, company from 'GC://"+objRootOU+objADsPath+"' where sAMAccountname='"+user+"'"
Set rs = Com.Execute
otherTelephone=rs("otherTelephone")
name=rs("name")
department=rs("department")
title=rs("title")
mail=rs("mail")
wwwhomepage=rs("wwwhomepage")
telephonenumber=rs("telephonenumber")
mobile=rs("mobile")
facsimileTelephoneNumber=rs("facsimileTelephoneNumber")
physicalDeliveryOfficeName=rs("physicalDeliveryOfficeName")
company=rs("company")
rs.Close
con.Close
Set rs = Nothing
Set con = Nothing
if isarray(otherTelephone) then
 for each strnumber in otherTelephone
  strotherTelephone=","&strotherTelephone&","&strnumber
 next
end if
%>
<table border="0" cellpadding="0" bgcolor="#DFDFDF">
<tr><td id="userinfo" colspan="2"><b><%=name%></b> - <%=company%></td></tr>
<tr><td id="userinfo">Title: </td><td><%=title%></tr>
<tr><td id="userinfo">Branch: </td><td><%=department%></tr>
<tr><td id="userinfo">Office: </td><td><%=physicalDeliveryOfficeName%></tr>
<tr><td id="userinfo">E-mail Address: </td><td><a href="mailto:<%=mail%>"><%=mail%></a></td></tr>
<tr><td id="userinfo">Phone Extension: </td><td><%=telephonenumber%><%=strotherTelephone%></td></tr>
<tr><td id="userinfo">Mobile Number: </td><td><%=mobile%></tr>
<tr><td id="userinfo">Fax Number: </td><td><%=facsimileTelephoneNumber%></tr>
</table>
<%Else%>
<p><br>Click on the name<br>of the person for<br>contact info.</p>
<%End If%>
</body>
</html>
valdeloire (TechnicalUser)
1 Apr 05 11:04
I am looking at doing something similar to your phone book.  I would like to allow my users to search for as specific record either by name or by department using a web form.  Is this possible?
zcolton (IS/IT--Management)
1 Apr 05 19:33
valdeloire

Anything is possible. Give until early next week, and I can have an example ready for you.

zcolton
molnara (Programmer)
10 Apr 05 9:51
Hi!

The code, what i find here, doesn't work, except on my computer (IIS is on my computer):

1  set ADSysInfo = CreateObject("ADSystemInfo")
2  response.write ADSysInfo.UserName
3  set CurrentUser = GetObject("LDAP://" & ADSysInfo.UserName)
4  if IsArray(CurrentUser.MemberOf) then
5   strGroups = LCase(Join(CurrentUser.MemberOf))
6   else
7    strGroups = LCase(CurrentUser.MemberOf)
8  end if
9  response.write strGroups
10 set ADSysInfo = nothing
11 set CurrentUser = nothing
12
13 if instr(strGroups, "cn=cst") then
14  cstcheck=1
15 end if

error on line 3
(0x800050000)

Do anyone know what settings may wrong with my IIS or AD?
Thank in advance!
zcolton (IS/IT--Management)
10 Apr 05 12:49
molnara (and to anyone else that may read this),

The number 1 item that most people over look is the security context in which you run these scripts. For the majority of the scripts that I have written, they must run under the context of a domain user. The anonymous IIS account is NOT a domain user. If you do not disable anonymous access or switch the anonymous account that IIS uses to a domain account, you will always get an access denied error (or in the case of LDAP queries - table not found). So, molnara, under what security context are you running the script?
molnara (Programmer)
11 Apr 05 8:34
Thank you!
It's now clear for me.
valdeloire (TechnicalUser)
12 Apr 05 9:22
zcolton

Any luck in getting a sample together for me?
zcolton (IS/IT--Management)
12 Apr 05 9:36
valdeloire,

Did you want something that is point-n-click or fill-in-the-blank?
valdeloire (TechnicalUser)
12 Apr 05 9:56
zcolton,

I would prefer a fill-in-the-blank type form.  
MQuimby (Programmer)
12 Apr 05 10:51
zcolton -

Your posts have been very insightful and helpful to me.

I hope you can answer a few questions for me. This is for an Intranet site.

1) I had a call into the GC working fine, now suddenly it has stopped working. I''m wondering if someone in another office made changes that might have done this - like applying an SP.

2) The code that was working was working with IIS Integrated Windows security. Now it works, but only if I hard code credentials - which I don't want to do.

3) The code that was working with integration was giving me a lot of data back in arrays - and I had to grab the 1st element. Now, when I pass credentials and get the dat - it is mostly in strings.

4) I'm wondering if I'm hittinga different DC - maybe on another site. Is there a way to find that out?

5) Is there a resource for the Properties and Methods available on the RootDSe and GC objects? (Eg., al ist of fields...)

I am trying to hit a Win2K3 DC and access AD.

Many thanks for any insight and advice.
Curriculum2 (Programmer)
12 Apr 05 16:37
Hello - I've read this excellent thread, and am not able to get any connection to an LDAP server using any of this code. It's apparent that security is an issue but I'd appreciate some help in understanding next steps:

Situation: eDirectory LDAP server which I'd like to get information from via an IIS ASP page.

I can browse the company LDAP server using the Softerra browser which is installed onto the web server.

Swapping in "mit" for my company, Softerra's URL showing which successfully browses is:

ldap://ldap.mit.edu:389/o=mit??base?(objectClass=*)

with "o=mit" entered into the "Base" textbox in the general tab.

For most all code samples, I get an asp 500 error at the line that is :
 Set objGroup=GetObject("ldap:// etc etc.

Can anyone point me to a solution? I"m thinking either:
a.) IUSR_machinename is not being accepted by the LDAP server, or
b.) I'm missing something in IIS setup that would set up this object
c.) the settings that I've seen in the sample code just aren't being matched by my company's situation.

If it's c.), then here's some additional info about the LDAP structure:
In the Softerra browser, under the main LDAP entity I've connected to, I see some ou=, and I'm interested in ou=ELEMENTARY, and within that, ou=BIGSCHOOL (among others) and within that, ou=STAFF (among others) and within that, cn=gbush (for example, among others).

Finally, I need to parse one of the many (about eight) "securityEquals" which has a string like:

cn=Teachers, ou=STAFF, ou=BIGSCHOOL, ou=ELEMENTARY, o=mit

so that I can detect the word "Teachers" for enabling access to the web page (rather than a student or secretary accessing the page).

Thanks for any direction on this.
mooka (MIS)
12 Apr 05 16:58
Wow this is the master LDAP thread!

I would like to add another question / problem that the masters may help with...

The infamous error: Table Does not Exist - With a Twist

I have the following Code (VB Script) used to enumerate the trusted domains...

I can run it no problem, I have other users who are getting the table does not exist...

Here is the script:


strDomain = InputBox("Enter the name of the Domain in Domain.com notation",Title,strDomain)
If InStr(strDomain, ".") = FALSE Then
    MsgBox("The Domain must be the FQDN e.g. Domain.com")
    WScript.Quit
End If

aDomain = Split(strDomain, ".")
strNTDomain = aDomain(0)

strDomainUid = InputBox("Enter a User Account (Domain\UserName)",Title,strNTDomain & "\")


strDomainPwd = InputBox("Enter Password for " & strDomain,Title,strDomainPwd)



GetTrustedDomains strDomain, strDomainUid, strDomainPwd

Sub GetTrustedDomains(strDomain, strDomainUid, strDomainPwd)
On Error Resume Next


Set con = CreateObject("ADODB.Connection")
con.provider = "ADsDSOObject"
con.Properties("User ID") = strDomainUid
con.Properties("Password") = strDomainPwd
con.open "Active Directory Provider"
Set com = CreateObject("ADODB.Command")
Set com.ActiveConnection = con

If Err.Number <> 0 Then
    MsgBox "Error binding to " & strDomain & ". Error is : " & Err.Description
    Exit Sub
Else
    MsgBox "Successfully connected to domain " & strDomain
End If

com.CommandText = "select name FROM 'GC://" & strDomain & "' where objectCategory='trustedDomain'"
Set rs = com.Execute

If Err.Number <> 0 Then
    MsgBox "Error opening connection To " & strDomain & ". Error is : " & Err.Description
    Exit Sub
End If

If Not rs.EOF Then
    Do Until rs.EOF
        wscript.echo "Trusted Domain: " & rs("name")
        rs.MoveNext
    Loop
    MsgBox "Query is functioning properly."
Else
    wscript.echo "No Trusted Domains Discovered."
End If
rs.Close
Set com = Nothing

If Err.Number <> 0 Then
    MsgBox "Error opening connection To " & strDomain & ". Error is : " & Err.Description
    Exit Sub
End If

End sub


For one particular client, this occurrs in their test domain, but not their production domain.

The domain is a Windows 2003 domain. From this thread it seems like the user permissions and MDAC are likely causes.

I know this script works, so I'm trying to troubleshoot why it works for some and not others. I've verified it against both Windows 2000 and Windows 2003 domains.

This is actually for a website, but I put it in VBS for ease of use.

The web service is using Integrated Authentication only, but doesnt really matter since I'm passing my own account information over. The problem seems to occcur for any level of domain permissions (Domain Admins and regular users.)

So if you guys can try this in your own domains to see if it works or not, or any ideas why it would work in some domains and not others, then you will have saved a mans business and will have good fortune for all of your lives.

Any help would be MUCH appreciated.

/John
zcolton (IS/IT--Management)
12 Apr 05 21:50
Everyone pleae hold tight... answers are soon to follow...
MQuimby (Programmer)
13 Apr 05 8:39
Awesome...

THanks..

Upon working on this all day yesterday, I have discovered the follwoing...

If I code to get the Default naming context, it pulls up something like this: DC=AB, DC=company - making my sleect statements:
"SELECT a, b FROM GC:\\DC=AB, DC=company" - which works in another site, but not here. It will work at mt site, but only if I hard code credentials - which I don't want to do.

If I hard code in the GC name like this:
"SELECT a, b FROM GC:\\ServerName" - everytihng works fine.

Obviously I don't want to do the latter....

I think this is indicating a DNS issue in my location - but I'm not a DNS expert, and I don't know where to look. I think I read I need to have SRV records added - does that make sense.

I think in the first case, the code is doing a double-hop to  get to the GC and thus not passing credentials - this is validated by the fact that if I trust my ID and the server to delegate, the first example works without credentials...

I did an NSLOOKUP - and if I read it correctly, it supports my theory.
Rikkimaru (Programmer)
13 Apr 05 16:51
Hello...I just wanted to ressurect this post to ask you all (or anyone else) who has gotten this code working what version of MDAC they use.

The MDAC version can be found here: C:\Program Files\Common Files\System\ADO\MDACReadMe.htm
(this location and file may vary slightly)

Code of this nature works fine on windows XP but gives me errors on Windows 2k Server when I try to display the result-set.

Here are my errors:
Response object error 'ASP 0106 : 80020005'

Type Mismatch

/phonebook/includes/test.asp, line 0

An unhandled data type was encountered




I have a theory that the code will not work unless MDAC is at version 2.7 or above.

So hopefully you all will reply and we will see whether I am right.

Thanks,
Rikki
Curriculum2 (Programmer)
13 Apr 05 17:01
Regarding MDAC version, my IIS server (the machine making the LDAP requests) is running 2.6 on a win2K server, and I'm one of the posts who can't get the code to work. I'll try 2.7.
Curriculum2 (Programmer)
14 Apr 05 2:38
Rikkimaru,
You, my friend, have solved my connection problem. I'm still at the infancy point of getting the data I need from a very hierarchical tree structure, but I'm getting gobs of data back now, so it should just be a matter of setting the query right.

Solution for me: Upgrade a Win2K server running IIS, to MDAC 2.8 (and the readme shows 2.7). It was at 2.6.



Curriculum2 (Programmer)
14 Apr 05 3:51
OK, I'll refine my question now that I'm seeing data:
My query is taking 30 seconds due to the size of the directory and the vagueness of my query.

I'm sending:
[and I've substituted "big" for my organization and some other states for actual values]

SQLStmt = "SELECT cn " & _
          "FROM'LDAP://ldap.big.edu:389/o=big/ou=State' " & _
          "WHERE objectClass='*'

and the LDAP structure is:
o=big
then about 10 ou's including:
ou=Ohio
then about 100 ou's including:
ou=Cleveland
then about 10 ou's including:
ou=STAFF
then about 300 cn's including:
cn=GBush
and within that container, tehre are five strings of
securityEquals, and one of them is of interest, which reads:
cn=Teachers,ou=STAFF,ou=Cleveland,ou=Ohio,o=big

and the fact that the entry has "Teachers" rather than something else is what I'm searching for.

I'll come into the search knowing the value for the cn (GBush) but I won't know that GBush is in Cleveland, let alone Ohio. I'm hoping that there is an obvious way to find GBush without what appears to be a grab of many megabytes of data by the IIS machine rather than the work being done by the LDAP server. Any ideas how to get what I need and get it quicker ?

tnx !
zcolton (IS/IT--Management)
14 Apr 05 16:08
valdeloire,

fill-in-the-blank phonebook

http://www.burltwpsch.org/users/zcolton/tools/pbfitb.zip

For all of the latest posts/questions. I will hopefully have time tonight to sit down and respond to them. I've been quite busy in the office. Sorry for the delay.
MQuimby (Programmer)
14 Apr 05 16:19
Thanks zcolton - I underatand this is not your number one priority.

More info....

I have found there are differences in W2K and W2K3.

In W2K some of the values come over as arrays and I need to access as elements. In W2K3, those same values need to be strings.

Also, W2K3 (possibly due to SP1) is requiring authentication where W2K is not - may have to do with double hop and Kerberos.

And, I think W2K3 does not resolve DNS entires for GC's - may also be due to authentication issues...

Look forward to your advice.

CityWebGuy (MIS)
15 Apr 05 8:29
Hello,

When I return the information from my LDAP query I notice that there is an whenCreated field.  

My question is, Can someone provide an example if it is possible so that I can query to retrive a list of users that were create withing a a given time frame.  Such as BeginDate - EndDate  which would be paramater that I pass into the page

Thanks for any help.
valdeloire (TechnicalUser)
15 Apr 05 9:20
zcolton,

Thanks for taking the time to help me with this.  I have the files and put them on the web server.  

I am getting the following error when I try to pull up the page.  

HTTP 500.100 - Internal Server Error - ASP error
Internet Information Services

Error Type:
Provider (0x80040E37)
Table does not exist.
/phonebook/Default.asp, line 42


Is there some other configuration that I need to do before trying to use this?
valdeloire (TechnicalUser)
15 Apr 05 9:42
zcolton,

Disregard that last post.  I was able to get the web page to work correctly.  

One question for you though.  It appears that all of my users need to be in a single OU to make this work correctly.  I have different OUs set up for different divisions (nested).  When I tried to change the OU in the asp pages to include the domain or an OU that has other OU's defined in it I do not get anything returned.  

Am I correct in this?  If that is the case, I can move all of my users into a single ou.
zcolton (IS/IT--Management)
15 Apr 05 10:46
valdeloire,

In the pages I provided, in the code, there is a variable objRootOU. That variuable defines the starting OU for the queries. The queries will then look in that OU and any other OU nested in it.

To all of the various security questions:
2k or not 2k : The examples I have shown, and the advice I have given apply to Win2k only. Though some info may hold true for Win2k3, I do not have a 2k3 domain do test for functionality. MS has made changes to the security of LDAP and GC when the made 2k3. You may need to refer to MSKB or MSDN for info on the differences.
IIS : Successful LDAP queries seem to reply on two things (other than proper programming) MDAC and user credentials. Step 1 - update the IIS server to latest version of MDAC. I believe 2.8 is the latest. It just may fix some of your issues. Step 2 - verify the user credentials that are being used to query LDAP. Under normal circumstances the IUSR_machine account can NOT query ldap. If anonymous pages are to be used with that account, the username and password for a domain account with atleast read access MUST be hardcoded in the ASP. What you can do (this is what I have done) is to create a very low-privledged domain account for the sole purpose of submitting queries. Change IIS settings to use that account instead of the IUSR account. You would only need to make thius change on the folder which contains the ASP pages. If you do this, verify the NTFS permissions on those files to be sure that the account has read access. For non-anonymous access, you can use Integrated Windows or Basic authentication. To use Integraded a few conditions MUST be true: anonymous access MUST be disabled, the client browser MUST support it and be enabled, and the client is logged in using a domain account. If all of this is true, Integrated works well. If the client end is not true, the security access reverts back to Basic. To verify the user credentials use:

CODE

Response.Write "AUTH_USER = " & Request.ServerVariables("AUTH_USER")
to display the username. If it comes up blank, you are using the IUSR_machine account.
There is a wya to configure Active Directory to allow anonymous queries (MSKB article ID 320528) but I have not tested it, nore would I want to. Changing permissions on Active Directory can be a VERY BAD thing if done incorrectly. I seriously DO NOT RECOMMEND it.
A few other notes when you do your queries:
Querying a GC is faster than LDAP, however, the Global Catalog may not contain all of the fields you are looking for. But that can be easily modified. (MSKB article ID 229662)

I don't know when I will have the time to answer specific questions. I've been extremely busy. I will what I can as time permits.
I hope this clears up most questions out there.
usctrojan (Programmer)
15 Apr 05 13:43
Hi All,
I want to retieve the mail-quata,mail-usage,warning,username and email address of perticular user in MS Exchange server. Uptil now I am able to retrieve only the email address of perticular user. Now I wants to retrieve user's mail quata,mail usage and warning(warning means if perticular user has warning= -10 and mail-quata=60 then when user reaches to mail-usage=50 i want to shoot the warning ...bcz 60-10=50..) I hope you understand my needs of program.  
Here is my code:
/*---------------------------------------------------------*/
Option Explicit
Dim strUsername,strUsernamea,strpassword,con,rs,Com,objADsPath,objDomain

Set objDomain = GetObject ("GC://rootDSE")
objADsPath = objDomain.Get("defaultNamingContext")
Set objDomain = Nothing
Set con = CreateObject("ADODB.Connection")
con.provider ="ADsDSOObject"
'con.Properties("User ID") = "BURLINGTON\"+strUsername
'con.Properties("Password") = strpassword
con.open "Active Directory Provider"
Set Com = CreateObject("ADODB.Command")
Set Com.ActiveConnection = con
Com.CommandText ="select mail FROM 'GC://"+objADsPath+"' where sAMAccountName='vsavalia'"
Set rs = Com.Execute

msgbox rs("mail")
rs.Close
con.Close
Set rs = Nothing
Set con = Nothing
/*-----------------------------------------------------------*/
usctrojan (Programmer)
15 Apr 05 13:51
dfdsfdsf
zcolton (IS/IT--Management)
15 Apr 05 15:09
usctrojan,

You are querying the Global Catalog. Do those attributes exist in your Global Catalog? Try LDAP instead of GC.
usctrojan (Programmer)
15 Apr 05 17:00
Hi,

I tried LDAP instead of GC and it's working fine but can you suggest me how i can retrieve the mail quata and mail quata usage for a given user...

Thanks,
Chintan
kondakindi (IS/IT--Management)
18 Apr 05 3:49
Hi Zcolton,

   I am new to Ldap concept. I need to do a simple authentication. I tried doing it by using the code u gave earlier but i am getting not authenticated even when i pass the correct username and pwd.

 I am hereby pasting the code:
do let me know if i am doing something wrong.....
  
<%@LANGUAGE="VBSCRIPT"%>
<% on error resume next
   fscompleted = request.QueryString("f")
   
   if fscompleted = 1 then
      ResultHTML = ProcessForm
    else
      ResultHTML = "<BR>"
    end if
 
 Function ProcessForm
   on error resume next
   const ADS_SECURE_AUTHENTICATION=&h0001
   ousername=request.form("username")
   opassword=request.Form("password")
   DN="LDAP.NJIT.EDU/ou=people,o=NJIT,c=US"
   SET mynamespace= GetObject("LDAP:")
   set X = mynamespace.OpenDSObject(DN,ousername,opassword,ADS_SECURE_AUTHENTICATION)
    if err.number=0 then
    HTML = "<p>Authenticated</p>"
    else
    HTML = "<p> Not Authenticated </p>"    
    end if
     set mynamespace= Nothing
     set X= Nothing
     ProcessForm=HTML
     end function
     PostURL = Request.ServerVariables("SCRIPT_NAME") & "?f=1"
     %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
</head>

<body>
<%=ResultHTML%>
<%
if request.QueryString("f")="" then
%>
<form method="post" action="<%=PostURL%>">
<p>username : <input type="text" name="username" size=10></p>
<p>Password : <input type="password" name="password" size=10></p>
<input type=submit name=submitbutton value="authenticate">

</form>
<%end if%>
</body>
</html>



thanks

zcolton (IS/IT--Management)
18 Apr 05 11:27
kondakindi,

2 things I noticed:
Try:

CODE

DN="LDAP://LDAP.NJIT.EDU/ou=people,o=NJIT,c=US"
Also, when you put in your username, it must contain the domain ( DOMAIN\username or username@DOMAIN )

zcolton
valdeloire (TechnicalUser)
18 Apr 05 12:42
zcolton,

Thanks for your assistance on the web form. I have it working correctly now.  I have also added a few things that are specific to our active directory that we wanted to have in the look up.  It works great.
kondakindi (IS/IT--Management)
18 Apr 05 14:10
Zcolton,

 I tried both the things but it is still giving me the same result.
kondakindi (IS/IT--Management)
19 Apr 05 15:21
Zcolton,

  i tried the changes u said but the problem persists and the page gives me not authenticated. i tried to figure out what the error is and the error code it gave is -2147016662.

  i searched for this error but was unable to resolve this problem. can u suggest anything?

thanks
zcolton (IS/IT--Management)
19 Apr 05 16:05
kondakindi,

The only thing I can suggest is that the string for the DN is not correct. The string should be:

LDAP://servername.domain.com/dc=domain,dc=com

I don't know what else to tell you.

To anyone else:
Are there any questions waiting for a reply? I've lost track.

zcolton
Atmosfear (MIS)
26 Apr 05 13:39
zcolton & jbigham, thanks for your contributions here. I've used your code a couple weeks ago for a phone directory search. My page simply calls itself to display the listing, so I've only got one file, phonedir.asp.

My question is this; I've got a lot of users in AD in different folders by location and department, etc.

I'm trying to exclude disabled users, but can't seem to get the right variable/property name (i.e. WHERE isuserdisabled="True"). Here's my current line:

          Com.CommandText ="select name,department,telephonenumber,facsimileTelephoneNumber from 'GC://"+objADsPath+"' WHERE objectCategory='User' AND(department = '" & strUserInput & "' OR name = '" & strUserInput & "' OR telephonenumber = '" & strUserInput & "')"

Any ideas would be appreciated!
zcolton (IS/IT--Management)
26 Apr 05 19:06
The link is the MSDN article on the property. The second is a page I wrote that lists disabled users. This should be enough info to get you pointed in the right direction.


http://msdn.microsoft.com/library/default.asp?url=/library/en-us/adsi/adsi/ads_user_flag_enum.asp

CODE

<%@ Language=VBScript %>
<%
Option Explicit
response.buffer = true
Dim con,rs,Com,objADsPath,objDomain,objADOU,intUAC
Const ADS_UF_ACCOUNTDISABLE = 2
%>
<html>
<head>
</head>
<body topmargin="0" leftmargin="0" bgcolor="#CCCCCC">
<%
 Set objDomain = GetObject ("GC://rootDSE")
 objADsPath = objDomain.Get("defaultNamingContext")
 Set objDomain = Nothing
 Set con = Server.CreateObject("ADODB.Connection")
 con.provider ="ADsDSOObject"
 con.open "Active Directory Provider"
 Set Com = CreateObject("ADODB.Command")
 Set Com.ActiveConnection = con
 Com.Properties("Cache Results") = False
 Com.CommandText ="select userAccountControl,name from 'LDAP://"+objADsPath+"' WHERE objectCategory='person'"
 Set rs = Com.Execute
 While not rs.eof
  intUAC=rs.fields("userAccountControl")
  If intUAC AND ADS_UF_ACCOUNTDISABLE Then
    response.write rs.fields("name")&" is disabled.<br>"
  End If
 rs.movenext
Wend
 rs.close
 set rs=nothing
 con.close
 set con=nothing
%>
</body>
</html>
Atmosfear (MIS)
2 May 05 17:07
Well, that doesn't seem to be working either, maybe you can tell me what I'm missing. Here's all the relevant code (I think).




If Request.Form("DisplayData") = "Yes" Then

 

                          Dim txtInput

                          Dim shader

                          Dim tablecode

 

                          strUserInput = "*" & Request.Form("txtInput") & "*"

                          shader = "header"

                          tablecode = "<Table border=0 style='"'padding:20px 0px 0px 20px'"'>"

 

 

                        groupdsn=request.querystring("group")

                        If groupdsn="" then

                          Set objDomain = GetObject ("GC://rootDSE")

                          objADsPath = objDomain.Get("defaultNamingContext")

                          Set objDomain = Nothing

                          Set con = Server.CreateObject("ADODB.Connection")

                          con.provider ="ADsDSOObject"

                          con.Properties("User ID") = "dcc\xxxxxxxx"

                          con.Properties("Password") = "xxxxxx"

                          con.Properties("Encrypt Password") = False

                          con.open "Active Directory Provider"

                          Set Com = CreateObject("ADODB.Command")

                          Set Com.ActiveConnection = con

'                          Com.CommandText ="select name,department,telephonenumber,facsimileTelephoneNumber from 'GC://"+objADsPath+"' WHERE objectCategory='User' AND telephonenumber='' AND(department = '" & strUserInput & "' OR name = '" & strUserInput & "' OR telephonenumber = '" & strUserInput & "')"

          Com.CommantText ="select userAccountControl,name from 'LDAP://"+objADsPath+"' Where objectCategory='person'"

          Set rs = Com.Execute

 

 

                          shader = "blue"

 

                          If rs.EOF then

                            Call CloseAll

                            response.write "No Results Found."

                            intUAC=rs.fields("userAccountControl")

                          If intUAC AND ADS_UF_ACCOUNTDISABLE then

 

                        Response.Write tablecode

                                Response.Write "<tr>"

                                  Response.Write "<td width=155 bgcolor=EAEAEA>"

                                    Response.Write "<strong>Name</strong>"

                                  Response.Write "</td>"

                                  Response.Write "<td width=160 bgcolor=EAEAEA>"

                                    Response.Write "<strong>Voice</strong>"

Atmosfear (MIS)
2 May 05 17:12
I can't see an edit feature, and my code looks a bit difficult to read, so I appologize, I should've previewed.

Also, thanks for your response ZColton.

Here's the error I get when I try it with your com.commandtext.

Microsoft VBScript runtim error '800a01b6'

Object doesn't support this property or method: 'CommandText'

/dir/phonedir.asp

Thanks again!
CityWebGuy (MIS)
3 May 05 16:38
zcolton - I need your help.

Here is our problem. We have 2 different domains.  Domain1 and Domain2 where Domain2 is under Domain1 but there is an Trust between the two.  

Here is the code
SET obSys = CreateObject("ADSystemInfo")
SET adsUser = GetObject("LDAP://" & obSys.username)

This is running on a Web Server that is also set as an DC in Domain1 also I am running Intergrated Authentication on the Web Server.     

When an user from Domain1 accesses the page it works.  When an user from Domain2 accesses the page it does not work they are getting Error Number -2147016672.

Do you have any insite to what kind of Group Policy setting or anything that I need to check as what is causing this to occur?

PS.  I know this is possible because it worked a few weeks again until our network Admin started playing with GP.

Thanks for any help.

City Web Guy.

chriscak (TechnicalUser)
4 May 05 6:36
Hi,

Anyone know how it could be that the following script runs fine on our (win2k) webserver, but does not run from a client machine (win2k) using the exact same domain admin user.
the site runs under intergrated authentication

CODE

Dim RootDSE
Dim UserContainer
Dim User
Dim RelativePathFromDomainToUserContainer

RelativePathFromDomainToUserContainer = "OU=Helpdesk,OU=Beheerders,OU=CAK-USERS,"

Set RootDSE = GetObject("LDAP://RootDSE")
Set UserContainer = GetObject("LDAP://" & RelativePathFromDomainToUserContainer & RootDSE.Get("DefaultNamingContext"))
UserContainer.Filter = Array("User")

For Each User in Usercontainer
Response.Write User.AdsPath & "<BR>"
Next

on the client machine it gives the following:

-----------
error '80005000'
/adsibook2.asp, line 19
-----------

i'm breaking my head over this :-(
CityWebGuy (MIS)
4 May 05 9:07
Hey Guys Any thought om my last post of LDAP over multiple domains?  We are about to launch this new setup this weekend and I need any thought on how I can get this to work again.

thanks
City Web Guy
CityWebGuy (MIS)
4 May 05 9:45
Here is an update...  

If I switch the server to Basic Authentication instead of Intergrated Authentication it works.  

Does anyone know why this is?  I really need to use Intergrated Authentication.

Thanks for any help
City Web Guy
zcolton (IS/IT--Management)
4 May 05 9:49
I've been quite busy lately... Please hold tight for a response...

zcolton
mooka (MIS)
4 May 05 15:27
CityWebGuy,

I believe the issue you are having is known as Double Impersonation. When only using Integrated Authentication, the IIS server does not know what your password is, because it is a Hash.

I use similar code but providing account information.

Set openDS = GetObject("LDAP:")
Set objADSI = openDS.OpenDSObject("LDAP://" & strDN, strDomainSpecificUserID, strDomainSpecificPassword, ADS_SECURE_AUTHENTICATION)

When the user from the child domain visits, the IIS server is attempting to bind to a DC in another domain. Just because the domain is a parent, doesn't mean it (IIS) has permissions in the child, as the domain is the security boundry.

You may try getting the information from the GC, if the property is replicated. If not, it's easy to replicate whatever you want to the GC.



CityWebGuy (MIS)
4 May 05 22:57
mooka,  Thanks for the reply.

I have decided to go with the GC.  and I am using code simular to this but I am having a little problem....


<%
strUsername = Request.ServerVariables("auth_user")
strUserName = Right(strUserName, Len(strUserName) - InStrRev(strUserName, "\"))
Set objDomain = GetObject ("GC://rootDSE")
objADsPath = objDomain.Get("defaultNamingContext")
Set objDomain = Nothing
Set con = Server.CreateObject("ADODB.Connection")
con.provider ="ADsDSOObject"
con.Properties("User ID") = "[Domain]\adsearchUser"
con.Properties("Password") = "adsearchUserPass"
con.open "Active Directory Provider"
Set Com = CreateObject("ADODB.Command")
Set Com.ActiveConnection = con
Com.CommandText ="select [Fields needed]FROM 'GC://"+objADsPath+"' where sAMAccountname='"+strUsername+"'"
Set rs = Com.Execute
response.write rs([Fields needed])
rs.Close
con.Close
Set rs = Nothing
Set con = Nothing
%>


I can run this on the web server and it works fine.  If I run this on a machine that is calling the web server I get Error: Table does not exist.

I know you have to hard code a username and Password.  I finnally got permission to do this, but this might be a stupid question.  What permissions do I need to set on this user so that I can pull the query with this User from page away from the server? I am running an Windows 2000/2003 domain.

Thanks for any help.

City Web Guy.
zcolton (IS/IT--Management)
5 May 05 8:44
CityWebGuy,

If you are using any type of user authentication (intergrated or basic) you should NOT hardcode user credentials in the web page. Make sure that anonymous access is disabled. This way IIS will run the code under the context of the user accessing the page. Also:
1) an IIS should not be a domain controller, but just a domain member
2) If everything worked before they started "playing" with group policies, check out the group policies. There may be a setting that restricts access accross domains. I'm not sure; that would take a little research.

Chriscak,
Security, security, security. Most of the time, problems access LDAP is a security issue. Things to check: under whos context is the script running; authentication method configured in IIS (anonymous, basic, integrated) Is integrated enabled on the client;

Atmosfear,
Check your code: Com.CommantText should be Com.CommandText
Simple typo

CityWebGuy (MIS)
5 May 05 10:11
Zcolton,

Thanks for the reply we are looking into the security issue.  I know we do not want the web server to be an DC.  But I can get GC to work if the server is a DC so until we fixed the security issue we are going to leave it that way.  

I do have one last question.  I am having a little issue with an GC query.


select cn from 'GC://CN=~Account Closing Request,OU=IAMS,DC=opc,DC=cnbwv,DC=local'


This is the Actual String I am using to access the security group within an OU on our domain.  When I access it, I can pull the name and basic information about the group.  

The question is how would I write a Query using GC to list all the members of this group.

Thanks again for your help!
zcolton (IS/IT--Management)
5 May 05 10:22
I don't think you can get a list of members using an LDAP query. But try something like this:

CODE

groupldap="CN=~Account Closing Request,OU=IAMS,DC=opc,DC=cnbwv,DC=local"
Set objGroup = GetObject ("GC://"&groupldap&"")
For each objMember in objGroup.Members
 ...
 put you code here...
 reponse.write objMember.CN
 ...
next
Set objGroup=nothing

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members!

Back To Forum

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close