ASP Survival Guide

Last edited: 12/12/13

This web page has some survival notes on using ASP & VBScript.

Download the source code to all of the files in this section.

Topic Notes
General General
  • ASP (Active Server Pages) is a Microsoft product.
  • ASPX (Active Server Pages Extended) is a Microsoft product working with MS's .Net technology.
  • Web Servers that support ASP:  MS IIS  (maybe others)
  • Basic Coding
    • An ASP can have HTML & ASP code.  HTML is processed by the client (browser) and ASP code is processed by the server (MS IIS).
    • Simple ASP - ASP Scripting is in the <% %> tags.
      • <h1><% = "Hello World" %></h1>
      • <% Response.Write("<h1>Hello World</h1>"); %>
    • Scripting (coding) - the scripting language supported by ASP (code between the tags <% %>) is either VBScript or JScript.
      VBScript - Like Microsoft's VB (Visual Basic).
      JScript - Microsoft's implementation of JavaScript.
  • Code Execution - Remember that any code (scripting) between the tags <% %> is executed on the server side (web/application server), not the client (browser).
Server Side Configuration
(For Developers)
Server Side Configuration - (Win XP Professional)

Home Directory

  • Launch MS IIS (Start, Control Panel, Administrative Tools, Internet Information Services)
  • Right click on "Default Web Site" and choose Properties.
  • Click on the "Home Directory" tab.
  • Click - Script Source Access
  • Click - Read
  • Click on "Configuration"

Home Directory - Configuration - Debugging - Turn on the to Debug

  • Click the "Debugging" tab
  • Check - Enable ASP server-side script debugging
    Check - Enable ASP client-side script debugging
    Check - Send detailed ASP error messages to client

Home Directory - Configuration - Options

  • Click the "Options" tab.
  • Click - Enable session state (Session time out: 20 min)
    Click - Enable Buffering
    Click - Enable parent paths
    Default ASP language: VBScript
    ASP Script timeout: 90 seconds
Server Directives Server Directives
  • All server directives must be at the top of the ASP page.
  • <%@  something %> - example of a Server directive.
  • Script Language Directive
    <%@ Language = VBScript %> - Default script is VBScript
    <%@ Language = JavaScript %> - Default script is JavaScript
    The default script language can be set at the Web Server.
Scripting Language Scripting Language

Defining the default script language:
(Make sure these server directives are at the top of your ASP page.)

  • JavaScript - by Netscape.  JScript is Microsoft's implementation (IE) of JavaScript.
    <%@ Language=JavaScript %>
  • VBScript - by Microsoft
    <%@ LANGUAGE = VBScript %>
    <% Option Explicit %>
    (Note: Option Explicit forces the declaration of variables.)

VBScript vs JavaScript

  • Case Sensitivity - VBScript-NO, JavaScript-YES.
  • There are many, many differences in the 2 languages.  VBScript is similar to MS Visual Basic and VBA (Visual Basic for Applications).  JavaScript was created by Netscape and has some similarity to C and Java (created by Sun).  JavaScript is NOT Java.
