Querying Active Directory using VBScript - asp-classic

I want to query Active Directory using VBScript (classic ASP).
How can I accomplish that?

To look at all the members of an OU, try this...
Set objOU = GetObject("LDAP://OU=YourOU,DC=YourDomain,DC=com")
For each objMember in ObjOU ' get all the members'
' do something'
Next
To do a custom search for DNs try this...
set conn = createobject("ADODB.Connection")
Set iAdRootDSE = GetObject("LDAP://RootDSE")
strDefaultNamingContext = iAdRootDSE.Get("defaultNamingContext")
Conn.Provider = "ADsDSOObject"
Conn.Open "ADs Provider"
strQueryDL = "<LDAP://" & strDefaultNamingContext & ">;(&(objectCategory=person)(objectClass=user));distinguishedName,adspath;subtree"
set objCmd = createobject("ADODB.Command")
objCmd.ActiveConnection = Conn
objCmd.Properties("SearchScope") = 2 ' we want to search everything
objCmd.Properties("Page Size") = 500 ' and we want our records in lots of 500
objCmd.CommandText = strQueryDL
Set objRs = objCmd.Execute
While Not objRS.eof
' do something with objRS.Fields("distinguishedName")'
objRS.MoveNext
Wend

I had to query WinAD by oldskool username, this .vbs script prints user accounts.
find by sAMAccountname, use * wildcard
print few attributes from each user object
use AccountType filter its most optimized way of iterating AD user objects
Test script first gets an user object by fully qualified string, its just an example. Second part does actual query by smith* filter.
WinADSearch.vbs
' c:> cscript -nologo script.vbs
' c:> wscript script.vbs
' http://msdn.microsoft.com/en-us/library/d6dw7aeh%28v=vs.85%29.aspx
' WindowsAD queries
' http://www.kouti.com/tables/userattributes.htm
Option Explicit
'On Error Resume Next
Dim StdOut: Set StdOut = WScript.StdOut
Dim objUser
Set objUser = GetObject("LDAP://CN=Firstname Lastname,OU=Internal Users,OU=MyCompany,OU=Boston,OU=Root,DC=REGION1,DC=COM")
println(objUser.givenName & " " & objUser.middleName & " " & objUser.lastName)
println("name=" & objUser.name)
println("displayName=" & objUser.displayName)
println("userPrincipalName=" & objUser.userPrincipalName)
println("sAMAccountName=" & objUser.sAMAccountName)
println("distinguishedName=" & objUser.distinguishedName)
println("")
Dim conn, strQueryDL, strAttrs, objCmd, objRs, idx
set conn = createobject("ADODB.Connection")
conn.Provider = "ADsDSOObject"
conn.Open "ADs Provider"
strAttrs = "sAMAccountName,displayName,distinguishedName" ' get attributes
'strQueryDL = "<LDAP://dc=REGION1,dc=COM>;(& (objectCategory=person) );" & strAttrs & ";SubTree"
'strQueryDL = "<LDAP://dc=REGION1,dc=COM>;(& (objectCategory=person)(objectClass=user) );" & strAttrs & ";SubTree"
'strQueryDL = "<LDAP://dc=REGION1,dc=COM>;(& (objectCategory=person)(objectClass=user)(sAMAccountName=smith*) );" & strAttrs & ";SubTree"
strQueryDL = "<LDAP://dc=REGION1,dc=COM>;(& (samAccountType=805306368)(sAMAccountName=smith*) );" & strAttrs & ";SubTree"
set objCmd = createobject("ADODB.Command")
objCmd.ActiveConnection = Conn
objCmd.Properties("SearchScope") = 2 ' search everything
objCmd.Properties("Page Size") = 100 ' bulk operation
objCmd.CommandText = strQueryDL
println(objCmd.CommandText)
Set objRs = objCmd.Execute
idx=0
do while Not objRS.eof
idx=idx+1
println( objRs.Fields("sAMAccountName") & " / " & objRs.Fields("displayName") & " / " & objRs.Fields("distinguishedName") )
if (idx>5) then exit do
objRS.MoveNext
loop
objRs.Close
Conn.close
set objRs = Nothing
set conn = Nothing
println("end")
'********************************************************************
Sub println(ByVal str)
If (StdOut Is Nothing) Then Exit Sub
StdOut.WriteLine str
End Sub

