*These notes are based on information taken from random sources on the Internet, the author's personal knowledge, and SAMS Teach Yourself ASP 3.0 in 21 Days (good book). - 4/12/2024 |
varname = value
delcares a variable;
Dim
varname
;
<% option explicit
%>
;
<%= expression %>
equals:
Response.Write(expression)
. This shortcut only works
outside an ASP block;
<script language=lang runat=server>
</script>
results in server-side processing. However, stuff
inside the tag gets executed last, which is confusing, so better not to use
it;
<!-- comment
-->
in HTML, and with // in Jscript;
const VARNAME = value
). Use constants when
declaring a file size for comparison, a date, etc..;
vbDate
, vbInteger
,
vbBoolean
, vbString
, etc...
Day 3 - Working with Variables, Math
arrayname = Array("varname0", "varname1",
"varname2", ...)
;
vartype(varname)
returns an integer that corresponds
to the data type of varname
. (0 for empty, 1 for null, 2
for integer, 6 for currency, 7 for date, 8 for string, 9 for object, 10 for
error, 11 for boolean, 8192 for array)
typename(varname)
returns a string with the name of
the data type (eg "Integer" or "Boolean")
isvartype(varname)
returns a boolean value,
depending on whether varname
corresponds with
vartype
. vartype
can be
"numeric," "array," "date," "empty," etc...;
mod
. This returns a
remainder (eg, 5/3 returns 2). This is useful if you need something to behave
in a cyclical manner (0 mod
3 returns 0, 1 mod
3
returns 1, 2 mod
3 returns 2, 0 mod
3 returns 0, 4
mod
3 returns 1, 5 mod
3 returns 2...);
AND
(x and y are both true);
OR
(x or y is true);
NOT
(x is false);
XOR
(x or y is true, but not both);
EQV
(x and y are both true, or both false);
IMP
(x is false or y is true);If condition Then
codeblock End If
): you can use an
if/then/end if
statment, an if/then/else/end
if
statment (which can be nested; eg,
if/then/else-if/then/else
or
if/then-if/then/else
; the latter allows for "if x is true,
then check y [the next if], else z), an if/then/elseif
statement (just requires one "end if" at the end, as opposed to one for every
nested "if" statement. A mere time saver). Remember to always finish code
with End If
where appropriate;Select
Case expression
Case value1
code_block for when expression equals value1
Case
value2, valueN
code_block for when
expression equals value2 or valueN
Case
Else
code_block for when expression
matches no named value
. *note: this is good for
preventing errors*End Select
Do
While...Loop
) executes a block of code while certain
conditions are true. Do Until...Loop
executes until a certain
condition is met.Do While condition
code_block
Loop
code_block
is run at least
once by putting the "while condition" below
it:Do
code_block
Loop While
condition
Exit Do
) statement to end a loop abruptly.
This is often paired with an If...Then
;
While...Wend
) is similar to (Do
While...Loop
) - better not to use it;
For...Next
) is used when the number of times the code
should loop is known. counter
is a numeric variable that
keeps track of the loop. counter
begins at
startvalue
. It increases, each loop, by
stepvalue
. If you omit Step
stepvalue
, ASP will assume a value of one.For
counter = startvalue to stopvalue Step
stepvalue
code_block
Next
For Each...Next
) is used to iterate through each
element in a group:For Each item in
group
code_block
(item)
Next
Sub routinename
(arg)
*Note: arg is not
required* code_block
End
Sub
Function
functionname (arg)
code_block
End Function
Cint(expression)
casts
expression
to an integer. Floating-point is rounded,
number-like string is changed, True becomes -1 and False becomes 0, etc;
Clng(expression)
casts
expression
to a long (stays the same, basically?)
Cbyte(expression)
casts
expression
to a byte value (provided
expression
is between 0 and 255);
Cdbl(expression)
casts
expression
to a double (stays the same, basically?);
Csng(expression)
casts
expression
to a single (eg, 0.000556 returns 5.56E-04);
Cbool...
returns false if expression
is
zero, otherwise returns true. Expression
must be
numeric;
Ccur...
returns a currency value (negligable?)
Cdate...
returns a date value (eg, 4 returns 1/3/1900,
4.445 returns 1/3/1900 10:40:48 AM, "4-5-98" returns 4/5/98, "April-5-98"
returns 4/5/98, "2:23 PM" returns 2:23:00 PM, etc).
DateValue(expression)
and
TimeValue(expression)
function the same way. Note that the
format dates are displayed depends on your system settings;
Cstr...
returns a string. Basically, anything becomes
"anything"; FormatDateTime(expression, optional_argument)
- this is used to format date/time data. Optional_argument
can be one of five things:
vbGeneralDate
- displays date as short date and time as
long time. This is the function's default setting. It's value is 0;
vbLongDate
- displays date using long date format,
value is 1;
vbShortDate
- displays date using short date format,
value is 2;
vbLongTime
- etc, value is 3;
vbShortTime
- etc, value is 4; FormatCurrency(value, arg1, arg2,
arg3, arg4)
- this is used to format currency values.
Arg1
is the number of digits after the decimal place (-1
for default). For arg2-4
, a value of -2 = default, -1 =
on, -2 = off. Arg2
specifies whether to add the leading
zero to values that are less than one, arg3
specifies
whether to enclose negative values in parenthesis, and
arg4
specifies whether to use the delimiter to
group digits (in the U.S., the delimiter is a comma; FormatNumber(value, arg1, arg2, arg3,
arg4)
- works just like FormatCurrency
, minus the
dollar sign;
FormatPercent(value, arg1, arg2, arg3,
arg4)
- works just like FormatCurrency
, but
returns a percentage;Abs(number)
returns absolute value,
Int(number)
returns first integer less than or equal to
number
, Fix(number)
returns first
integer greater than or equal to number
,
Round(number)
rounds to nearest integer;
Round(number, dec)
rounds to dec
places after the decimal point;
Randomize
at the top of a page allows you to
call Rnd
, which will contain a random number less than one and
greater than zero. To change those bounds, call: (upperbound -
lowerbound) * Rnd + lowerbound
; Date
returns the current date. It can be stored in
variables or utilized/output as is;
Time
returns the current time. It can be stored in
variables or utilized/output as is;
Now
returns the current date and time;
DateAdd(interval, number, date)
adds
the number
of intervals
to the
date
specified. Interval
must
be put in quotes because it is a string. Interval
can
equal: yyyy (for year), q (for quarter), m (for month),
d (for day), ww (for week of year), h (for hour), n (for minute), s (for
second). DateAdd
will not return an invalid date - it'll
just try its best with what you give it. Make number
something negative (perhaps 1 - Weekday(date)
) to go
back in time instead of forwards;
DateDiff(interval, date1, date2,
first_dow, first_woy)
returns the number of
intervals
between date1
and
date
2. When operating, DateDiff
counts the
second date, but not the first. Intervals are same as for
DateAdd
. If date2
comes after
date1
, the return value is positive.
First_dow
and first_woy
are optional
- they let you specify what day is the first day of the week, and what week
is the first week of the year:
vbSunday
(value = 1; default);
vbMonday
(value = 2);
vbTuesday
(value = 3);
vbWednesday
(value = 4);
vbThursday
(value = 5);
vbFriday
(value = 6);
vbSaturday
(value = 7);vbFirstJan1
(value = 1; default);
vbFirstFourDays
(value = 2);
vbFirstFullWeek
(value = 3); DateSerial(year, month, day)
creates a date value that you can then stick into a variable. Use this if
year
, month
, or
day
are variables themselves, since you can't
simply write #month/day/year#.
DateSerial(99, 5, 1 -
3)
returns 4/28/99; in other words, three days before 5/1/99;
TimeSerial(hour, minute, second)
...etc;
Timer
returns the number of seconds elapsed since midnight;
DatePart(d_part, date, first_dow,
first_woy)
retrieves a portion of a date.
First_dow
and first_woy
are optional
(they let you specify what day is the first day of the week, and what week
is the first week of the year), and d_part
is a
string (as in interval
, DateAdd
).
Values are returned as a number.
Year(date)
returns the year portion from
date
(a number);
Month(date)
returns the month portion from
date
(a number);
MonthName(monthNumber, abbrev)
returns a
string with the name of the month. MonthNumber
ranges
from 1 to 12. Abbrev
is optional - if set to
true, it will abbreviate the returned string (eg, "Nov");
Day(date)
...etc;
Weekday(date)
...etc;
Hour(time)
returns the hour portion from
time
;
Minute(time)
...etc;
Second(time)
...etc; UCase(string)
returns string
with all its letters converted to uppercase;
LCase(string)
returns string
with all its letters converted to lowercase;
LTrim(string)
removes all spaces from left side of
string
;
RTrim(string)
removes all spaces from right side of
string
;
Trim(string)
removes all spaces from both sides of
string
;
Space(number)
returns a string consisiting of
number
spaces (not really useful, except for within
<pre> tags);
String(number, char)
returns a string
consisting of char
repeated number
times;
Len(string)
counts the number of characters in
string
;
StrReverse(string)
returns
string
with the characters in reverse order;
StrComp(string1, string2, comparetype)
is used to perform string comparisons. Omit
comparetype
to take into account letter case, otherwise
use 1 to ignore case. StrCompare
returns -1 if
string1
is less than string2
, 1 if
the reverse, and 0 if they are the same;
Right(string, number)
returns the
number
rightmost characters of
string
;
Left(string, number)
...etc;
Mid(string, start, length)
returns
length
characters from string
,
starting at position start
(length
and start
should be numbers);
InStr(start, string1, string2,
comparetype)
checks if and where string2
occurs within string1
.
Start
is optional; it determines where in
string1
to start looking.
Comparetype
is optional. InStr
returns 0 if the check fails, and returns the starting position of
string2
within string1
if it
succeeds.
InStrRev(string1, string2, start,
comparetype)
works in reverse (ie, checks from right to left).
Start
is -1 by default. Character positions (in return
values) are still numbered from left to right, though;
Replace(string, find, replace, start,
count, comparetype)
is used to replace occurences of
find
with replace
in
string
. Count
is -1 by
default (replace every occurence). Remember to put commas in place of
start
, count
, or
comparetype
if you want to use one, but not the other;
Filter(arrStrings, SearchFor, include,
comparetype)
searches the array,
arrStrings
, for SearchFor
, and
returns a subset of the array. Include
can be true or
false - true returns strings that match, false returns strings that don't
match;
Split(expression, delimiter, count,
comparetype)
splits a string into an array of strings.
Delimiter
indicates what is used to separate the
intented sub-strings in expression
(its default is the
space), and can be more than one character. Count
limits
the number of sub-strings that will be created (default is -1, for no
limit);
Join(stringarray, delimiter)
takes an array
of strings and joins them into one string, using
delimiter
to separate them (default is, again,
the space);
LBound(array)
returns the smallest valid index for
array
. This is normally 0;
UBound(array)
returns the largest valid index for
array
. This is the index of the last element in the
array;
For iIndex = LBound(myarray) to UBound(myarray)...
;
Asc(string)
returns the ANSI code for the first
character of string
;
Chr(integer)
returns the opposite of
Asc
. Use Chr
to access and print characters that
otherwise aren't on the keyboard, like the copyright symbol:
Chr(169)
;
ObjectVariableName.Property
;
ObjectVariableName.Method
;
Response
- used to send output. Response
also
controls how and when data is sent, and do stuff with cookies;
Request
- used to retrieve data from the client.
QueryString
data (seen at the end of URLs) is an
example of a request object;
Application
- used to share information among several
clients visiting the same group of pages. Application
refers to all the .asp pages in a directory and its subdirectories.
One instance of this object is created and shared among all clients;
Session
- refers to a single client accessing an
application. A new instance is created for each session, and carries
information between pages for client;
Server
- has a few basic properties and methods: the
CreateObject
method is used to create an instance of a server
component (a server component is a package of related objects). To
use: Set ObjInstance =
Server.CreateObject("Class.Component")
. The
ScriptTimeout
property can be used to specify the length of
time a script may be allowed to execute before an error occurs. To
use: Server.ScriptTimeout = seconds
. The
HTMLEncode
method replaces reserved HTML characters in a string
with their ASCII equivalent. To use:
Server.HTMLEncode(string)
. URLEncode
does the
same for URLs. The MapPath
method coverts a virtual path into a
physical path. To use:
Server.MapPath(virtual_path)
;
ObjectContext
- used to link ASP
and the Microsoft Transaction Server (MTS).
ASPError
- allows you to obtain information about script
errors in your pages. QueryString
(a collection in the Request
object). If you have an object instance named Texas
that
contains a collection named Cities
, and
Cities
contains a pair named "Capital
", you
can find the corresponding value using the Item
method -
Texas.Cities.Item("Capital")
. Item
is the default
method for collections, so you can omit it. You can also access values in a
collection by using an index number, as in arrays. Collection indexes,
however, start at 1 (as opposed to zero). Use:
Object.CollectionName.Count
when counting through a
collection with an unknown number of pairs.
Class
classname
public
propertyname
private
propertyname
public Sub
methodname(args)... End Sub
private
Function methodname(args)... End Function
etc...
End Class
Set variablename = objectexpression
.
Objectexpression
is either the name of an object, another
instance of the same object type, or the keyword New
followed by
a class name. (eg, Set MyCar = New Car
).
Color
property of instance MyCar
(object Car
) like this: MyCar.Color = "blue"
;
Sub
and Function
methodname(args)...
);
Set objectinstance = Nothing
to free up
system memory, once an instance no longer needs values;
Initialize
(generated when an instance of an object is created)
and Terminate
(...when destroyed). Creating a method in a
class statement called Class_Initialize
will result in that
method's code block automatically activating when an instance of that object
is created. Response
is used to send output to the client. The
Write
method sends HTML to the browser.
Response.Write
can be expressed both with parenthesis and
without;
Response.Write
expression cannot contain
"%>
". If you need to write that, use "%\>
". In
addition, the expression cannot contain double quotes. To get around this, use
single quotes, or use double-double quotes (eg, "");
<%=
shortcut for the Write
method. You'll have to close and re-open the VBScript brackets around it;
<% Response.Buffer = vbBoolean %>
at the top of
your script to enable or disable buffering. True = enabled. Buffered output is
cached and not sent until the script is finished, unbuffered output is sent
immediately;
Response.Clear
causes the buffer to be wiped out;
Response.Flush
flushes all the data from the system buffer,
but sends it to the client first. This is useful for sending blocks of data
to the client (to avoid making them impatient);
Response.End
ends the execution of a script. Buffered data
is sent, and any remaining statements are not carried out. This is not a
good way to end things (end tags like </HTML> won't be sent, etc), but
is useful in cases of error detection;
<META
HTTP-EQUIV=REFRESH CONTENT="#;URL=www.something.com">
(# = number
of seconds to wait before redirect) and Response.Redirect
URL
. The latter must come before all other output, or it won't
work. (Note - every time a client requests a particular ASP page, an object
context is created. This holds things like Session
and
Request
objects and some server variables.
Response.Redirect
creates a new object context;
Response
includes a collection called Cookies
that can be used to write cookies;
Response.Expires = Number
tells the browser that the
cached version of the page should expire after Number
minutes. Response.Expires = -1500
tells the browser not to
cache the page. Remember to be careful when choosing specific expiration
times; your server clock may be faster or slower than the client's;
Response.ExpiresAbsolute = Date Time
makes
the page expire after a certain date and time. (Put pound signs on left of
date, and right of time, nothing in between but space). If Time
is ommitted, the page expires at midnight;
Response.Status = "401 Not Authorized"
, for example. Other codes:
"302 Object Moved" and "404 Object Not Found"<form>
- defines a form. Its action
attribute gives the URL of the application that will receive the data (put URL
in quotes). Form-processing aps ususally go in a directory named
cgi-bin;
enctype
attribute should be included with a
value of "text/plain" if the action
attribute will contain a
mailto, and with "multipart/form-data" if the form will be used for file
uploading. In both cases, the method
attribute must
be set to post;
method
attribute determines how form data will be
sent to the server. If set to GET, it will be sent through the querystring. If
set to POST, it will be sent in a separate transmission. Small forms with a
few short fields should be sent via the GET method. If security is an issue,
select POST;
action
attribute, use javascript to
inform a user that their form has been processed (they won't know otherwise);
input
tag is used to define most of a form's possible
controls. It has two required attributes: type
and
name
. The type
attribute can include:
text
- defines a text entry field. The
size attribute determines the width of the display field (in chars),
the maxlength
attribute determines how many total characters to
accept from the user, and the value
attribute puts a
pre-selected value into the field;
password
- simply a text field that masks user input
as it is being typed;
file
- opens a dialog box that allows users to
select a file. Use the accept
attribute to constrain the types
of files that the user can select - its value is a comma-separated list of
MIME encodings. Remember to change the enctype
attribute to
"multipart/form-data";
checkbox
- requires the value
attribute. The optional checked
attribute (no value) will start
a box off as checked. After closing the input tag, you should write what you
want the user to see as the value of the checkbox;
radio
- requires the value
attribute.
Every radio button in a group should have the same name
. One
member in a group may contain the optional checked
attribute;
submit
- has no required attributes; it will simply
submit a form's values to the URL specified by action
.
Specifying a value attribute will change the submit button's label,
specifying a name
and value
attribute will (in
addition), send the extra name/value pair along with the rest of the form's
name/value pairs;
reset
- has no required attributes. You can change
the button's label with the value
attribute;
hidden
- requires the value
attribute.
This is simply a way to hide a name/value pair in a form. If you want to get
information from one form into another (without making a user re-type it),
this is a good way; textarea
tag creates a mutiline text entry area.
Body content will flow above and below but not around a textarea
box. Control height (in rows) and width (in characters) with the
rows
and cols
attributes. To make text in a
textarea
wrap, include the wrap
attribute.
Setting wrap to virtual
will cause the text to be transmitted to
the server exactly as it was typed (with line breaks only where the user
pressed "enter"). Setting it to physical
causes text to be
transmitted the way it looks to the user;
select
tag, with its option
-tagged
items, creates a pull-down or scrolling menu. The multiple
attribute lets a user choose more than one item in the menu. The
size
attribute determines how many items in the menu are visible
at once - anything more than one will result in a scrolling menu. The
select
tag gets the name
attribute, the
option
tags get the value
attributes; Day 9 - Collecting the Form Information
Request.Form(variablename)
collection to retrieve its
values. When set to GET, you use the
Request.Querystring(variablename)
collection.
Variablename
should be equal to the name property of the
relevant form field. You can also simply use
Request(variablename)
- this only fails if a
name
is used in both a page's querystring and a form;
Response.Redirect
can be used in conjunction with list boxes
(menus) as a navigational tool. The value of each option should be set to a
URL, and the action
value of the form should be set to an ASP
file called "redirect.asp", or something;
name
(different
values), and a user selects more than one checkbox, the named group is
returned as a comma-delimited list. You can:
split
function to turn that list into an array.
After that, you can use loops to determine what has or has not been checked
(pg 277), or whatever. Note that comma-delimited lists are spaced, so
splitting one will leave a leading space on each item in the array (except
for the first). You will have to trim it off;
name
(same value), and then
use multiple "If" statements to parse through the results; For Each varname In
Request.Form
to rotate through the results. varname
represents
the name aspect of a pair; Request.Form(varname)
represents
the value aspect of a pair. Day 10 - The Request Object (& Cookies)
Response.AddHeader
method
(Response.AddHeader HeaderName, HeaderValue
) allows
you to send a custom response header;
HTTP_ACCEPT
- a list of MIME types the client will accept;
HTTP_ACCEPT_LANGUAGE
- what languages the browser expects;
HTTP_CONNECTION
- the type of connection established
between client and server;
HTTP_HOST
- the hostname of the client computer;
HTTP_USER_AGENT
- the browser type and version, and
operating system of client;
HTTP_REFERER
- the full URL of the web page containing the
hyperlink used to reach the currently executing ASP page;
HTTP_COOKIE
- the cookies sent from the browser; Request.ServerVariables
to read the above headers. To
display all headers, use Request.ServerVariables("ALL_RAW")
. For
a formatted list, use ("ALL_HTTP
"). For a specific header, use
("HTTP_headername
");
USER_AGENT
header follows these standards: Both IE and
Netscape begin their USER_AGENT
headers with the word "Mozilla."
Netscape follows that with a forward slash and version number (Mozilla/4.61).
IE follows that with a string of parameters, including "MSIE" followed by a
version number;
Request.ServerVariables
, *all* are loaded into the collection.
So, don't use the collection except when you must;
URL
- the URL of the ASP page from after the domain name up
to the questrystring;
PATH_INFO
- same as URL
;
PATH_TRANSLATED
- the full, physical path of the ASP page;
APPL_PHYSICAL_PATH
- the physical address of the Web's root
directory;
QUERY_STRING
- equivalent to Request.QueryString;
SERVER_NAME
- the web server's computer name;
SERVER_SOFTWARE
- name of the web server software; Request.ServerVariables(environmentVariable)
to
read the above variables;
CERT
" will be empty unless the client and
server use certificates;
SERVER_NAME
and URL
variables (in that order) to retrieve the full URL of an ASP page; cookies
collection to maintain state over long
periods of time. Cookies are stored and read using the HTTP headers; each time
the browser requests a web page, it send the cookies that the current website
created. Cookies can contain any data except for arrays and objects. Cookies
can optionally have a set of keys that each store information.
Request.Cookies(cookieName)(keyName)
, write cookies
with: Response.Cookies(cookieName)(keyName1) =
value
;
Request.Cookies(cookieName).HasKeys
to determine
if a cookie has keys;
Response.Cookies(cookieName).Expires = dateValue
,
otherwise a cookie expires when the client closes their browser. Note that
dateValue
can be something like (Date + 5
) - the
cookie would expire 5 days from this day;
Domain
property to change what web site can
read a cookie, and the Path
property to change what ASP pages
(eg, in a certain path) can read a cookie;
Secure
property (set to "True") to prevent a cookie
from being sent without the HTTPS protocol;
If Len(Response.Cookies(cookieName)) = 0
Then
...;
Request.Cookies
is a collection. That means you can
call it, without arguments, to get a list of all cookies (eg, by doing
For each varname in Request.Cookies
...) Day 11 - The Session and Application Objects (+ QueryString shortcut)
<a href =
"http://3gwt.net/dje/somepage.asp?<%=Request.QueryString%>"></a>
Session
object is used to maintain state on a
person-by-person basis, for the duration of a user's visit to the website. It
can store arrays and objects; however, all Session
variables for
each user are stored in the web server's memory, so this should not be used in
sites with many concurrent users. Create session variables as follows:
Session(variableName) = value
;
SessionID
, is stored (as a cookie) on the
user's machine (it can be found in the Cookie header). Call it with
Session.SessionID
. Note that if the webserver restarts, duplicate
SessionID's may be created;
Session.Timeout
=
time_in_minutes
. This value should probably never be
higher than 20 minutes, or so. Destroy a session instantly with
Session.Abandon
;
Session
, use: Set
Session(variableName) = Server.CreateObject(ObjectName)
;
Session
object contains two collections:
Contents
, which contains all non-object variables, and
StaticObjects
;
Count
property can be used on the Session
object (eg, Session.Contents.Count
returns the number of
variables in Contents
);
Cookie Munger
will simulate cookies, so that you may use the
Session
object with users that disable them. However, it is very
intense for the web server, and should only be used on low volume sites;
Day 12 - Working with Common ASP Components
Set
objComponent =
Server.CreateObject("classname.componentname")
. Components in
this section have the classname "MSWC" - derived from the package the
components come in;
Set objComponent = Nothing
; REDIRECT
URL
WIDTH pixel_width
HEIGHT
pixel_height
BORDER
border_thickness
FirstImageURL
HomePageURL
AltText
Weight
SecondImageURL
...
HomePageURL
;
Weight
should be between 0 and 10,000;
REDIRECT URL
) will be
called with:
redirect_URL?URL=HomepageURL&image=ImageURL
,
and will look (at simplest) like: <%
Response.Redirect(Request.QueryString("url")) %>
If ObjBC.Browser = "Netscape"
Then
...; Day 13 - Reading and Writing Files on the Web Server (+ Code Insertion)
<!--#include virtual="fullpath/something.asp"-->
;
Server.Transfer
and Server.Execute
are new methods to IIS 5.0 that also enable code insertion;Server.Execute(path)
executes the ASP script
specified, and can be placed anywhere in a page. It's better than server-side includes
because it can be used conditionally, it is worse because it can't make use of
procedures or page-scope variables in the calling page;
Server.Transfer(path)
transfers control to another ASP
page without requiring another network trip between client and server. In addition, it allows you
to access any Form and Querystring values available to the calling page. However, if you want
a new object context (ie, so you can pass a new value through the querystring), don't use this - use
Response.Redirect
. In addition, Server.Transfer
may break
the relative links on the page you transfer to, so beware;FileSystemObject (instantiate with: Set objFSO =
Server.CreateObject("Scripting.FileSystemObject")
:
FileExists
and FolderExists
return "True"
if the target is found (If objFSO.FolderExists(path) Then...
).
You must remember to instantiate FileSystemObject
before using
these or any other methods for it. Also, be sure to use
Server.MapPath(path)
to convert a virtual path to a
physical address;
GetFile
method (of objFSO
) is used to
instantiate the file object. Set objFile =
objFSO.GetFile(Server.MapPath(path/file))
. objFile has its own
set of methods:
Attributes
- used to set and return some of the
special attributes of the file;
DateCreated
- returns the date and time the file
was created;
DateLastAccessed
- returns the data and time the
file was last accessed;
DateLastModified
- ...;
Drive
- returns the letter of the drive the file
is on;
Name
- used to set or return the name of the file;
ParentFolder
- returns an instance of teh folder
object corresponding to the parent folder of the file;
Path
- returns the path for the file, including
its filename;
Shortname
- returns the version of the filename
that is used by programs without support for long filenames;
ShortPath
- ...;
Size
- returns the size of the file, in bytes;
Type
- returns info that is known about the file's
type; GetFolder
method (of objFSO
) is used to
instantiate the folder object:
Files
- erturns a collection consisting of all the
file objects contained in the folder;
IsRootFolder
- has a value of True if the folder
is the root folder of the current drive;
Subfolders
- returns a collection of all folder
objects within this folder; Set
objOpenFile = objFSO.OpenTextFile(filename, mode,
create, format)
. mode
has three possible
values - ForReading (1), ForWriting (2), or ForAppending (8). If
filename
is not found, a value of True
(in the
create spot) will create it (the default is false
).
format
indicates whether to open the file as ASCII or
Unicode (-2 for default, 0 for ASCII, -1 for Unicode);
Set objOpenFile =
objFile.OpenAsTextStream(mode, format);
Set objNewFile = objFSO.CreateTextFile(filename,
overwrite, format)
;
objOpenFile.Close
; Read(numcharacters)
method.
numcharacters
is an integer specifying the number of
characters to be read in: objOpenFile.Read(10)
, for
example. Successive Read
commands will pick up where the last
one left off, eventually using up all the characters in a file and returning
an error;
AtEndOfStream
is a property of the text stream object. Its
value is True
if you are at the end of the text;
ReadLine
method returns a string consisting of an
entire line from the file;
ReadAll
method returns a string containing the entire
file;
<pre>
and
</pre>
tags is a good idea - it will maintain the
formatting of the text file; Write
method:
objOpenFile.Write("your text")
;
WriteLine
method writes a string to a text file and
then adds a carriage return. With no argument, it simply adds a carriage
return;
WriteBlankLine(number)
writes
number
carriage returns to the file; ForWriting
), you
destroy its old version. Use ForAppending
(when opening the
file) to avoid this; Day 14 - Debugging ASP Scripts and Handling Errors
ASPError
object to determine what will happen when a
bug appears. (Instantiate with Set ojbASPError =
Server.GetLastError
)To specify what action should occur, load the
Internet Information Services program in Windows 2024. Right click the website
you want to configure, select properties, select the Custom Errors tab, then
edit the properties of an HTTP error. 500;100 is the error you want to
change (other major error: 404; happens with broken links).
ASPError
properties include:
For
control
structure, or calling a function with an incorrect number of parameters...;
Response.Flush
, or if you have
Response.Buffer = False
, the custom error page won't be loaded;
something.mdb
. Choose
Create Table in Design View. Enter the columns for the table into the rows
of the resulting matrix (their name, data type, and description);
Text
(255 alphanumeric
chars or less), Memo
(65k chars or less), Number
(numeric values), Date/Time
, Currency
(supports up
to four digits of decimal precision), Yes/No
(for columns that
can have one of two values), Autonumber
(automatically
increments to uniquely identify each row). Note that these data type names
don't perfectly match those of other database programs - you'll have to
learn theirs also;
Connection
object and Recordset
object Day 16 - Reading from a Database Using ASP
Connection
,
Recordset
, Error
, Field
,
Command
, and Parameters
; Connection
object is used to hold information
about the data store you want to access. It is part of the ADOBD package.
(Set objConn = Server.CreateObject("ADODB.Connection")).
If using multiple Access databases, or mixing Access and other databases, you
would use multiple instances of the Connection
object;
something.dsn
for the Data Source Name. You
will use this to reference the DSN in ASP pages. Click Select, and choose
the .mdb file for the database. Click Ok, three times; objConn.ConnectionString
= "DSN=something.dsn"
objConn.Open strUsername,
strPassword
-or-objConn.Open "DSN=something.dsn", strUsername,
strPassword
-username and password
are used if the host requires it;
"DSN=something.dsn"
in a DSN-less
connection with:
"DRIVER={Microsoft Access Driver (*.mdb)};" &
"DBQ=PhysicalPath\something.mdb"
objConn.ConnectionString = "Provider=ProviderName; Data
Source=DatabaseSource; Initial Catalog=DatabaseName; User
ID=UserID; Password=Password"
Provider=SQLOLEDB; Data Source=myMachine; Initial
Catalog=something; User ID=; Password=
Provider=Microsoft.Jet.OLEDB.3.51;
Data
Source=c:\inetpub\wwwroot\something.mdb
Set objConn
and objConn.Open
in a file
called DatabaseConnect.asp, for inclusion into all pages that access the
database. However, don't forget to explicitly close and free the
Connection
object, just because you didn't have to manually open
it;
objConn.Close
Set
objConn = Nothing
Properties
collection of the Connection
object (objConn.Properties
) contains an instance of the
Property
object for every property supported by the connection;
Recordset
object is used to contain all the
records in a table, or a subset of those records: Set objRS =
Server.CreateObject("ADODB.Recordest")
;
Open
method: objRS.Open source, connection,
cursortype, locktype, commandtype
;
source
- either a command object or a string that
relates to commandtype ("mytable");
connection
- either a Connection object or a string
containing the connection information;
cursortype
- indicates the way you want to move
through the recordset. Default is the ADO constant
adOpenForwardOnly
, which means you can only move forward;
locktype
- affects whether you can write to the
table, and if so, how. Default is adLockReadOnly
, which makes
the table read-only;
commandtype
- indicates how the source parameter
should be evaluated. adCmdTable
indicates that source is a
table name; Recordset
object, then opening it (with the
connection
parameter correctly set to everything that
would go into the Connection
object's
ConnectionString
); adovbs.inc
file to use them. Copy it from c:\Program
Files\Common Files\System\ado\ and
paste it into your Web root directory. Then you can use: <!--#include
virtual="/adovbs.inc"-->
;
<!--METADATA TYPE="TypeLib" File="\msado15.dll"-->
(you must put msado15 in your root web, first). You can put this statement
into your global.asa
; Recordset
object with the following methods
(objRS.method
):
MoveNext
- advances to the next record;
MovePrevious
- goes back one record;
MoveFirst
- moves to the first record, even if
adOpenForwardOnly
is set;
MoveLast
- goes to the last record;
Move number
- skips ahead (or back)
number
records; BOF
property tells you that you are at the beggining of
the recordset, EOF
signifies the end. They are boolean values.
These properties are very important - use them to avoid errors when looping
forwards or backwards through a recordset (eg, Do While Not
objRS.EOF
);
objRS("FieldName")
returns the value of
FieldName
in the current row of the recordset;
If
objRS.EOF Then (Reponse.Write "error message") Else (database
operations...)
; Nothing
) both objConn
and objRS when you are done with them!!!
Day 17 - Inserting, Updating, and Deleting Database Records (with the Recordset object)
locktype
can be set to
adLockOptimistic (value of 3), which signifies that records will be locked
when Update
is called;
Recordset
enable you to make changes to a
database: AddNew
(creates a new record once Update
is called) and Update
(makes changes take effect). When
AddNew
is called, the new record becomes the current record. Use:
objRS.AddNew field,
value
objRS.Update
-or-
objRS.AddNew
(*Note: you can skip this line, and it'll still
work*)
objRS(field) =
value
objRS(field2) =
value...
objRS.Update
objRS.CancelUpdate
. This only works if
Update
has not been called yet;
objRS.Delete
. This is good for cancel
membership type functionality...;
Day 18 - Examining the Recordset Object
Recordset
object
represents a particular property of the object. Each row in a database table
or Recordset
object represents and instance of the object;
Recordset
object is represented by a
collection that contains as many elements as there are columns in the matrix,
referred to as the Fields
collection. Each value in the
collection is referenced by the column name;
Fields
collection is referred to as a
Field
object. The Value
property of that object (the
default property) contains the actual data of that cell in the table. When you
use objRS(field)
, you are actually using
objRS.Fields(field).Value
;
Field
object, the
Fields
collection should be referenced explicitely. These
properties are:
Count
property of the Fields
collection
returns the number of elements in the collection (columns in the table);
Fields
collection can be accessed by index, starting with
zero:
For iLoop = 0 to objRS.Fields.Count - 1
codeblock
obRS.Fields(iLoop)
Next
-or-
For
Each strName in objRS.Fields
codeblock
objRS.Fields(strName??)
Next
objRS.Open Source, ActiveConnection,
CursorType, LockType, Options
.
CursorType
determines what type of database cursor will be used.
adOpenForwardOnly
(known as a fire hose cursor) is
default. adOpenStatic
, adOpenKeyset
, and
adOpenDynamic
cursors are all scrollable database cursors, and
can move backwards through the recordset. While the Static cursor is
opened, rows in objRS will not update if changed. While the Keyset
cursor is open, they will. While the Dynamic cursor is opened, even new
rows will be added to the table will be updatted. Note - Access does not
support the Dynamic cursor;
objRS.CursorLocation = adUseClient
; on the server-side, omit,
or: = adUseServer
. When using a client-side cursor, all rows in
the Recordset
object are copied to the client's machine! You can
only use the adOpenStatic
cursor when working on the client-side;
objRS.Sort = field
.
Unfortunately, this can only be done on the client-side. The Sort
method sorts in ascending order by default. Append DESC to the field you are
sorting (eg, "field DESC");
If objRS(field) > numericValue
Then...
If
objRS.Filter = "field > numericValue"
(*Note - this is global, former is local*) Filter
property works with any logical statement (note -
logical operators are restricted to AND, NOT, and OR);
Filter
, you must put single quotes around string
or date column values in the equation (eg, objRS.Filter = "Symbol =
'MSFT'"
); Day 19 - Using SQL Statements to Query Data
objRS.Open
SQLStatement, ActiveConnection, CursorType,
LockType
. Before this, you must set:
SQLStatement = SELECT_statement
.
SELECT_statement
has the following form (words in all
caps are referred to as clauses):
SELECT selectList
(contains a comma-delimited
list of columns)FROM TableName
(name of the
table containing the data)WHERE
searchClause
(optional: contains logical
statements correlating columns and values)ORDER BY
orderExpression
(optional: will sort by
column and/or by ASC|DESC) selectList
is "*"
, then all columns
are obtained;
WHERE
clause,
use parenthesis. Without parenthesis, note that NOT
takes highest
precedence, followed by AND
, followed by OR
;
WHERE
clause, you must surround
the variable you are comparing the column to in single quotes;
LIKE
operator can be used in the WHERE
clause to search for patterns in strings:
%
-Translates to any string of zero or more chars;
_
-Translates to exactly one char;
[]
-Translates to any specific char within a certain
range;
WHERE ColumnName LIKE 'M%'
(this returns all items in ColumnName
that start with
the letter "M"). WHERE ColumnName LIKE '[a-f]ouse'
(this
returns all items with "a" through "f" as their first char, and "ouse" as
the rest); ORDER
clause is placed before the WHERE
clause, an error will result; Day 20 - Advanced Database Techniques
cursortype
attribute of objRS.Open
should be set to adOpenForwardOnly
if possible. If you need to
move backwards through objRS
, however, the other cursor types are
necessary. In addition, with adOpenForwardOnly
, you cannot
determine the number of records in a Recordset
before looping
through that entire Recordset
. To avoid this, set
cursortype
to a scrollable cursor, set cursor location to
client, and use the
RecordCount
method to return the number of records
(objRS.RecordCount
); locktype
attribute of
objRS.Open
is important. Its default is read-only, which prevents
updates altogether. The four types are:
adLockReadOnly
;
adLockPessimistic
- Records are locked immediately on
editing;
adLockOptimistic
- Records are only locked when the Update
method is called;
adLockBatchOptimistic
- Records are not locked until a
batch update occurs. This should be used with client-side cursors; Recordset
object implicitely using the
Execute
method of the Connection
object. You cannot
specify the CursorType
or LockType
if you do
this. Set objRS = objConn.Execute(CommandText,
RecordsAffected, Options)
Note that Options
must be set to adCmdTable
if CommandText is a table name;
objConn.Execute SQLstatement
can be
used to insert, update, and delete records from a database, without using a
recordset;Source
attribute in
objRS.Open
is the stored procedures name;
strSQL =
"EXEC nameofprocedure " & inputVariable...
Command
object, when used in conjunction with
objConn.Execute
, can be used to retrieve return values from the
database (through stored procedures). This process is a bit involved;
use an SP Wrapper
to make it easier. Command
object can be used to implicitely create
Recordsets as well. Its Execute
method operates like that of the
Connection
object. First, instantiate objCommand
,
then set its ActiveConnection
,
CommandText
, and CommandType
properties, then create/instantiate objRS
(Set objRS
= objCommand.Execute
).
CDONTS.NewMail
properties/methods are:.From
- takes email string;.To
- takes email string (separate multiple addresses with
semicolon);.CC
- takes email string;.BCC
- takes email string;.Subject
- takes subject string;.Body
- takes message string;.BodyFormat
- set to CdoBodyFormatHTML
if message
will contain HTML;.Importance
- set to Cdohigh
(or 2), CdoNormail
(or 1), and CdoLow
(or 0);.ContentBase
- will prefix all URLs in the message body with
the provided string;.ContentLocation
- will prefix all URLs in the message body
with the provided string (comes after ContentBase
);.AttachFile
- takes source (a fully qualified path), fileName
(optional caption for the file), and encodingMethod (also optional);.MailFormat
- set to CdoMailFormatMIME
if you want
to use the MIME format (takes advantage of Rich Text);.Value
- enables you to create custom headers in the email
head: eg, objMail.Value("keywords") = "Greeting"
;.Send
(in relation to above) - fires off constructed email;CDONTS.Session
provides access to a user's messaging
store. This can be used to read their messages, put things in their inbox,
etc (though not to modify the content of anything)
These notes were written by David J Edery
Back to 3GWT