Active Server Pages/Appendix A: Language Reference

Previous: Server-Side Includes Index  

Objectives edit

A reference for all of the keywords and statements used in Active Server Pages. Items are grouped by function and contain a short description and example of their usage.

Content edit

This contains a quick reference of all of the language elements in Active Server Pages.

Array Functions edit

Statement Purpose
Array This function creates an instance of an array. The arguments to this function are the elements you want to see the array with. It is possible to have no arguments at all.
aOption = Array("yes", "no", "unknown")
Erase Subroutine which clears all of the elements of the array. If the elements are numeric values, then they will all be set to zero. If the elements are strings then they will all be made empty.
Erase(aYear)
Filter Selectively include or exclude elements from an array. The optional third argument is a boolean which indicates whether items are included.
Filter(aArray, "remove", False)
Join Build a string by joining all of the elements in the array. A "glue string" is inserted between each element.
sCSV = Join(aArray, ",")
LBound Return the lower bound of an array meaning the smallest possible array index that may be used for the array. All arrays in ASP start with the index 0, so you shouldn't need to use this.
nStart = LBound(aArray)
ReDim Use this to re-dimension (or resize an array) after it has already been declared. If the Preserve keyword is used, existing elements will not be destroyed in the process.
ReDim Preserve aField(nCount + 10)
Split Takes a string argument and creates an array by "splitting" the string into multiple elements. Strings are split based on a "delimitter" which is passed as the second argument.
aName = Split("joe,bill,john", ",")
UBound Return the upper bound of the array meaning the last possible array index. This is often used to get the size of an array (which in turn can be used in For...Next loops to iterate over the elements)
nLast = UBound(aArray)

Variable and Procedure Declarations edit

Statement Purpose
Const Used to declare a constant value (a value that will never change over the course of the program)
Const PI = 3.1415926
Dim Used to declare a variable in your program. Variables can be declared as "global" meaning available to the entire script or as local variables (inside a procedure)
Dim I, J, K
Function Used to declare a function in your script. A function is a procedure that should return a value but this is not enforced in Active Server Pages.
 Function YearsOld(dBirthDate)
 	YearsOld = DateDiff("y", dBirthDate, Now())
 End Function
Sub Used to declare a subroutine in your script. A subroutine cannot return a value to the caller. You don't have to declare a function or subroutine before calling it.
 Sub HelloWorld(sName)
 	Response.Write "Hello " & sName
 End Sub

Control Flow Statements edit

Statement Purpose
Call Invoke a procedure (either a subroutine or a function). If used to invoke a function, the return value cannot be assigned (leave the Call keyword off if you want to do something with the return value)
 Call SayHello("Bill Gates")
 ' alternative way to call a subroutine (notice no parentheses necessary)
 SayHello "Bill Gates"
Eval Evaluate Active Server Pages code that is built dynamically. In other words, if you build a string (at runtime) containing ASP code, you can execute that code using Eval.
fArea = Eval("3.14159 * fRadius * fRadius")
Execute Execute an ASP script programatically. Allows you to execute an ASP page during runtime. Most normal methods of doing this (like using a server-side include) will process the script regardless of whether it is used or not. With Execute, you can conditionally process ASP scripts.
 if (nThemeNo = 1) then
   Execute("/theme/fantasy/header.asp")
 Else
   Execute("/theme/modern/header.asp")
 End If
Exit Used to break execution out of a function, subroutine, or many of the looping constructs.
 Exit Function
 Exit Sub
 Exit For
 Exit Do
 Exit While
Select Case This allows you to create a multi-branched conditional construct similar to a sequence of If Then ... Else If ... Else If ... Else ... End If.
 Select Case nDayOfWeek
   Case vbSunday : Response.Write "Day of Rest"
   Case vbSaturday : Response.Write "Shopping Day"
   Case vbMonday : 
   Case vbThursday : Response.Write "Dance Class"
   Case Else : Response.Write "Work is Fun!"
 End Select

Loop Statements edit

Statement Purpose
Do Loop There are two different variations of the do loop. Do While repeats a block of statements while a condition is true and Do Until repeats while a condition is false. You can exit out of a Do ... Loop statement by using the Exit Do statement.
Do While I < 0
  I = I + 1