You want to use Active Directory Service Interfaces (ADSI)
The ADSI Scripting Primer is a good place to start learning and find examples.
(btw, these links refer to Windows 2000, but are valid for subsequent versions of Windows as well).

Related

How to get a list of running processes in Classic ASP? [duplicate]

I need a VBScript that will check if a process is in use by a specific user:
Agent clicks program icon --> batch file calls for progcheck.vbs -->
progcheck.vbs looks to see is "whatever.exe" is running under that user only -->
if program is running under that user then MsgBox "Program running" --> wscript.quit (this needs to terminate out of the batch file)
else --> return to batch file.
I have tried this with tasklist in a batch file and the script works, but takes forever to run for a domain user. Want to do this in vbscript anyway.
*** UPDATED SCRIPT WITH MODS 10/12 *****
OPTION EXPLICIT
DIM strComputer,strProcess, strUserName,wshShell
Set wshShell = WScript.CreateObject( "WScript.Shell" )
strUserName = wshShell.ExpandEnvironmentStrings( "%USERNAME%" )
strComputer = "." '
strProcess = "notepad.exe"
IF isProcessRunning(strComputer,strProcess,strUserName) THEN
If MsgBox ("Notepad needs to be closed.", 1) = 1 then
wscript.Quit(1)
End If
END IF
FUNCTION isProcessRunning(BYVAL strComputer,BYVAL strProcessName,BYVAL strUserName)
DIM objWMIService, strWMIQuery
strWMIQuery = "Select * from Win32_Process where name like '" & strProcessName & "' AND owner like '" &strUserName& "'"
SET objWMIService = GETOBJECT("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
IF objWMIService.ExecQuery(strWMIQuery).Count > 0 THEN
isProcessRunning = TRUE
ELSE
isProcessRunning = FALSE
END If
End Function
Let me know what you think and where I have it wrong. Thanks in advance.
UPDATED CODE v3: review comments for help
OPTION EXPLICIT
DIM strComputer, strProcess, strUserName, wshShell
Set wshShell = WScript.CreateObject( "WScript.Shell" )
strUserName = wshShell.ExpandEnvironmentStrings( "%USERNAME%" )
strComputer = "."
strProcess = "notepad.exe" 'change this to whatever you are trying to detect
IF isProcessRunning(strComputer, strProcess, strUserName) THEN
If MsgBox ("Notepad needs to be closed.", 1) = 1 then
wscript.Quit(1) 'you need to terminate the process if that's your intention before quitting
End If
Else
msgbox ("Process is not running") 'optional for debug, you can remove this
END IF
FUNCTION isProcessRunning(ByRef strComputer, ByRef strProcess, ByRef strUserName)
DIM objWMIService, strWMIQuery, objProcess, strOwner, Response
strWMIQuery = "SELECT * FROM Win32_Process WHERE NAME = '" & strProcess & "'"
SET objWMIService = GETOBJECT("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2").ExecQuery(strWMIQuery)
IF objWMIService.Count > 0 THEN
msgbox "We have at least ONE instance of Notepad"
For Each objProcess in objWMIService
Response = objProcess.GetOwner(strOwner)
If Response <> 0 Then
'we didn't get any owner information - maybe not permitted by current user to ask for it
Wscript.Echo "Could not get owner info for process [" & objProcess.Name & "]" & VBNewLine & "Error: " & Return
Else
Wscript.Echo "Process [" & objProcess.Name & "] is owned by [" & strOwner & "]" 'for debug you can remove it
if strUserName = strOwner Then
msgbox "we have the user who is running notepad"
isProcessRunning = TRUE
Else
'do nothing as you only want to detect the current user running it
isProcessRunning = FALSE
End If
End If
Next
ELSE
msgbox "We have NO instance of Notepad - Username is Irrelevant"
isProcessRunning = FALSE
END If
End Function
You can use the following function:
FUNCTION isProcessRunning(BYVAL strComputer,BYVAL strProcessName)
DIM objWMIService, strWMIQuery
strWMIQuery = "Select * from Win32_Process where name like '" & strProcessName & "'"
SET objWMIService = GETOBJECT("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
IF objWMIService.ExecQuery(strWMIQuery).Count > 0 THEN
isProcessRunning = TRUE
ELSE
isProcessRunning = FALSE
END IF
END FUNCTION
For local computer you would use "."
For the process name, you would use the executable "notepad.exe"
For the rest of the code, you could can use something simple:
OPTION EXPLICIT
DIM strComputer,strProcess
strComputer = "." ' local computer
strProcess = "notepad.exe" 'whatever is the executable
IF isProcessRunning(strComputer,strProcess) THEN
'do something
ELSE
'do something else or nothing
wscript.echo strProcess & " is NOT running on computer '" & strComputer & "'"
END IF
That should do it.
EXTRA
To show every process running, then just run:
Option Explicit
Dim objWMIService, objProcess, colProcess
Dim strComputer, strList
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
Set colProcess = objWMIService.ExecQuery _
("Select * from Win32_Process")
For Each objProcess in colProcess
strList = strList & vbCr & _
objProcess.Name
Next
WSCript.Echo strList
WScript.Quit
in terminal server this function can be very slow, all the GetOwner calls are terrible in performance.
A very fast solution i created is to narrow the query using SessionID of the current user (assuming we want only current user's processes) So I added this code:
SessionID can be obtained this way:
Dim oExec, sOutput, iUserPos, iUserLen, iStatePos, SessionID
dim oShell, userName
Set oShell = CreateObject("Wscript.Shell")
userName = oShell.ExpandEnvironmentStrings("%USERNAME%")
Set oExec = oShell.Exec("query session %username%")
sOutput = LCase(oExec.StdOut.ReadAll)
iUserPos = InStr(sOutput, LCase(userName))
iStatePos = InStr(sOutput, "active")
iUserLen = Len(userName)
SessionID = CInt(Trim(Mid(sOutput, iUserPos+iUserLen, iStatePos-iUserPos-iUserLen)))
Changed the function from the previous post:
Function isProcessRunning(ByRef strComputer, ByRef strProcess, ByRef strUserName, byRef sessionID)
DIM objWMIService, strWMIQuery, objProcess, strOwner, Response
strWMIQuery = "SELECT * FROM Win32_Process WHERE SessionId = " & sessionID & " And NAME = '" & strProcess & "'"
SET objWMIService = GETOBJECT("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2").ExecQuery(strWMIQuery)
IF objWMIService.Count > 0 THEN
'msgbox "We have at least ONE instance of Notepad"
For Each objProcess in objWMIService
Response = objProcess.GetOwner(strOwner)
If Response = 0 Then
'Wscript.Echo "Process [" & objProcess.Name & "] is owned by [" & strOwner & "]" 'for debug you can remove it
if strUserName = strOwner Then
'msgbox "we have the user who is running notepad"
isProcessRunning = TRUE
Else
'do nothing as you only want to detect the current user running it
isProcessRunning = FALSE
End If
'else
'we didn't get any owner information - maybe not permitted by current user to ask for it
'Wscript.Echo "Could not get owner info for process [" & objProcess.Name & "]" & VBNewLine & "Error: " & Return
End If
Next
ELSE
'msgbox "We have NO instance of Notepad - Username is Irrelevant"
isProcessRunning = FALSE
END If
End Function

GetCurrentUserName() is causing crash in MS Access 2010

I am running Windows 7 Professional. I have an MS Access frontend to an MS Access backend. The form that opens at the start of opening the frontend causes the app to crash.
Here is the code:
Private Sub Form_Open(Cancel As Integer)
Dim strMyDir As String
Dim intPos As Integer
Dim rst As dao.Recordset
Dim strSQL As String
Dim rstWhatsNew As dao.Recordset
DoCmd.ShowToolbar "Database", acToolbarNo
DoCmd.ShowToolbar "Toolbox", acToolbarNo
DoCmd.ShowToolbar "Form View", acToolbarNo
If Application.GetOption("ShowWindowsInTaskbar") = -1 Then
Application.SetOption "ShowWindowsInTaskbar", 0
End If
If DLookup("Locked", "luLockOut") <> 0 Then
MsgBox "Database is being worked on. Please try back in a couple minutes.", vbInformation, " "
DoCmd.Quit
Else
strSQL = "Select * From tblLastLogins Where UserName = '" & GetCurrentUserName() & "'"
This is where I have traced the error to: GetCurrentUserName()
Set rst = CurrentDb.OpenRecordset(strSQL)
With rst
If Not .EOF Then
.Edit
strSQL = "Select WhatsNewID From tblWhatsNew Where DateAdded >= #" & !LastLoginDate & "#"
Set rstWhatsNew = CurrentDb.OpenRecordset(strSQL)
While Not rstWhatsNew.EOF
DoCmd.OpenForm "frmWhatsNew", , , , , acDialog, rstWhatsNew!WhatsNewID
rstWhatsNew.MoveNext
Wend
rstWhatsNew.Close
Set rstWhatsNew = Nothing
Else
.AddNew
!UserName = GetCurrentUserName()
End If
!LastLoginDate = Now()
!IsLoggedIn = -1
Me.txtLastLoginID = !LastLoginID
.Update
.Close
End With
Set rst = Nothing
DoCmd.OpenForm "frmPrivacyNote"
Debug.Print Me.txtLastLoginID
End If
I need to track the username, so if GetCurrentUserName() is outdated, what is the current syntax?
Further follow up. I could not find data on Bing for GetCurrentUserName(), for good reason. It is a function within a MOD, so I need to figure out why the MOD is not getting called, or is malfunctioning.
After further delving, I found a Referenced MDB that has another function created by one of our users that is the cause of this error.
This is currently not an issue of MS Access working incorrectly. It is an issue with user created code.
GetCurrentUserName() is not defined by Access, so you should have looked at (and posted) its code.
If you are looking for the Windows user name, use this function:
Public Function GetUserName() As String
' GetUserName = Environ("USERNAME")
' Environ("USERNAME") is easily spoofed, see comment by HansUp
GetUserName = CreateObject("WScript.Network").UserName
End Function
Source
The link below would suggest that
CurrentUser()
is the function
CurrentUser()
Andre, thank you very much for the insight! I found this link:
http://www.codeproject.com/Articles/1422/Getting-User-Information-Using-WSH-and-VBScript
Dim objNet
On Error Resume Next
'In case we fail to create object then display our custom error
Set objNet = CreateObject("WScript.NetWork")
If Err.Number <> 0 Then 'If error occured then display notice
MsgBox "Don't be Shy." & vbCRLF &_
"Do not press ""No"" If your browser warns you."
Document.Location = "UserInfo.html"
'Place the Name of the document.
'It will display again
End If
Dim strInfo
strInfo = "User Name is " & objNet.UserName & vbCrLf & _
"Computer Name is " & objNet.ComputerName & vbCrLf & _
"Domain Name is " & objNet.UserDomain
MsgBox strInfo
Set objNet = Nothing 'Destroy the Object to free the Memory

Classic ASP: Type mismatch: 'GroupCheck'

I have a function named GroupCheck, which is designed to get the logged in users group from AD. It is, however, giving me the following error:
Microsoft VBScript runtime error '800a000d'
Type mismatch: 'GroupCheck'
/ldap.asp, line 67
Line 67 is where I call the function, passing in the Request.ServerVariables("AUTH_USER")
The following function is stored in a file which is included at the top of the page:
<%
function GroupCheck(user)
dim user, ADUser, objCom, objCon, objRS, membership
ADUser = "LDAP://OU=Staff,OU=Users,DC=example,DC=internal"
' Make AD connection and run query'
Set objCon = Server.CreateObject("ADODB.Connection")
objCon.provider ="ADsDSOObject"
objCon.Properties("User ID") = "EXAMPLE\user"
objCon.Properties("Password") = "Test"
objCon.Properties("Encrypt Password") = TRUE
objCon.open "Active Directory Provider"
Set objCom = CreateObject("ADODB.Command")
Set objCom.ActiveConnection = objCon
objCom.CommandText = "SELECT memberOf FROM '" + ADUser + "' where sAMAccountName='*" + 'user + "*' AND UserAccountControl <> 514"
Set objRS = objCom.Execute
Do While Not objRS.EOF Or objRS.BOF
if isNull(objRS.Fields("memberOf").value) then
membership = ""
else
for each item in objRS.Fields("memberOf").value
membership = item + "<br>"
next
end if
if inStr(membership, "UserGroup") then
GroupCheck = 1
else
GroupCheck = 0
end if
objRS.MoveNext
Response.Flush
Loop
'Clean up'
objRS.Close
objCon.Close
Set objRS = Nothing
Set objCon = Nothing
Set objCom = Nothing
end function
%>
I really don't know what the problem is, because /ldap.asp, line 67 is :
Set getMembership(username)
EDIT: My code for ldap.asp is:
getMembership = GroupCheck(Request.ServerVariables("AUTH_USER"))
'This should fetch all the accounts that appears in the "Contact Centre" group
if getMembership = 1 then
'Response.Write "<td><a href='entry.asp?account_name=" & objRS("sAMAccountName") & "'>Edit</a></td>"
elseif objRS("sAMAccountName") = session("username") then
Response.Write "<td><a href='entry.asp?account_name=" & objRs("sAMAccountName") + "'>Edit</a></td>"
else Response.Write "<td></td>"
end if
Response.Write "</tr>" + vbCrL
objRS.MoveNext
Response.Flush
Loop
Response.Write "</table>"
' Clean up
objRS.Close
objCon.Close
Set objRS = Nothing
Set objCon = Nothing
Set objCom = Nothing
%>
So what exactly is in line 67?
Set getMembership(username)
or
[unknown variable] = GroupCheck(Request.ServerVariables("AUTH_USER"))
?
In any case, this is probably the cause of the problem:
objCom.CommandText = "SELECT memberOf FROM '" + ADUser + "' where sAMAccountName='*" + 'user + "*' AND UserAccountControl <> 514"
In VBScript, the + operator is for arithmetic addition. "SELECT memberOf From '" cannot be converted into a number; hence the type mismatch. Probably. (I can't be sure because I don't know how you're calling or including the function.)
Instead, use the proper VBScript concatenation operator, &.
objCom.CommandText = "SELECT memberOf FROM '" & ADUser & "' where sAMAccountName='*" & user & "*' AND UserAccountControl <> 514"
Also, you're potentially shooting yourself in the foot by dimming a variable with the same name as the function argument:
function GroupCheck(user)
dim user, ADUser, objCom, objCon, objRS, membership
'^^^^
It may still work if you do that, but it's just not a good idea.

Classic ASP and MS Access Batch Update

I am using the following code to update an Access Database with Classic Asp:
<%# Language=VBScript %>
<% Option Explicit %>
<%
Response.Buffer = True
'First, we need to get the total number of items that could be updated
Dim iCount
iCount = Request("Count")
'We need to obtain each cost and ID
Dim strstudent, strcourse, strgrade, strcomments
'We will also need to build a SQL statement
Dim strSQL
Dim conn
set conn=server.CreateObject("ADODB.connection")
conn.ConnectionString="provider=Microsoft.jet.OLEDB.4.0;data source=C:\db\agsystem.mdb"
conn.Open
'Now, we want to loop through each form element
Dim iLoop
For iLoop = 0 to iCount
'student data
strstudent = Request(iLoop & ".Student")
'course data
strcourse = Request(iLoop & ".course")
'grade
if isNull(Request(iLoop & ".grade")) or Request(iLoop & ".grade")="" then
strgrade="null"
else
strgrade= Request(iLoop & ".grade")
end if
if isNull(Request(iLoop & ".comments")) or Request(iLoop & ".comments")="" then
strcomments=null
else
strcomments=Request(iLoop & ".comments")
end if
strSQL = "UPDATE testing SET semester2 = " & strgrade & ", commentss=" & "'" & strcomments & "'" & " WHERE newstudentid = " &"'"& strstudent&"'" & " and Courseid = " & "'"& strcourse & "'"
conn.Execute strSQL
Next
conn.Close
Set conn = Nothing
Response.Redirect "protected.asp"
%>
The problem is that when tested in the server it updates without any issues. But when access from a wireless network it won't update.
The target table to update has about 27,000 records
I need to know what I'm doing wrong or if there is another approach.
I found the error after carefully analyzing the situation.
Records in primary key that have spaces for example '2 OR 13' will not update. But records without spaces in primary key like '2CEN13' updates perfectly. I did not had time to solve it in my asp code, so i edited all records with spaces and that solve the problem.

Returning more than 1000 rows in classic asp adodb.recordset

My code in asp classic, doing a mssql database query:
rs.pagesize = 1000 ' this should enable paging
rs.maxrecords = 0 ' 0 = unlimited maxrecords
response.write "hello world 1<br>"
rs.open strSql, conn
response.write "hello world 2<br>"
My output when there are fewer than 1000 rows returned is good. More than 1000 rows and I don't get the "hello world 2".
I thought that setting pagesize sets up paging and thus allows all rows to be returned regardless of how many rows there are. Without setting pagesize, paging is not enable and the limit is 1000 rows. However my page is acting as if pagesize is not working at all.
Please advise.
is it possible you are declaring your oRS.pagesize before you are opening the recordset?
Here is a good example of paging using getrows...
<!--VB ADO Constants file. Needed for the ad... constants we use-->
<!-- #include file="adovbs.inc" -->
<%
' BEGIN USER CONSTANTS
Dim CONN_STRING
Dim CONN_USER
Dim CONN_PASS
' I'm using a DSN-less connection.
' To use a DSN, the format is shown on the next line:
'CONN_STRING = "DSN=DSNName;"
CONN_STRING = "DBQ=" & Server.MapPath("database.mdb") & ";"
CONN_STRING = CONN_STRING & "Driver={Microsoft Access Driver (*.mdb)};"
' This DB is unsecured, o/w you'd need to specify something here
CONN_USER = ""
CONN_PASS = ""
' Our SQL code - overriding values we just set
' Comment out to use Access
CONN_STRING = "Provider=SQLOLEDB;Data Source=10.2.2.133;" _
& "Initial Catalog=samples;Connect Timeout=15;" _
& "Network Library=dbmssocn;"
CONN_USER = "samples"
CONN_PASS = "password"
' END USER CONSTANTS
' BEGIN RUNTIME CODE
' Declare our vars
Dim iPageSize 'How big our pages are
Dim iPageCount 'The number of pages we get back
Dim iPageCurrent 'The page we want to show
Dim strOrderBy 'A fake parameter used to illustrate passing them
Dim strSQL 'SQL command to execute
Dim objPagingConn 'The ADODB connection object
Dim objPagingRS 'The ADODB recordset object
Dim iRecordsShown 'Loop controller for displaying just iPageSize records
Dim I 'Standard looping var
' Get parameters
iPageSize = 10 ' You could easily allow users to change this
' Retrieve page to show or default to 1
If Request.QueryString("page") = "" Then
iPageCurrent = 1
Else
iPageCurrent = CInt(Request.QueryString("page"))
End If
' If you're doing this script with a search or something
' you'll need to pass the sql from page to page. I'm just
' paging through the entire table so I just hard coded it.
' What you show is irrelevant to the point of the sample.
'strSQL = "SELECT * FROM sample ORDER BY id;"
' Sept 30, 1999: Code Change
' Based on the non stop questions about how to pass parameters
' from page to page, I'm implementing it so I can stop answering
' the question of how to do it. I personally think this should
' be done based on the specific situation and is clearer if done
' in the same method on all pages, but it's really up to you.
' I'm going to be passing the ORDER BY parameter for illustration.
' This is where you read in parameters you'll need for your query.
' Read in order or default to id
'If Request.QueryString("order") = "" Then
' strOrderBy = "id"
'Else
' strOrderBy = Replace(Request.QueryString("order"), "'", "''")
'End If
' Make sure the input is one of our fields.
strOrderBy = LCase(Request.QueryString("order"))
Select Case strOrderBy
Case "last_name", "first_name", "sales"
' A little pointless, but...
strOrderBy = strOrderBy
Case Else
strOrderBy = "id"
End Select
' Build our SQL String using the parameters we just got.
strSQL = "SELECT * FROM sample ORDER BY " & strOrderBy & ";"
' Some lines I used while writing to debug... uh "test", yeah that's it!
' Left them FYI.
'strSQL = "SELECT * FROM sample WHERE id=1234 ORDER BY id;"
'strSQL = "SELECT * FROM sample;"
'Response.Write "SQL Query: " & strSQL & "<BR>" & vbCrLf
' Now we finally get to the DB work...
' Create and open our connection
Set objPagingConn = Server.CreateObject("ADODB.Connection")
objPagingConn.Open CONN_STRING, CONN_USER, CONN_PASS
' Create recordset and set the page size
Set objPagingRS = Server.CreateObject("ADODB.Recordset")
objPagingRS.PageSize = iPageSize
' You can change other settings as with any RS
'objPagingRS.CursorLocation = adUseClient
objPagingRS.CacheSize = iPageSize
' Open RS
objPagingRS.Open strSQL, objPagingConn, adOpenStatic, adLockReadOnly, adCmdText
' Get the count of the pages using the given page size
iPageCount = objPagingRS.PageCount
' If the request page falls outside the acceptable range,
' give them the closest match (1 or max)
If iPageCurrent > iPageCount Then iPageCurrent = iPageCount
If iPageCurrent < 1 Then iPageCurrent = 1
' Check page count to prevent bombing when zero results are returned!
If iPageCount = 0 Then
Response.Write "No records found!"
Else
' Move to the selected page
objPagingRS.AbsolutePage = iPageCurrent
' Start output with a page x of n line
%>
<p>
<font size="+1">Page <strong><%= iPageCurrent %></strong>
of <strong><%= iPageCount %></strong></font>
</p>
<%
' Spacing
Response.Write vbCrLf
' Continue with a title row in our table
Response.Write "<table border=""1"">" & vbCrLf
' Show field names in the top row
Response.Write vbTab & "<tr>" & vbCrLf
For I = 0 To objPagingRS.Fields.Count - 1
Response.Write vbTab & vbTab & "<th>"
Response.Write objPagingRS.Fields(I).Name
Response.Write "</th>" & vbCrLf
Next 'I
Response.Write vbTab & "</tr>" & vbCrLf
' Loop through our records and ouput 1 row per record
iRecordsShown = 0
Do While iRecordsShown < iPageSize And Not objPagingRS.EOF
Response.Write vbTab & "<tr>" & vbCrLf
For I = 0 To objPagingRS.Fields.Count - 1
Response.Write vbTab & vbTab & "<td>"
Response.Write objPagingRS.Fields(I)
Response.Write "</td>" & vbCrLf
Next 'I
Response.Write vbTab & "</tr>" & vbCrLf
' Increment the number of records we've shown
iRecordsShown = iRecordsShown + 1
' Can't forget to move to the next record!
objPagingRS.MoveNext
Loop
' All done - close table
Response.Write "</table>" & vbCrLf
End If
' Close DB objects and free variables
objPagingRS.Close
Set objPagingRS = Nothing
objPagingConn.Close
Set objPagingConn = Nothing
' Show "previous" and "next" page links which pass the page to view
' and any parameters needed to rebuild the query. You could just as
' easily use a form but you'll need to change the lines that read
' the info back in at the top of the script.
If iPageCurrent > 1 Then
%>
[<< Prev]
<%
End If
' You can also show page numbers:
For I = 1 To iPageCount
If I = iPageCurrent Then
%>
<%= I %>
<%
Else
%>
<%= I %>
<%
End If
Next 'I
If iPageCurrent < iPageCount Then
%>
[Next >>]
<%
End If
' END RUNTIME CODE
%>
Try changing your rs.open line to:
rs.Open strSQL, Conn, 3, 1, &H0001
Here's the breakdown of the function call and parameters:
recordsetobject.Open Source, ActiveConnection, CursorType, LockType, Options
3 - adOpenStatic
1 - adLockReadOnly
&H0001 - adCmdText
I pull this from some old code of mine. I don't remember why this combination of parameters is necessary but it's what is necessary to implement paging.
Unlimited records sounds great but I would set a limit even if it's quite hi.
If you are not getting the "Hello World 2" output, is there an error? That would be helpful as well.
paging is for just that, paging.
your code here is not enough to accomplish that but regardless of the code, why are you trying to return a 1000 rows of data ????
nobody's going to read a 1000 rows of data and it will likely be very slow performance.
Using the following code, I returned 4000+ rows from a sql server table in classic ASP. It's not using the same method, but it doesn't suffer the limitations either.
strconnect = "DRIVER={SQL Server};SERVER=****;DATABASE=****;UID=****;PWD=****"
set conn=server.createobject("adodb.connection")
conn.open strconnect
set rs = conn.execute("select firstname from users")
if not rs.eof then
f_Array = rs.getrows
end if
rs.close
set rs = nothing
conn.close
set conn = nothing
for x = 0 to ubound(f_Array, 2)
response.write (x+1) & ". " & f_Array(0,x) & "<br />"
next

Resources