Computers
Active Server Pages |
This is your ASP Cheat Sheet!
- General -- general information, including
tutorial websites
- Built-in Methods -- ways to communicate with the
outside world
- Text Manipulation -- including encapsulation
(quoting)
- Math -- and other functions
- Flow of control -- ifs, loops, functions, etc.
- Email -- sending email from an ASP script
General -- general information
Tutorial and Reference Websites
ASP
Tutorial For Beginners
General syntax
When you save a web page, name it something.asp to tell the server it
contains ASP code.
The default scripting language is VBScript. To use JavaScript for ASP
code, start the page with
<%@ language="javascript"%> (not
recommended, since this cheat sheet assumes VBScript)
Enclose ASP code in <% and %> -- everything in between is executed,
and then the server replaces it with the output of running the program.
Upper/lower case in built-in methods seems not to matter; however good form
is to "properize" all names
' Comments are set off by a single quote
Continuation: end each line but the last with underscore _
<!--#include file="filename.asp" -->
<!--#include virtual="filename.asp" --> -- includes the file (or
virtual file). Can only be used outside <%, %> delimiters.
Constants:
string -- "value"
hex number -- &hFF00FF (Magenta) -- note: colors are in
reverse order BGR
vbNewLine -- platform-specific newline character (Chr(10) or
Chr(13)&Chr(10))
date -- #May 10,2002#
Declaring a variable:
dim names(6),i -- declares an array variable, names, and a scalar
variable, i. Later, use it this way:
For i = 0 to 6 : response.write(names(i) & "<br />") : Next
Variable scope
variables declared outside a procedure are can be accessed and
changed by any procedure in the ASP file.
variables declared in a procedure are created and destroyed each
time the procedure is entered/exited.
Session variables -- used to store information about ONE single user, and are available to all pages in one application. Typically information stored in session variables are name, id, and preferences
Application variables -- also available to all pages in one application. Application variables are used to store information about ALL users in a specific application.
Variable type -- returned by VarType(variable) --
0 - vbEmpty -- Empty (uninitialized)
1 - vbNull -- Null (no valid data)
2 - vbInteger -- Integer
3 - vbLong -- Long Integer
4 - vbSingle -- Single-precision floating-point number
5 - vbDouble -- Double-precision floating-point number
6 - vbCurrency -- Currency
7 - vbDate -- Date
8 - vbString -- String
9 - vbObject -- Object
10 - vbError -- Error
11 - vbBoolen -- Boolean
12 - vbVariant -- Variant (Used only with Arrays)
13 - vbDataObject -- Data-access Object
17 - vbByte -- Byte
8192 - vbArray -- Array
Built-in Methods -- ways to communicate with the
outside world
response
response.buffer=true -- Use at the top of an ASP page. It means: Don't start sending the page until it is completely built. This is needed if response.redirect might be used later!
response.write text -- text is written to the user's browser, replacing the
ASP code in the page
response.redirect "http://" & v1 & v2 & v3 & v4 & v5 & v6 & v7 Redirect to another web page
Response.Cookies("cookiename").Expires=date+365 -- make the
cookie, "cookiename", expire in one year
Note: The Response.Cookies command must appear BEFORE the
<html> tag.
Response.Cookies("cookiename")=value -- store value in cookie,
"cookiename".
Response.Cookies("cookiename")("keyname")=value -- store
value in key "keyname" of cookie, "cookiename".
request
v1=request.querystring("v1") -- In "get" mode, get the value of the parameter, v1 that was sent via
http://webpage&v1=value&v2=value
use: if v1<>"" then : ... to see if the variable
was supplied
v2=Request.Form("fname") -- In "post" mode, get the
value of the parameter, v2, that was sent via a form.
use: if v2<>"" then : ... to see if the variable
was supplied
Request.ServerVariables ("HTTP_User-Agent") client browser type as a string.
Request.ServerVariables ("REMOTE_ADDR") client's IP (Internet protocol) address as a string.
Request.ServerVariables ("REMOTE_HOST") client's domain name as a string.
Request.ServerVariables ("SERVER_NAME") domain name of the server as a string. If the server has no domain name, returns the server's IP address as a string.
Request.ServerVariables("HTTP_REFERER") web page that directed you
to this page -- very handy for email scripts!
For Each Key in Request.ServerVariables :
response.write Key & ": " & request.servervariables(Key)
& " <br><br>" : Next -- a complete little program that lists the names and values of all the server variables
cookievalue=Request.Cookies("cookiename") -- get the value of the
cookie, "cookiename"
For Each x In Request.Cookies
If Request.Cookies(x).HasKeys Then '-- test whether each cookie
has keys
Response.Write("<p>")
For Each y in Request.Cookies(x)
Response.Write(x & ":" & y & "=" &
Request.Cookies(x)(y)) & "<br />"
Next
Else
Response.Write(x & "=" & Request.Cookies(x) & "<br />")
End If
Response.Write "</p>"
Next
Session
Session.Timeout=5 -- sets timeout to 5 minutes (default is 20 minutes)
Session.Abandon -- causes a session to end
Session("variablename")=value -- stores value in session variable,
"variablename".
x=Session("variablename") -- returns value of session variable,
"variablename".
For Each x in Session.Contents : Response.Write "Session variable "
& x & " = " & Session.Contents(x) & "<br>"
: Next
Session.Contents.Count -- returns the number of session variables
Session.Contents.Remove("variablename") -- removes a session
variable
Session.Contents.RemoveAll() -- removes all session variables
For Each x In Session.StaticObjects : Response.Write(x & "<br />") : Next
-- see all the session objects
Application and global.asa
Application variables are created in global.asa this way:
<script language="vbscript" runat="server">
Sub Application_OnStart :
Application("vartime")="" : Application("users")=0: End Sub
Sub Application_OnEnd: code to clean up after
last user : End Sub
Sub Session_OnStart : Application.Lock :
Application("users")=Application("users")+1 :
Application.Unlock :
Session("started")=now() : End Sub
Sub Session_OnEnd: Application.Lock :
Application("users")=Application("users")-1 :
Application.Unlock : End Sub
</script>
Application("variablename") -- returns value of variable, "variablename"
Application.Contents.Count, etc., work just as Session.Contents.Count, etc.
Application.Lock -- prevents other users changing the application's variables
Application.Unlock -- allows other users changing the application's
variables
Text Manipulation, encapsulation (quoting)
Built-in Functions
Asc(char), AscW(char) -- returns the ascii (or Unicode for AscW) value of the
given character.
Chr(n), ChrW(n) -- returns the character whose ascii code is n.
InStr(n,hay,needle,C), InStrRev(hay,needle,s,C) -- 1-based position (at or after
optional position n) of the first (last)
occurrence of needle within haystack or 0 if not
found; (C=0 for binary, C=1 for text-base comparison)
Ex: InStr(3,"abcdef","cde")=3.
InStr(100,"abcdef","cde")=0. Instr(0,"abcdef","cde")=Error
InsStrRev(4,"abcdef","cde")=0.
InsStrRev(5,"abcdef","cde")=3.
LCase(s), UCase(s) -- lower case (upper case).
Len(s) function is used to determine the length or number of characters in a string.
Left(s,n), Right(s,n) -- a number of leftmost (rightmost) characters of string
s.
Mid(s,n,l) -- returns the middle characters starting at 1-based position n,
length l. l=0 ok, l>Len(s) ok, n=0 Error, n>Len(s) ok.
LTrim(s), RTrim(s), Trim(s) function is used to remove leading / trailing / both
spaces from a string.
Replace(hay,needle,replacement,n,c,C) -- replace a specified substring (optional
position n, count c, compare-type C)
Space(n) -- creates a string including the specified number of spaces.
StrComp(string1,string2,C) function compares two strings and returns whether they are equal or not.
String(n,c) -- String of n c's. If c is string, only first character is
used.
Tip: to create multiple instances of a longer string, use Replace(String(3,"a"),"a","elephant")
StrReverse(s) -- creates a string in which the character order of a specified string is reversed.
Server Methods
Server.MapPath("readmetest.txt") -- converts virtual file to fully
qualified server filename
Math and other built-in functions
Prime number example
operators, expressions
eval(expression), (expression) -- evaluates the expression; needed with
& for concatenation
n = expression -- assignment
a+b, a-b, a*b, a/b, a^b -- addition, subtraction, multiplication, division,
exponentiation
a\b -- integer division
logical expressions, used in: if expression then : statements : end if
a=b, a<b, a<=b, a>b, a>=b, a<>b -- evaluate to vbTrue is
-1; vbFalse is 0
a And b, a Or b, a Xor b -- bitwise and, or, exclusive or.
"And" binds tighter than "Or", so use parentheses
Not a -- bitwise negation of a
time and date
t=Now() -- returns time of day
Hour(t) -- returns hour of day, from 0 to 23
other math functions
Abs(n) -- absolute value of n
Sgn() function is used to determine the sign of a number, i.e. whether it is greater than, equal to, or less than zero.
Sqr() function takes a number and calculates the square root.
Fix(n), Int(n),
Round(n,d) -- next-smaller, next-lower, or nearest: Int(6.2) is 6; Int(-6.2)
is -7; Fix(-6.2) is -6; Round(3.14,1)=3.1.
Randomize, Rnd(), Rnd(n) -- seed the random number generator, next random
number between 0 and 1,
Rnd(0)=same number again, Rnd(n) with n<0 = a particular
number using n as the seed
Abs(n) function returns the absolute value of a number, i.e. its unsigned magnitude.
Cos(n), Sin(n), Tan(n), Atn(n) function computes the trig function (angle in radians)
Exp(n), Log(n) function returns e (the base of natural logarithms) raised to a
power, and the natural log
FormatNumber(n,p,z,n,g), FormatCurrency(n,p,z,n,g), FormatPercent(n,p,z,n,g)
--
format n with precision p, tristate z for leading zero, tristate
n for negative parens, tristate g for comma grouping.
(tristate: 0=false, -1=true, -2=use VB default)
Hex(n), Oct(n) function converts a number or expression to a string
representing the hex (or octal) value.
RGB(r,g,b) returns r + 256g + 65536b
Flow of Control -- if's, loops, functions, etc.
If logicalexpression Then : statements : Else : statements : End If
Do While...Loop -- Do While n < 10 : response.write n : n=n+1 : Loop
Do Until...Loop -- Do Until n = 10 : response.write n : n=n+1 : Loop
Exit Do -- (And Exit For, Function, Property, or Sub) leaves the enclosing loop
or other unit.
For n=1 to 20 Step 2 : response.write n : Next n -- the variable after
"Next" is optional.
test is done first, so For n=2 to 1 will not even run once
after the loop is done, n will have been incremented (n=21 in this
case)
For Each x --
Dim names(2) : names(0) = "Al" : names(1) = "Bo" : names(2) = "Cal" :
For Each x In Names : Response.Write(x & "<br />") : Next
Select Case x : Case "Al" : stmt : Case "Bo" : stmt : Case
Else : stmt : End Select
Sub vbproc(num1,num2) : response.write(num1*num2) : End Sub
call vbproc(3,4)
Function vbfunc(a) : vbfunc=returnvalue : End Function
x=vbfunc(3)
Email -- sending email from an ASP script
Bamboo Example -- sends a message to
"feedback" (so it goes into the bit bucket). This has a problem
that the encoding is not text/html, so the html doesn't format the text as
expected.JMail Example -- sends a message.
JMail also has the ability to behave as a POP3 client to receive messages, read
them, and act on their contents.
For more info: JMail
Reference
|