Loop
Do Until rs.EOF
  rs.MoveNext
Loop
For Each When working with a collection, you can use this function to iterate over each item.
For Each sKey In oHash.Keys
Next
For Next Iterate over a sequence of numbers with a known start and end value and an optional increment value. You can force execution to break out of a For ... Next loop by using the Exit For statement.
For I = 1 To 10
  Response.Write " I = " & I
Next
For I = 10 To 1 Step -1
  Response.Write " I = " & I
Next
While Loop Repeat a block of statements while a condition is true. You can force execution to break out of a While loop by using the Exit While statement.
While I < 10
  Response.Write "I = " & I & "&lt;br&gt;"
  I = I + 1
  If I = 6 Then Exit While
Wend

Math Functions edit

Statement Purpose
Abs Calculate the absolute value of an expression (makes a negative result into a positive one)
x = Abs(y)
Atn Trigonometry function to calculate the arc-tangent of a value
x = Atn(y)
Cos Trigonometry function to calculate the cosine of a value
x = Cos(y)
Exp Calculates the value of the expression e ^ y where e is a constant representing the base of the natural logarithm (otherwise known as napier's constant).
x = Exp(y)
Fix Converts a number to an integer. Negative numbers are rounded up (instead of down which is how Int works). So a number like -5.99235 would result in a value of -5.
x = Fix(-5.66663)
Int Converts a numeric value into an integer value. It effectively does the same thing as the "Floor" function in that it truncates any fractional part of the number (not performing any rounding).
x = Int(y)
Log Calculate the natural logarithm of a number. This is often expressed in mathematics as ln(y)
x = Log(y)
Mod Calculate the modulus (or remainder) between two numbers. This is a boolean operator just like + or /. The result of 10 Mod 3 is 1, because 3 goes into 10 at most 3 times with 1 left over (3 * 3 = 9 and 10 - 9 = 1)
nRem = 10 Mod 3
Randomize Seed the random number generator. Doesn't return a value but prepares the script to produce truly random numbers via the Rnd function.
Randomize
Rnd A function which returns a random number that is greater than or equal to zero and less than 1. You shoud always call Randomize before calling this function.
x = Int(Rnd() * 100)
Round A function which rounds a number to the closest integer. So if the fractional part of the number is < 0.5, the number will be rounded down, otherwise the number will be rounded up.
x = Round(3.5)
Sgn Performs the sign function which returns only three possible values. -1 if the argument is a negative number, 1 if the number is positive, or 0 if the argument is exactly zero.
x = Sgn(-245.444)
Sin Trigonetry function which returns the sine function. The argument is the angle of degrees in radians.
x = Sin(90)
Sqr Calculates the square root of a number. The argument must be a positive number greater than or equal to zero.
x = Sqr(16)
Tan Trigonometry function to calculate the tangent of a value. The argument is the angle of degrees in radians.
x = Tan(1.331)

String Functions edit

Statement Purpose
Asc Return the ASCII code for a character (the first character of a string since there is no character subtype in ASP)
nAsciiH = Asc("Hello")
AscB Returns the first byte of a sequence of binary data. Binary data is typically used when manipulating files.
nByte = AscB(sInput)
AscW Returns the 32-bit wide (unicode) character code for the first character in a string
nAsciiH = AscW("Hello")
Chr Builds a single string (character) based on the ASCII code argument. This is how you can build a string containing non-printable characters. ASP contains many built-in constants which also serve this purpose (such as vbCr, vbLf and even vbCrLf).
sStr = "Hello World!" & Chr(13) & Chr(10)
FormatCurrency Formats a numeric value as currency according to the locale settings. The optional second argument indicates the number of places after the decimal point. In the United States, the default is two.
 sGasPrice = FormatCurrency(3.00)
 sNatlDebt = FormatCurrency(9065368997351, 0)
FormatNumber Formats a numeric value according the locale settings for the server. It may insert digit separator (like the comma in 3,932) or pad the number with zeros. An optional second argument indicates the number of digits to show after the decimal point.
 sPopulation = FormatNumber(9065368997351)
 sPI = FormatNumber(3.1415926, 4)
FormatPercent Format a number as a percentage value. Actually it converts a probability number from 0 to 1 into a percentage between 0% and 100%. An optional second argument indicates the number of digits shown after the decimal point.
 nPct = FormatPercent(0.5442)
 nPct2 = FormatPercent(0.5442542, 3)
InStr Find the first occurrence of one string within another. By default the search will do a case sensitive comparison. The first argument is the character index to start the search from. The second argument is the text to be searched (haystack) and the third argument is what you are looking for (the needle). The optional fourth argument allows you to specify the comparison type (like vbTextCompare or vbBinaryCompare)
nBeginPos = InStr(1, sText, "Begin", vbTextCompare)
InStrRev Find the first occurrence of one string within another starting from the end of the string and searching to the left. Unlike InStr, the optional position to start the search from is the third argument (instead of the first). The optional fourth argument allows you to specify the comparison type (like vbTextCompare or vbBinaryCompare)
 nScriptPos = InStrRev(sURL, "/")
 nProtocolPos = InStrRev(sURL, "http://", 100, vbTextCompare)
LCase Convert all alphabetic characters in a string to lowercase.
sUsername = LCase("WaCkYcAsEuSeR")
Left Return a substring starting from the left side (first character) of the base string.
sFirst = Left(sFullName, 10)
Len Given a string as the argument, returns the length of the string in characters.
nLen = Len("ASP")
LTrim Trim any whitespace that exists on the left side of the string. So if you give the function an argument of " Hi! ", it would return the value "Hi! ".
sFirst = LTrim("   Will")
Mid Get a subtring from a string. The first argument is the base string to extract the substring from. The second argument indicates the character index to start from. The last argument indicates the number of characters to extract. You may omit the last argument to retrieve all characters up to the end of the string.
 sMiddle = Mid(sFullname, nMidStart, nMidEnd - nMidStart + 1)
 sLast = Mid(sFullName, nLastStart)
Replace Replace all occurrences of the search string (argument 2) with the replacement string (argument 3) in the base string (argument 1) and return it.
sEscape = Replace(sSQL, "'", "''")
Right Return a substring starting from the right side (last character) of the base string.
sLast = Right(sFullName, 13)
RTrim Trim any whitespace that exists on the right side of the string. So if you give the function an argument of " Hi! ", it would return the value " Hi!".
sClean = RTrim("  Hi!  ")
Space Build a string with a repeated number of spaces. When displayed as HTML, the browser will compress all whitespace unless the text is preformatted (in a <PRE>...</PRE> block) or the content is delivered in plain text.
Response.Write Space(30 - Len(sFirst)) & sFirst
StrComp Compare two strings to see if they are equal or not. You may perform a binary (case sensitive) comparison (the default) or you can do a textual (case insensitive) comparison by passing the optional third parameter as vbTextCompare
if (StrComp(sFirst1, sFirst2, vbTextCompare)) Then Response.Write "EQUAL!"
String Creates a string by repeating a specified character a certain number of times. The first argument is the number of repetitions and the second argument is the string (character) to repeat.
 sLine = String(80, "-")
 sDblLine = String(80, "=")
StrReverse Take a string and reverse the order of the characters. In other words, given a string like "012345789", this function would return "9876543210".
sReverse = StrReverse("0123456789")
Trim Trim any whitespace that exists on either the right or left side of the string. So if you give the function an argument of " Hi! ", it would return the value "Hi!".
sClean = Trim("  Hi!  ")
UCase Convert all alphabetic characters in a string to uppercase.
sUsername = UCase("WaCkYcAsEuSeR")

Logic Statements edit

Statement Purpose
And Logical "AND" operations. Result is true only if both of the expressions evaluate to true, otherwise the result is False
If nScore > 80 And nScore < 90 Then sGrade = "B"
Eqv Test a pair of boolean expressions and return true only when both of the expressions evaluate with the same result (both are true or both are false).
If nScore > 60 Eqv False Then
If Then This evaluates an expression (resulting in a boolean true or false) and conditionally executes ASP code based on the resulting
 ' example of a single-line If...Then
 If nScore < 60 Then sGrade = "F"

 ' example of a multi-line If.. Then
 If nScore < 60 Then
   Response.Write "Sorry, You Failed"
 Else
   Response.Write "Congratulations, You Passed"
 End If
Imp The "implication" operator is used to determine whether A implies B. The result is always true unless A is true and B is false.
If bCondA Imp bCondB Then Response.Write "It Implies"
Is Use the is operator on variables containing objects to test if one object is the same as another (refers to the same instance). You can also use is to see if an object variable is set to nothing.
If oFile is nothing Then Response.Write "Nothing"
IsArray This function determines if a variable contains an array. Returns true to indicate it does, or false meaning it does not.
If IsArray(aVar) Then nCount = UBound(aVar) + 1
IsDate Test to see if the expression contains a valid date (either as a string which may be converted to a date using CDate or as date subtype)
If IsDate(dBirth) Then sBirthDay = FormatDateTime(dBirth)
IsEmpty Check to see if a variable (or an expression) contains an empty value. An empty value is the default value for variables which have been declared but never assigned.
If IsEmpty(sVar) Then Response.Write "You forgot to define the variable ""sVar"""
IsNull Check to see if a variable or an expression evaluates to null. This is particularly useful for database values retrievied using the ADODB component.
If IsNull(rs.Fields("lastname").value) Then bError = True
IsNumeric Check to see if a variable or expression contains a numeric value or can be converted to a numeric value using CLng, CInt, CFlt, or CDbl.
If IsNumeric(sAmount) Then nAmount = CInt(sAmount)
IsObject Test to see if a variable or expression refers to a valid object. An object can be created by calling the Server.CreatObject method.
If IsObject(oFile) Then oFile.Close
Not Perform a negation operation on a boolean expression. Gives you the opposite of either true or false.
bSad = Not bHappy
Or Boolean "or" operation takes two arguments which must be boolean expressions. Returns true if either expression evaluates to true, otherwise returns false.
 If bLovesSchool Or bLovesBoooks Then bIsSmart = true
 bIsSmart = (bLovesSchool Or bLovesBoooks)
Xor The exclusive or operator only returns true when exactly one of the boolean expression arguments is true. Returns false when both arguments are false OR both arguments are true.
 If (bLikesYankees Xor bLikesMets) Then bIsRealPerson = true
 bGiveCake = (bJoeWantsCake Xor bJuneWantsCake)

Date and Time Functions edit

Statement Purpose
Date Return the date according the local system clock. Does not return any time information, just the date.
dToday = Date()
DateAdd Add a specific number of time units to the supplied date.
dTomorrow = DateAdd("d", 1, Now())
DateDiff Calculate the number of time units between two date arguments.
Response.Write "Hours = " & DateDiff("h", dTomorrow, Now())
DatePart Extract a specific part of the datetime expression and return it. First argument may be "d" (day), "m" (month), "yyyy" (year), "q" (quarter), "w" (weekday), "ww" (week of year), "h" (hour), "n" (minute), or "s" (second).
nDay = DatePart("d", Now())
DateSerial Construct a date value from its individual components. The components are year (argument 1), month (argument 2) and day (argument 3).
dChristmas = DateSerial(2008, 12, 25)
DateValue Attempt to convert a string containing a date value into a variable with subtype date. If the date is not formatted properly, the script will fail with an error.
dChristmas = DateValue("12/25/2008")
Day Extract the day portion of a date expression. Shortcut for DatePart("d", dDate).
Response.Write "Christmas is on day " & Day(dChristmas)
FormatDateTime Format a datetime expression into human readable format. Format specifier (argument 2) may be one of: vbGeneralDate, vbLongDate, vbShortDate, vbLongTime, or vbShortTime.
sModified = FormatDateTime(dModified, vbGeneralDate)
Hour Extract the hour portion of a date expression. Shortcut for DatePart("h", dDate).
nHour = Hour(dChristmas)
Minute Extract the minute portion of a date expression. Shortcut for DatePart("n", dDate).
nMinute = Minute(dDate)
Month Extract the month portion of a date expression. Shortcut for DatePart("m", dDate).
nMonth = Month(dDate)
MonthName Returns the name of a month corresponding to a month number (1 to 12). The second argument is an optional boolean indicating whether the month name should be abbreviated (true) or not (false).
 sMonth = MonthName(Month(dDate))
 sMonth2 = MonthName(DateValue("12/25/2008"), true)
Now Returns a datetime value which corresponds to the current server time.
Response.Write "Today is: " & Now()
Second Extract the second portion of a date expression. Shortcut for DatePart("s", dDate).
nSecond = Second(Now())
Time Returns a time value using the current server time. The date is not included in this value (for that you should use Now).
Response.Write "Time Right Now: " & Time()
Timer Returns a floating point value with the integer portion indicating whole seconds (since Jan 1, 1970) and the fractional part indicating milliseconds.
 fStart = Timer()
 ' do some work here
 fEnd = Timer()
 fElapsed = fEnd - fStart
TimeSerial Construct a variable with a subtype of time using the supplied arguments. Arguments are: hour, minute, and second.
dTime = TimeSerial(23, 59, 0)
TimeValue Attempt to convert a string (representing a valid time value) into a variable with subtype time. Throws an exception of the string is not properly formatted (and unable to convert).
dTime = TimeValue("23:59:00")
Weekday Extract the day of the week (as an integer) for a datetime expression. The first day of the week is Sunday which is returned as 1. The last day of the week is Saturday which is returned as 7.
nWeekday = Weekday(DateValue("12/25/2008"))
WeekdayName Extracts the day of the week (as a string) for a datetime expression.
sWeekday = WeekdayName(DateValue("12/25/2008"))
Year Extract the year portion of a date or datetime expression. This is a shortcut for DatePart("yyyy", dDate).
nYear = Year(dChristmas)

Data Type Conversions edit

Every variable in ASP is a variant (meaning the language is not strongly typed), so when we talk about type conversions, we're talking about the subtype of a variant value.

Statement Purpose
CBool Convert a variable into a boolean type (which can only hold true or false)
bDone = CBool("true")
CByte Convert a variable into a byte type (integer from 0 to 255)
bByte = CByte("127")
CCur Convert a variable into a currency type. This is just like a decimal number in that extra care is taken to ensure that nothing is lost in rounding).
fMoney = CCur(Request.Form("LoanAmount"))
CDate Convert a variable into a datetime value. The expression may be a date, a time, or a datetime expression.
dBirthday = CDate(Request.Form("BirthDay"))
CDbl Convert a variable into a double type which is a double precision floating point number.
dVal = CDbl("23.3452e+04")
CInt Convert a variable into an integer type. An integer is a 2-byte signed value that is restricted to values between -32,768 to 32,767. Note that CInt() performs "Banker's Rounding"—it does not truncate the fractional portion. Use Int() to truncate variables to integers.
nIntVal = CInt(Request.Form("SATScore"))
CLng Convert a variable into a long integer type. A long integer is a 4-byte signed value that is restricted to values between -2,147,483,648 to 2,147,483,647. Note that CLng() performs "Banker's Rounding"—it does not truncate the fractional portion.
nLngVal = CLng(Request.Form("SerialNo"))
CSng Convert a variable into a floating point number (basically a float) which is also known as a single precision floating point number. Positive numbers are restricted to values between 1.401298E-45 to 3.402823E+38 and negative numbers are restricted to values between -3.402823E+38 to -1.401298E-45.
fTemp = CSng(Request.Form("Temperature")
CStr Convert a variable into a string value. This is often necessary when comparing two values where one is a different type.
if (CStr(nAge) = Request.Form("Age")) Then Response.Write "You're " & nAge
Hex Convert an integer number to hexadecimal equivalent. Hexadecimal is a "base 16" number with digits ranging from 0 to 9 and A to F. Hexagonal numbers are restricted to four-byte values so that converting a value of -1 results in the value FFFF.
sEnc = Hex(Asc("%"))
Oct Convert an integer number to its octal equivalent. An octal number is a "base 8" number meaning the digits range from 0 to 7.
sOct = Oct(123)

Object-Oriented Programming edit

Statement Purpose
Class Declare a new instance of a class by enclosing it between Class ... End Class. Contained inside the class may be member variable definitions, method definitions, and property definitions.
 Class Month
  Private String sName
  Private String nDays
 	
  ' constructor
  Sub Class_Initialize()
    sName = "Unknown"
  End Sub
  
  ' Abbreviation method
   Public Function Abbreviation
     Abbreviation = Left(sName, 3)
   End Function
  
   ' retrieve the number of days
   Property Get Days
     Days = nDays
   End Property
  
   ' assign the name for this month
   Property Let Name
     sName = Name
   End Property
 End Class
New Use this statement to declare a new instance of a class. The built-in class RegExp may be used to declare an instance of a regular expression object. You must use the Set statement when instantiating a new object.
 Set oRE = New RegExp
 oRE.Pattern = "\w+"
Private This is an access modifier which may appear before a member variable, method, or properety. Any entity marked private may only be accessed within the class definition itself.
Private String sName
Public This access modifer makes an entity public. So a public variable can be accessed using the "dot notation" from the instance of a class. Likewise for methods and properties. Note that Public is the default access modifier and you don't have to include an access modifier on all entities.
Public Function Abbreviation
Property Get The Property Get statement allows you to declare a read-only property to your class. This is similar to a function in that it returns a value. If you try to do assignment using this property (oMonth.Days = 31), the parser will throw an exception.
Property Get Days
Property Let Use this property definition to define an assignor method. This allows you to assign a value to a class property. How the assignor method is implemented is up to you, but it usually modifies one of the member variables.
Property Let Name
Property Set If you need to define a property which assigns the value of an object, you should define a Property Set method. To define a property which retrieves an object value, you can simply use Property Get.
 Property Set RegularExp
 
 Set oRE = New RegExp
 Set oMonth.RegularExp = oRE
Set Assign an instance of an object to a variable.
Set oRE = New RegExp
TypeName Use this function to retrieve the type of an object as a string. When used with a regular variable, it returns the subtype ("Date", "Double", "Integer", "String", "Boolean", etc.)
 ' another built-in object - Dictionary COM+ object
 Set oHash = Server.CreateObject("Scripting.Dictionary")
 ' this will return the string "Dictionary"
 Response.Write "Hash Type = " & TypeName(oHash)
With The With statement will save you some typing and allow you to access one instance of an object repeatedly by using a notation like .Write for the Response object. So instead of repeatedly typing Response.Write, you could do:
 With Response
   .Write x
   .Write " x "
   .Write y
   .Write " = "
   .Write z
 End With

Comments edit

Statement Purpose
' A line comment which commenting out all text up to the end of the line (or the end of the script block whichever comes first)
' This procedure does something
Rem Old style of making comments in visual basic. I believe this is only part of the language for backwards compatibility. It does the same thing as a single quote (') meaning that it does a line comment (commenting out all text up to the end of the line)
Rem This procedure does something

Error Handling edit

Statement Purpose
On Error The On Error statement is used to trap errors thus preventing the throwing of an exception. On Error must be terminated with an On Error Goto 0 to stop error trapping.
' trap all division error (overflow or divide-by-zero)
On Error Resume Next
f = x / y
If Err.Number <> 0 Then
   sError = Err.Number & " - " & Err.Description
End If
On Error Goto 0

Built-in Literals edit

Statement Purpose
Empty The default value of a variable before it has been assigned a value. You never explicitly assign this value to a variable but you can test for its existence using IsEmpty
IsEmpty(sFullname)
False Boolean value with a negative connotation. Similar to "No".
bIsCool = false
Nothing A special value that an object variable can be set to. Used to clear an object variable.
Set oFile = nothing
Null A null value is used to indicate that a variable holds no valid data. Primarily used when accessing the value of database fields.
If IsNull(rs.Fields("firstname").Value) Then ...
True Boolean value with a positive (or affirmative) connotation. Similar to "Yes".
bIsFun = true
Previous: Server-Side Includes Index