VBScript Basics VBScript Basics
  • Commenting (Comment / Comments)
    • // - Single line comment
    • ' - Single line comment
    • <%= %> - Cannot have comments.
    • In-line comments in multiple lines of code - DOES NOT WORK (for me atleast)
      • Example that DOES NOT Work
        strMsg = "Hello" & _ //Test Comment.
      • Example that DOES Works
        strMsg = "Hello" & _
                 "World" //Test Comment.
    • Multi-line comments (VBScript) - DOES NOT WORK
      • /* */ - does not work.
      • The best work around is to close the ASP script and make an HTML comment.
        • Example that DOES work  (Because the comment becomes an HTML comment!)
          response.write( "Before" & "<br>")
          response.write( "Hello World" & "<br>")
          response.write( "Session.SessionID = " & Session.SessionID )
          response.write( "After" & "<br>")
        • Example that DOES NOT work.
          response.write( "Before" & "<br>")
          response.write( "Hello World" & "<br>")
          response.write( "Session.SessionID = " & Session.SessionID )
          response.write( "After" & "<br>")
  • Creating multiple lines of code.  Use the "_" character.
    MyVar = "This is test line 1" _
                & "This is test line 2"
  • Declaring a variable
    • <% Option Explicit %> -  Forces declaration of variables.
    • Dim strSql ' As String - Declare a variable.
  • Conditional
    • Or - don't use: ||
    • And - don't use: &&
  • String Values
    • Assign a string value:  Use a double quote ( " ). 
        • Single quote ( ' ) doesn't work!
    • Adding strings (&): "String 1" & "String 2"
    • Insert a quote (") in a string.  Escape the quote by using 2 quotes.
      sText = "<font size=""3"">Hello World</font>"
      Returns:  <font size="3">Hello World</font>
  • Misc Items
    • Count vs Length
      VBScript: objMy.Count
      JScript: objMy.length
  • Other gotchas
    • Equality in conditional statement, use "=" and NOT "==".
    • NULL
      VBScript: NULL (notes: isNull(NULL) returns true.  isNull("") returns false.  )
      JScript: null
    • "&" vs "+" with Strings.  Use the "&" to add string values.
    • Escaping a Quote
      JScript: Escape Quote: \"
      VBScript Escape Quote: "" (2 Quotes)
    • += Doesn't exist !!!
      Use intLoop = intLoop + 1
    • not vs !
      Example #2:
      JScript: intMyVar != 1
      VBScript: not ( intMyVar = 1 )
      Example #1:
      JScript: if ( ! blnMyVar )
      VBScript: if ( not blnMyVar )
      Example #2:
      JScript: if ( intEx != 0 ) (<> is an error)
      VBScript: if ( intEx <> 0 ) (!= is an error)
    • Arrays start with 0.
      JScript Arrays start with: 0, columns with 0
      VBScript Arrays start with: 0, But columns with 1
JScript Basics JScript Basics
  • Commenting
    • // - Single line comment.
    • /* */
  • <%  <ASP Server side script %>
  • <%= <value or function that returns a value>  %>
  • <% Response.Write ( <value> ) %>
Debugging Tips Debugging Tips
  • If you want to stop processing the .ASP page and return the results use: (Very useful to me!)
    If ( false ) then
      Response.Write("query = " & query)
    End if


    If Response.Buffer has been set to TRUE, calling Response.End will flush the buffer. If you do not want output returned to the user, you should call Response.Clear first.
Variable Visibility Variable Visibility
  • Visibility of Variables
    • Web Server Variables (IIS)
      • Session - Store the variable in the Session Object.  Visible by all ASP pages requested by one user (user specific).
          Session("FirstName") = "John"
          Session("LastName") = "Doe" 
      • Application - Store the variable in the Application Object.  Visible by all ASP pages requested by any user (application specific).  "... an Application is a group of ASP files within as single directory, including any subdirectories"
        <% Application("AppName") = "ABC Reporting" %>
    • Global - A variable declared outside of a procedure (VBScript) or a function.
    • Local - A variable declared inside of a procedure (VBScript) or a function.
DB Connections DB Connections

Example ASP Code to Connect to a DB:

  • x
    • Open Connection string.
  • MS Access 2000 MDB example.
    //Example of connecting to a Database.
    Dim dbcnUsers ' As ADODB.Connection
    Dim strDbPathname ' As String
    Dim strConnection ' As String

    strDbPathname = Server.MapPath("MyDbBasics.mdb")

    strConnection = _
    "Provider=Microsoft.Jet.OLEDB.4.0;" _
    & "Data Source=" & strDbPathname

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

Provider attributes:

  • MS Access 2000: Provider=Microsoft.Jet.OLEDB.4.0;
  • MS Access 97: Provider=Microsoft.Jet.OLEDB.3.51;
  • DSN (Data Source Name)
    DB2 Example:


Create a Table of Data Based on a SQL Query Create an HTML Table based all the fields of a Query:

Dim dbcnUsers ' As ADODB.Connection
Dim strOpenDBInfo ' As String
strOpenDBInfo = "DSN=MyDbAsp;UID=mydbasp;PWD=mydbasp;"
Set dbcnUsers = Server.CreateObject("ADODB.Connection")
Dim rsUsers ' As ADODB.Recordset
Dim strSql ' As String
strSql = "select * from users order by username"
Set rsUsers = dbcnUsers.Execute( strSql ) //Returns a RecordSet

response.write( "<table border='1'>" )

' Create the column titles.
Dim itemColumn
Response.Write("<tr>" & vbCrLf )
For Each itemColumn in rsUsers.Fields
  Response.Write("<td>" & & "</td>" & vbCrLf )
Response.Write("</tr>" & vbCrLf )

Do While Not rsUsers.EOF
  ' Create the rows of data.
  Response.Write("<tr>" & vbCrLf )
  For Each itemColumn in rsUsers.Fields
    Response.Write("<td>" & rsUsers( & "</td>" & vbCrLf )
  Response.Write("</tr>" & vbCrLf )


response.write( "</table>" )

Load an Array With the Results

arrUsers = rsUsers.GetRows

Database Permissions Permissions is granted at the Database server, not in ASP.  You can log into the database from ASP at connection time.
  • MS Access Database
    • The default is to give permissions to the Group "Users"
    • To view permissions, open the database then:  Tools, Security, Users & Group Permissions.
Basic ASP Objects Basic ASP Objects
  • Response - object that returns data to the browser.
    • Response object - is used to send the output back to the client (browser) (HTTP variables, cookies, and other info about the content).
      • Response.Cookies (collection) - specify the values of cookies which will be sent back to the client browser.
      • Response.Buffer (property) A boolean value indicating whether page output is buffered or not. (true = output from the page will not be sent to the client until all the script in that page is processed). IIS 5 default is true.
      • Response.CacheControl (property) - A string specifying that the output from the ASP should be cached or not. (Pulbic = proxy server to cache the output of your ASP, Private = no)
      • Response.Charset (property) - A string which appends the name of character set to be used to HTTP-content-type header.
      • Response.ContentType (property) - A string which specifies the HTTP content type for the response. (default = MIME-type "text/html")
      • Response.Expires (property) - An integer specifying the duration of time in minutes after which the page expires in the client browser cache.
      • Response.ExpiresAbsolute (property) - Date/Time after which the page cached in the client browser expires and is no longer valid. (ex: Response.ExpiresAbsolute = #March 31, 2001 12:00:00# )
      • Response.IsClientConnected (property) - A boolean value indicating whether the client is still connected to this particular page. If this property returns false then the page's script processing can be stopped by using Response.End method.
      • Response.Pics (property) - create a PICS header (content rating)
      • Response.Status (property) - A string which specifies the value of status line of the server. (ex: "404 File Not Found".)
      • Response.AddHeader (method) - Adds a custom new HTTP header to the response. Must be used before any text or HTML is sent to the client. Does not replace a HTTP header of the same name e.g. Response.AddHeader "AUTHENTICATED", "You are now logged on."
      • Response.AppendToLog (method) - A string which is added to the end of the web server log entry for this page. (ex: Response.AppendToLog "Your custom log info.".
      • Response.BinaryWrite (method) -  writes binary data (images, etc...)
      • Response.Clear (method) - Clears the buffered output html (ex:  aborting, etc....)
      • Response.End (method) -  Abort the processing of the script and send page to client.
      • Response.Flush (method) - Sends the buffered output immediately to the client. Is used to send parts of long pages to the client when Response.Buffer is set to true.
      • Response.Redirect (method) - Redirects the browser to another page (URL)
        (ie: Response.Redirect( "" ).
        (ie: Response.Redirect( "http://<yourpage>?parm1=hello&parm2=world" ).
      • Response.Write (method) - Writes the specified string to the web page
        (ie: Response.Write( "Hello World!") )
  • Request - object that contains data sent by the browser (html parms, forms, cookies, client certificates (if SSL) etc...).
    • Request.ServerVariables (collection) - Contains a collection of predetermined environment variables plus a collection of all the HTTP header values sent from the client browser to the server.
      Request.ServerVariables("SERVER_NAME") - returns the server name.
      Request.ServerVariables("QUERY_STRING") - returns the complete URL parm string as a string.
      Request.ServerVariables("selSearchCities") - returns the URL parm value for "selSearchCities".
      (Note: You can do the following also: Request("selSearchCities")  )
    • Request.QueryString (collection) - Collection of variables which are stored in the HTTP query string.
      Ex: Request.QueryString("myurlparm")
      (Note: You can do the following also: Request("myurlparm")  )
    • Request.Form (collection) - Collection of all the values of Form element in the HTTP request.
      Ex: Request.Form("selSearchCities")
    • Request.ClientCertificate (collection) - Makes us available a collection of values stored in the client certificate that is sent to the HTTP request.
    • Request.Cookies (collection) - cookies stored in the client browser for this domain.
    • Request.TotalBytes (property) total number of bytes in this request.
    • Request.BinaryRead (method) - Retrieves data sent to the server from the client in raw format as part of the POST request. It saves all this data in a SafeArray.
  • Server - the methods and properties of our server ( IIS ).
    • Server.ScriptTimeout (property) - script timeout abort value in seconds.
      ex: Server.ScriptTimeout = 90 'In Seconds
      Warning:  Requires an IIS reset (restart) before the ASP pages will use the new value if it is changed from the IIS Manager screen (ASP Script timeout).
    • Server.CreateObject (method) - Creates an instance of the object ( a component, application or a scripting object ).
    • Server.Execute (method) - Executes the given .asp page and then returns the control to the page who called the method.
    • Server.HTMLEncode (method) - Provides HTML encoding to a given string.
    • Server.MapPath (method) - Maps the specified virtual or relative path into physical path of the server.
    • Server.Transfer (method) - Transfers the control of the page to another page specified in the URL.
    • Server.URLEncode (method) - Provides URL encoding .
  • Application
    • The Application object is created when the first .asp page is requested after starting the IIS and remains there until the server shuts down. All the variables created with application object have application level scope meaning there by that they are accessible to all the users. All .asp pages in a virtual directory and its subdirectories come under the application scope. So application level variables are shared by more than one user at a time.
    • Application.Contents (collection) - all application objects.
    • Application.StaticObjects (collection)
    • Contents.Remove (method) - removes item from Application.Contents.
    • Contents.RemoveAll (method) - removes all item from Application.Contents.
    • Application.Lock (method) - lock so one user at a time can modify the values.
    • Application.UnLock (method)
    • Application_OnEnd (event) - This event occurs when the IIS is shut down after Session_OnEnd event. All the variables are destroyed after that.
    • Application_OnStart (event) - This event occurs when the first .asp page is called after starting the IIS. Application level variables can be declared here.
  • Session - user specific object that has persistence across web pages and is stored by IIS.
    • Session(<session name>) = <value>
    • Session object - created every time client browser access pages from your web site. Session object is specific for every user and varies from user to user. It can be used to store variables specific for a user and IIS will maintain these variables when the client moves across pages within your site.
    • Session.Contents (collection) - Contains all the items which have been added to the Session object. You can iterate through the Contents collection and retrieve a list of all the items added or you can retrieve a specific item. Note that it contains all the Session items except the ones created using <object> element.
    • Session.StaticObjects (collection) - Contains all the items which have Session scope created using <object> element.
    • Session.CodePage (property) - An integer which defines the code page to be used to display content to the client browser (1252= American English)
    • Session.LCID (property) - locale identifier.
    • Session.SessionID (property) - session identifier for this client browser.
    • Session.Timeout (property) - time out period in minutes. If the client doesn't refresh or request any page of your site within this time out period then the server ends the current session. (default - 20 minutes).
      Ex: Session.Timeout = 120 'In Minutes
  • ASPError - (starting in IIS v5)
    • ASPError.ASPCode (property) - A string which contains the error code generated by the server .
    • ASPError.Number (property) - A long integer which contains the error code returned by the COM component. A standard COM error code.
    • ASPError.Source (property) - A string which contains the actual source code which caused the error, if available.
    • ASPError.Category (property) - A string which indicates if the error was caused by IIS, scripting language or some component.
    • ASPError.File (property) - A string, name of the .asp page which caused the error.
    • ASPError.Line (property) - An integer which indicates the number of line in .asp page that caused the error.
    • ASPError.Column (property) - An integer indicating the column position within the .asp page which caused the error.
    • ASPError.Description (property) - A string , short description of the error.
    • ASPError.ASPDescription (property) - Detailed description of the error if it is ASP related.
  • ObjectContext - objects for Transaction processing.
    • SetAbort (method) -  Aborts the transaction initiated by the ASP script.
    • SetComplete (method) - if all components report complete then the transaction will complete.
    • OnTransactionAbort (event) - This event occurs when the transaction is aborted.
    • OnTransactionCommit (event) - This event occurs when the transactional script's transaction is committed.
Error Handling Error Handling in VBScript

On Error Resume Next - will resume process if there is an error.  Then you can trap for it.
On error goto 0 - Resets error handling.
(Note: There is No "On Error Function()" in VBScript like there is in VB)

Example #1:
On Error Resume Next
Set rsMyResultSet = mydatabase.execute(strSql)

if ( Err.Number = 0 ) Then
End if

Example #2:

Sub HandleError

  If Err.Number = 0 then Exit Sub

  Response.Write("<hr>" & vbCrLf)
  Response.Write("Err.Number = " & Err.Number & "<br>" & vbCrLf)
  Response.Write("Err.Description = " & Err.Description & "<br>" & vbCrLf)

End Sub

On Error Resume Next
Set rsMyResultSet = mydatabase.execute(strSql)

Example #3:

dim rsUsers
dim strSql
strSql = "select * zzz from MyTable"
On Error Resume Next
Set rsUsers = mydbconnection.execute(strSql)
if ( Err.Number <> 0 ) Then
  Response.Write("<hr>" & vbCrLf)
  Response.Write("Err.Number = " & Err.Number & "<br>" & vbCrLf)
  Response.Write("Err.Description = " & Err.Description & "<br>" & vbCrLf)   Response.Write("Err.HelpContext = " & Err.HelpContext & "<br>" & vbCrLf)   Response.Write("Err.Source = " & Err.Source & "<br>" & vbCrLf)
Response.Write("Err.HelpFile = " & Err.HelpFile & "<br>" & vbCrLf)
  Response.Write("<hr>" & vbCrLf)
' This error object has no data for SQL errors!!!
Dim objASPError
Set objASPError = Server.GetLastError()
Response.Write("ASPCode = " & objASPError.ASPCode & "<br>" & vbCrLf)
Response.Write("ASPDescription = " & objASPError.ASPDescription & "<br>" & vbCrLf)
Response.Write("Category = " & objASPError.Category & "<br>" & vbCrLf)
Response.Write("Column = " & objASPError.Column & "<br>" & vbCrLf)
Response.Write("Description = " & objASPError.Description & "<br>" & vbCrLf) Response.Write("File = " & objASPError.File & "<br>" & vbCrLf)
Response.Write("Line = " & objASPError.Line & "<br>" & vbCrLf)
Response.Write("Number = " & objASPError.Number & "<br>" & vbCrLf)
Response.Write("Source = " & objASPError.Source & "<br>" & vbCrLf)
Response.Write("<hr>" & vbCrLf) Response.Write("URL = " & Request.ServerVariables("URL") & "<br>" & vbCrLf) Response.Write("Filename = " & Request.ServerVariables("PATH_TRANSLATED") & "<br>" & vbCrLf)
Response.Write("Remote User = " & Request.ServerVariables("REMOTE_USER") & "<br>" & vbCrLf)
Response.Write("Remote Host = " & Request.ServerVariables("REMOTE_HOST") & "<br>" & vbCrLf)
Response.Write("Server Name = " & Request.ServerVariables("SERVER_NAME") & "<br>" & vbCrLf)
Response.Write("Local Addr = " & Request.ServerVariables("LOCAL_ADDR") & "<br>" & vbCrLf)
' Response.redirect("database_example.asp") 'Endless error loop!
End If
Other Items
  • Raise an error:  Err.Raise 6 'Raise an overflow error.
  • Err.Clear 'Clears the error. 
Invoking a Stored Procedure from ASPExample Code (ASP-VBScript): (to run a Stored Procedure from MSSQL )

dim strOpenDBInfo
dim database

strOpenDBInfo = "DSN=mydb; UID=sa; PWD=mypswd;"
Set database = Server.CreateObject("ADODB.Connection")

dim cmdSaveUser
dim strSql

Set cmdSaveUser = Server.CreateObject("ADODB.Command")
Set cmdSaveUser.ActiveConnection = database
cmdSaveUser.CommandText = "spCustomSaveUser"
cmdSaveUser.CommandType = &H0004 ' &H0004 Value for a Stored Procedure (aka: adCmdStoredProc if you have that const variable.)

cmdSaveUser.Parameters(1) = Session("User.userid") ' @userId int
cmdSaveUser.Parameters(2) = Request.Form("elmPhone") ' @phone varchar(30)
cmdSaveUser.Parameters(3) = Request.Form("elmEmail") ' @email varchar(128)

'Output returned. (See the Stored Procedure and look for Parms with OUTPUT.
'cmdSaveUser.Parameters(4) @errorCode int OUTPUT
'cmdSaveUser.Parameters(5) @errorText varchar(255) OUTPUT


If cmdSaveUser.Parameters(4) <> 0 Then '@errorCode
response.redirect("creditcard_confirm.asp?errorcode=" & cmdSaveUser.Parameters(4) & "&errortext=" & cmdSaveUser.Parameters(5)) '@errorText
End If

Microsoft's resources:
Email using CDONTS.NewMailEmail using CDONTS.NewMail
FYI - I was not successful in getting CDONTS working on a server that emailed using a relay server.
Warning: I don't think there is a way to specify the SMTP Server. (Win2000 IISv5)

Microsoft's resources:

Email using CDO.MessageTested on a Win 2000 Server with IIS v5

These metadata tags have the cdo... variable values.  Place these tags towards the top but below the Server Language tag.

<!--METADATA TYPE="typelib" UUID="CD000000-8B95-11D1-82DB-00C04FB1625D" NAME="CDO for Windows 2000 Library" -->
<!--METADATA TYPE="typelib" UUID="00000205-0000-0010-8000-00AA006D2EA4" NAME="ADODB Type Library" -->

Here is the cdo values for the variables if you don't want to place the metadata tags in your code:
cdoSendUsingPort = 2
cdoBasic = 1
cdoSendUsingMethod =
cdoSMTPServer =
cdoSMTPServerPort =
cdoSMTPAuthenticate =

Microsoft Resource:;EN-US;Q286431&ID=KB;EN-US;Q286431&

IIS and ASP pages hangingI've seen the following: (Win 2000 & IIS v5)
(Note: I could NOT duplicate this problem on Win XP Prof IIS web server.  All ASP pages would server out even during the script timeout period.)

Problem #1:
In a MSSQL DB environment, if a script that generates a SQL error is not Error Trapped then all ASP pages appear to hang until the script times out.  (Ex SQL: select * zzz from MyTable )

Problem #2:
All ASP pages appear to hang (the script doesn't time out from the server side).  It is possible that the client's web browse could time out.  Other files work fine (ie: html, images, etc....).
To create this problem, setup problem #1 (SQL select error) and have 2 users hit the ASP page at the same time that has a SQL select error.

How to un-hang IIS:
Win 2000 & Win XP Prof

IIS Option #2: (This will stop and start the web server).
bulletIIS Option #1:
In IIS Manager, right click on the web site (ie: Default Web Site) and choose Properties
Click on "Home Directory"
In the Application Setting section, notice the Application Name setting (ie: Default Application)
Click "Remove" accross from Application Name and then click Create.
Now any new hits to ASP pages will be served out.
bulletIIS Reset (Restart):
from the command line do: c:\ IISReset

Solution to Problem #1 and #2: (also consider global.asa etc...)

Place error trapping around the calls to execute when creating the results set.
' Note: You do not have to create the "Err" object.
On Error Resume Next
Set rsUsers = docentlms.execute(strSql)
if ( Err.Number <> 0 ) Then
  Response.Write("Err.Number = " & Err.Number & "<br>" & vbCrLf)
  Response.Write("Err.Description = " & Err.Description & "<br>" & vbCrLf)
  Response.Write("Err.HelpContext = " & Err.HelpContext & "<br>" & vbCrLf)
  Response.Write("Err.Source = " & Err.Source & "<br>" & vbCrLf)
  Response.Write("Err.HelpFile = " & Err.HelpFile & "<br>" & vbCrLf)
End If

  • Placement of the file - IIS will use the Global.asa file if it is placed in the root directory of the Web Site or a Virtual Web Site.   With that statement in mind, the closest Global.asa file will override any Global.asa file in a parent directory.  If there is no Global.asa in the current virtual Web Site then the web server will use the closest Global.asa in a parent Web Site.  The closest Global.asa will completely replace any Global.asa in a parent Web Site.
  • In my testing of Win XP Pro and Win 2000 Server changes to the Global.asa seem to be read immediately without a web server reset (or restart) or without the user closing his browser and creating another connection.  This includes changes to the Application_xxx and Session_xxx subs.
ASP & Server Name
(Network Server Name vs the HostName from the Client's URL)
Network Server Name vs the HostName from the Client's URL

This is the HostName from the client's URL:


Get The Network Server Name:
' (FYI - this will work in the Global.asa's Application_OnStart sub.)
Dim strNetworkServerName
Dim objWScriptNetwork

Set objWScriptNetwork = CreateObject("WScript.Network")
strNetworkServerName = objWScriptNetwork.ComputerName

Application("strNetworkServerName") = strNetworkServerName
WSH (Windows Script Host)Windows Script Host

Network Server Name:
Dim strNetworkServerName
Dim objWScriptNetwork
Set objWScriptNetwork = CreateObject("WScript.Network")
strNetworkServerName = objWScriptNetwork.ComputerName


File SystemFile System

Example of creating a text file on the server and appending text.

Dim objFileSystemObject
Dim objFile
Dim objFileStream

Set objFileSystemObject = Server.CreateObject("Scripting.FileSystemObject")

If ( objFileSystemObject.FileExists( Application("strLogFileLocation") ) ) Then
  Set objFile = objFileSystemObject.GetFile( Application("strLogFileLocation") )
  ' 8=ForAppending, -2 System Default 0 = ASCII
  Set objFileStream = objFile.OpenAsTextStream(8, 0)
  Set objFileStream = objFileSystemObject.CreateTextFile( Application("strLogFileLocation") )
End If

objFileStream.Write( strLogFileMsg )

In Download zip file - see MyTextFileA.asp.

Creating an Excel file.Creating an Excel file:

Dim strFileName
strFileName = "MyFile_" & _
              DatePart("yyyy",Date) & _
              right("0" & DatePart("m",Date), 2) & _
              right("0" & DatePart("d",Date), 2) & _

Response.ContentType = "application/"
Response.AddHeader "content-disposition","attachment; filename=" & strFileName

Example of ASP code that will use the Excel Sum function:
<td bgcolor="#808080">=SUM(B4:B6)</td>

Then add your normal html code.  Be aware that some tags may have conversion issues.

Note:  I have an example .asp page in my download zip: MyExcelSpreadSheet.asp

ASP (VBScript) - running from a Windows Scheduled Task. ASP VBScript - Running from a Windows Scheduled Task - see information on trying to run ASP from a windows scheduled task.
Running an ASP page from a batch file.

In Download zip file - see MyTextFileA_batchfile_run_asp_via_ie.bat

Example Batch file:

cd "C:\_data\webs\A\\tech\asp\myaspexamples"
set strLogFile=MyTextFileA_batchfile_run_asp_via_ie.log
echo ************************************ >> %strLogFile%
echo Start: %date% %time% >> %strLogFile%
"C:\Program Files\Internet Explorer\IExplore.exe" "http://localhost/michael-thomas/tech/asp/myaspexamples/MyTextFileA.asp?loopcount=10000&closebrowser=no"
echo Stop: %date% %time% >> %strLogFile%

VBScript Resources



ASP-VBScript Functions, Subroutines & Custom Objects

Subroutines vs FunctionsSubroutines vs Functions
  • Functions - return values.
  • Subroutines - do not return values.


Subroutines - MainMain Sub Routine - used to start running the ASP page.

Sub Main()


End Sub

Call Main


Sub <SubName> ( [ <parm1>, <parm2>, _
                            <parm3>, etc... ] )


End Sub

To exit a subroutine at any place use:  Exit Sub

FunctionsFunction <FunctionName> ( [ <parm1>, <parm2>, _
                                           <parm3>, etc... ] )


  <FunctionName> = <value>  ' This is what is returned.
End Function

Example: Simple function for writing to <td> cells ( &nbsp; instead of "" or NULL)

Function fHtmlEmptySpace( varValue ) ' Inline If
  Dim strReturn
  If ( isNull( varValue ) or varValue = "" ) Then
    strReturn = "&nbsp;"
    strReturn = varValue
  End If
  fHtmlEmptySpace = strReturn
End Function

Call like this:
strPaymentType = fHtmlEmptySpace( rsDealerPayment("PaymentType") )
Creating Custom Classes
(Custom Objects)
In my download examples, this file is called:
MyAspCustomClasses.asp (tested in IIS v5)

<%@ Language=VBScript %>
<% Option Explicit %>
<% Response.Expires= -1 %>
<% Sub Main %>
<title>Example of Custom Classes in ASP (VBScript)</title>
<meta name="Microsoft Border" content="t, default">
<h1 align="center">Example of Custom Classes in ASP (VBScript)</h1>

<p>Simple example of creating a custom class (custom object) in ASP using VBScript. (Note: You must look at the .ASP source code. Viewing the source from the browser will not work.)</p>


Dim objUser ' As User
Set objUser = New User

objUser.Name = "John Doe"
objUser.LastLogin = Date()
objUser.ChangeUserCode("Preferred") ' Options: Preferred, Normal
' objUser.UserCode = 1 ' Note: because this was made Private, you can't access it here!


Name: <%= objUser.Name()%> <br>
User Code Type: <%= objUser.UserCodeType() %> <br>
Last Login: <%= objUser.LastLogin() %> <br>
Public Var in User Object: <%= objUser.strPublicVarTest %> <br>

<% End Sub %>
<% Call Main %>
Class User

  Private strName ' As String
  Private dateLastLogin ' As DateTime
  Private intUserCode ' As Integer
  Public strPublicVarTest ' As String - Not a good programming practice.

  Public Property Let Name(strValue)
    strName = strValue
  End Property

  Public Property Get Name()
    Name = strName
  End Property

  Public Property Let LastLogin(dateValue)
    dateLastLogin = dateValue
  End Property

  Public Property Get LastLogin()
    LastLogin = dateLastLogin
  End Property

  ' Note that this is a PRIVATE example.
  Private Property Let UserCode(intValue)
    intUserCode = intValue
  End Property

  Public Property Get UserCode()
    UserCode = intUserCode
  End Property

  Public Sub ChangeUserCode( strUserCode )
    If ( strUserCode = "Preferred" ) Then
      UserCode = 1 ' This calls the Let (setter) which is Private.
      UserCode = 0 ' This calls the Let (setter) which is Private.
    End If
  End Sub

  Public Function UserCodeType()
    If ( UserCode = 1 ) Then      ' This calls the Get
      UserCodeType = "Preferred"
      UserCodeType = "Normal"
    End If

  End Function

End Class


ASP-VBScript Control Loops

If ... Then ... ElseIf <conditions> Then
[ElseIf <condition> Then ]
End If

Inline If for VBScript: (WORK-AROUND: Create a function!)

Function IIf( blnValue, varTrue, varFalse )
  If blnValue Then IIf = varTrue Else IIf = varFalse
End Function
strMyVar = IIf( 2>1, "Greater", "Less Than") ' result: Greater

For/NextFor <loopvariable> = <startvalue> To <endvalue> [ Step <value> ]
For Each/NextFor Each <loopvariable> in <objName>

ASP Examples:

' Loop through all of the Application variables: ( or Application("variable name") )
For Each strItem in Application.Contents
  Response.Write("Application(""" & strItem & """) = " & _
                  Application.Contents(strItem) & "</br>" & vbCrLf )

' List of All Session.Contents variables: ( or Session("variable name") )
For Each strItem in Session.Contents
  Response.Write("Session.Contents(""" & strItem & """) = " & _
                  Session.Contents(strItem) & "</br>" & vbCrLf )

' List of All Request.ServerVariables variables:
For Each strItem in Request.ServerVariables
  Response.Write("Request.ServerVariables(""" & strItem & """) = " & _
                  Request.ServerVariables(strItem) & "</br>" & vbCrLf )


' Step through properties of an Object.
' (ActiveX in a MSSQL DTS)

For Each objMy in colObjects
  strMsg = strMsg & & vbCrLf

Example: (ActiveX in a MS SQL DTS)
Set objFileSystemObject = CreateObject("Scripting.FileSystemObject")
Set objFSO_Folder = objFileSystemObject.GetFolder(".")
Set colFiles = objFSO_Folder.Files

For Each objFile in colFiles
  strMsg = strMsg & & vbCrLf

msgbox ( strMsg )


Select/CaseSelect Case <variable>
  Case <literal value>
  Case <literal value>, <literal value>, etc... :
  Case Else
End Select

Loop While <variable> <condition> <value>

Loop Until <variable> <condition> <value>

Do Until <variable> <condition> <value>

Do  While <variable> <condition> <value>

While <variable> <condition> <value>

Dim intLoop
intLoop = 1
  intLoop = intLoop + 1
Loop While intLoop >= 5

Special Objects

Object Info
RegExpr RegExp - Regular Express Object (under construction)

Dim objRegExp
Set objRegExp = New RegExp




ASP-VBScript Function List by Category

Category Functions
Variable Types TypeName, VarType
CBool, CByte, CCur, CDate, CDbl, CInt, CLng, CInt, CLng, Csng, CStr
IsArray, IsDate, IsEmpty, IsNull, IsNumeric, IsObject

Note: Use the c... functions to convert a string to numeric.
intMyVar = cInt( "123" )
lngMyVar = cLng( "123.99" )

Strings Asc, Chr, InStr, InStrRev, LCase, Left, Len, LTrim, Mid, Replace, Right, RTrim, Space, StrComp, String, StrReverse, Trim, UCase
FormatCurrency, FormatDateTime, FormatNumber, FormatPercent
Numbers Abs, Atn, Cos, Exp, Fix, Hex, Int, IsNumeric, Log, Oct, Rnd, Round, Sgn, Sin, Sqr, Tan
Date/Time Date, DateAdd, DateDiff, DatePart, DateSerial, DateValue, Day, Hour, IsDate, Minute, Month, MonthName, Now, Second, Time, TimeSerial, TimeValue, Weekday, WeekDayName, Year
Arrays Array, Filter, IsArray, Join, Split, IsArray, UBound
Objects CreateObject, GetObject, IsObject
Scripting ScriptEngine, ScriptEngineBuildVersion, ScriptEngineMajorVersion

ASP-VBScript Functions & Description


Returns the absolute value of the number. (Converts all negative values to positive values).
Creates an array. 
Rows start from: 0
Columns start from: 1

<ArrayName>(3) - Single dimensional
<ArrayName>(3, 5)  - Multi-dimensional

Example: Single Dimensional Array created with Array()

Dim intDay
Dim arrDaysOfWeek
arrDaysOfWeek = Array("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday")

strMsg = strMsg & "Array created by Array()." & "<br>" & vbCrLf
For intDay = 0 to UBound(arrDaysOfWeek)-1 Step 1
  strMsg = strMsg & intDay & " - " & arrDaysOfWeek(intDay) & "<br>" & vbCrLf
Response.Write( strMsg )

Example: Single Dimensional Array

Dim strMsg
Dim arrItems(4)

arrItems(0) = "January"
arrItems(1) = "February"
arrItems(2) = "March"
arrItems(3) = "April"

Dim intCounter

strMsg = strMsg & "Step through an array: Bottom up" & "<br>" & vbCrLf
For intCounter = 0 to UBound(arrItems)-1 Step 1
  strMsg = strMsg & intCounter & " - " & arrItems(intCounter) & "<br>" & vbCrLf

strMsg = strMsg & "<br>" & vbCrLf

strMsg = strMsg & "Step through an array: Top down (reverse)." & "<br>" & vbCrLf
For intCounter = UBound(arrItems)-1 to 0 Step -1
  strMsg = strMsg & intCounter & " - " & arrItems(intCounter) & "<br>" & vbCrLf

Response.Write( strMsg )

Example: Multi-Dimensional Array

Dim strMsgMulti
Dim intCounterMulti
Dim arrItemsMulti(3,2)
Const COL1MULTI = 1
Const COL2MULTI = 2

arrItemsMulti(0, COL1MULTI) = "Row #0 - Col #1"
arrItemsMulti(0, COL2MULTI) = "Row #0 - Col #2"
arrItemsMulti(1, COL1MULTI) = "Row #1 - Col #1"
arrItemsMulti(1, COL2MULTI) = "Row #1 - Col #2"
arrItemsMulti(2, COL1MULTI) = "Row #2 - Col #1"
arrItemsMulti(2, COL2MULTI) = "Row #2 - Col #2"

strMsgMulti = strMsgMulti & "Step through an Multi-Dimensional array: Bottom up" & "<br>" & vbCrLf
For intCounterMulti = 0 to UBound(arrItemsMulti)-1 Step 1
strMsgMulti = strMsgMulti & intCounterMulti & " - " & arrItemsMulti(intCounterMulti,COL1MULTI) & " : " & arrItemsMulti(intCounterMulti,COL2MULTI) & "<br>" & vbCrLf

Response.Write( strMsgMulti )

Returns the ANSI code for the first letter in the string.
Each letter in the alphabet (and some special characthers) has got it's own numeric value. To find this value use the Asc() function. The reverse function is Chr().
Returns the arctangent.
Converts to variant of subtype Boolean
Converts to variant of subtype Byte
Converts to variant of subtype Currency
Converts to variant of subtype Date
Converts to variant of subtype Double
Converts ANSI code to the corresponding keyboard character

Common Uses:

chr(13) Carriage return
chr(13)&chr(10) Combination carriage return and line feed
chr(12) Form feed
chr(10) Line feed
chr(9) Horizontal tab
chr(11) Vertical tab

Converts to variant of subtype Integer
Converts to variant of subtype Long
Returns the cosine
Creates an server object.
Converts to variant of subtype Single
Converts to variant of subtype String
Returns the date according to the system.

ex:  date() returns: 5/31/2007
Note: This is the time of the server in the time zone of the server.  This is not GMT time.

Warning:  This value is only the Date and does not include the time.

Also see: Now(), Time()

Adds the time interval to date. The interval argument accepts the following values:

Interval options:
yyyy Year
q Quarter
m Month
y Day of year
d Day
w Weekday
ww Week of year
h Hour
n Minute
s Second


DateAdd("d",1,Now()) - adds one day.

Returns the number of intervals between two dates. The interval argument accepts the following values:

Interval options:
yyyy Year
q Quarter
m Month
y Day of year
d Day
w Weekday
ww Week of year
h Hour
n Minute
s Second

DateDiff("d",date1,date2) -> 31
Returns the designated part of the time. The interval argument accepts the following values:

Interval: Description:
yyyy Year
q Quarter
m Month
y Day of year
d Day
w Weekday
ww Week of year
h Hour
n Minute
s Second
Converts to subtype Date
Converts to subtype Date

Dim dateRegStartDate
dateRegStartDate = DateValue("31-Jan-02")
'  You may want to use this to convert a SQL results set value to a Date. 
'  This value does NOT accept a time value.
Returns the day of the month according to the argument
Raises e to the number of number.
Creates a new array according to the filter criteria.
Converts to integer (rounds up for negative numbers)
FormatCurrencyFormatCurrency(Expression [,NumDigitsAfterDecimal [,IncludeLeadingDigit [,UseParensForNegativeNumbers [,GroupDigits]]]])
Formats currency according to the settings of the server and the parameters given.
Formats dates and times.
Default format: mm/dd/yyyy
Default time: hh:mm:ss AM/PM

<% =FormatDateTime("4/17/07") %>  4/17/2007
<% =FormatDateTime("17:30") %>   Results: 5:30:00 PM
<% =FormatDateTime(Now()) %>  Results: 5/7/2007 12:41:28 PM
<%= FormatDateTime(Now(), 0) %> Results: 5/7/2007 12:37:47 PM
<%= FormatDateTime(Now(), 1) %> Results: Monday, May 07, 2007
<%= FormatDateTime(Now(), 2) %> Results: 06/01/2007
<%= FormatDateTime(Now(), 3) %> Results: 5:30:00 PM
<%= FormatDateTime(Now(), 4) %> Results: 17:30   Note: 24 hr clock
VBGeneralDate0Display the date and time using system settings
VBLongDate1Display the date in long date format
Tuesday, April 17, 2007
VBShortDate2Display the date in short date format
VBLongTime3Display the time in long time format
5:00:00 PM
VBShortTime4Display the time in short time format (24 hour clock)


FormatNumberFormatNumber(Expression [,NumDigitsAfterDecimal [,IncludeLeadingDigit [,UseParensForNegativeNumbers [,GroupDigits]]]])
Formats numbers.
FormatPercentFormatPercent(Expression [,NumDigitsAfterDecimal [,IncludeLeadingDigit [,UseParensForNegativeNumbers [,GroupDigits]]]])
Formats percentages.
Returns the specified Automation object from the specified file.
Returns the hexadecimal value of number.
Returns the hour according to the time argument.
Returns the first appearance of string2 within string1.

Return of 0 = not found.

start (optional) integer - The starting position for the search
compare (optional) integer - The type of string comparison. (0=Binary (default), 1 = Text (case insensitive))

Returns the last appearance of string2 within string1.
Returns an integer (rounds down for a negative number).
Determines whether a variable is an array

DIM myarray(1,2)
DIM myvariable
IsArray(myarray) = True
IsArray(myvariable) = False
Determines whether a expression can be converted to date format
Determines whether the variable has been initialized.
Determines whether expression is null.
Determines whether expression is a number.
Determines whether expression is an object.
Joins substrings in an array separated by the charcather indicated by delimiter.
Changes the string to lowercase.
Returns the left string portion of the designated length.
Returns the length of the string or the byte size of the variable.
Returns the natural logarithm of the number.
Removes extra spaces to the left of the string.
Returns a string portion of the designated length starting from the argument start.
Returns the minute according to the time argument.
Returns the month represented by the number.
Returns the month represented by the name.
Returns the current date and time according to the system.

Response.Write( Now() )
Ex: 5/31/2007 3:33:50 PM  (Date/Time of the server's time zone (not GMT) )

Also see: Date(), Time()

Returns the octal value of number.
Replaces the designated substring <find> with the substring <replacewith> the designated number of times.

strExample = Replace("Hello World example of remove spaces"," ","") - this will remove the spaces.

Returns the right string portion of the designated length. 
Generates a pseudo-random number.

Randomize  ' Needed for Rnd() to generate a true random number.
Rounds number to the specified number of decimal places.
Removes extra spaces at the right.
Reurns the name of the scripting language in use
Reurns the build version of the scriptengine in use.
Returns the major version number of the script engine.
Returns the second according to the time argument.
Returns the sign of the number.
Returns the sine of the number
Creates a string with the specified number of spaces.
Splits a string and converts it into an array.
Returns the square root of the number.
String comparison.
Creates a string with character repeated the specified number of times.
Reverses the charcters of a string.
Returns the tangent of the number.
Returns the current time according to the server clock

Also see: Date(), Time()
Returns Date Variant.
Returns Date Variant containing time.
Removes extra spaces at each side of a string
Returns the subtype by name.
Returns the upper bound of the array dimension. If no dimension is specified, the first dimension is used.
Changes the string to uppercase.
Returns subtype by value.

Value Description
0 Uninitalized (default)
1 Contains no valid data
2 Integer subtype
3 Long subtype
4 Single subtype
5 Double subtype
6 Currencey subtype
7 Date subtype
8 String subtype
9 Object
10 Error subtype
11 Boolean subtype
12 Variant (only used for arrays of variants)
13 Data acces object
14 Decimal subtype
17 Byte subtype
8192 Array
Returns the day of the week by number.
Returns the day of the week by name.
Returns the year according to the argument