You are on page 1of 27

*ASP Notes*

(If you appreciate these notes, please visit Syslist.com, a site developed by the author.
Thank you!)

1. Basics
2. Variables, Math
3. Control Stuctures
4. Built-in VB functions
5. Objects
6. The Response Object
7. Forms
8. Collecting Form Info
9. The Request Object (& Cookies)
10. The Session and Application Objects (*QueryString Shortcut)
11. Common ASP Components
12. Reading and Writing Files on the Web Server (*Code Insertion)
13. Debugging ASP Scripts and Handling Errors
14. Using Databases
15. Reading from a Database Using ASP
16. Inserting, Updating, and Deleting Database Records (with the Recordset
Object)
17. The Recordset Object
18. Using SQL Statements to Query Data
19. Advanced Database Techniques
20. External Notes

*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/2000

Day 2 - Basics

• varname = value delcares a variable;


• Put strings in double quotes to differentiate them from code, variable names, and
numbers;
• Variables names must start with a letter. A variable name may include but cannot
*be* a reserved word (keyword);
• Variables can be declared at outset with: Dim varname;
• To force variable declaration, use: <% 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 with a single ' char in ASP, with <!-- comment --> in HTML, and
with // in Jscript;
• A line break ends a statement. To avoid this, use the _ char. You cannot use the
underscore within a quoted string (output);
• constants: once assigned a variable, a constant cannot be changed (const
VARNAME = value). Use constants when declaring a file size for comparison, a
date, etc..;
• several constants are already built into VBScript, including vbDate, vbInteger,
vbBoolean, vbString, etc...

Back to Top

Day 3 - Working with Variables, Math

• An array function indexes a list of variables: 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...;
• standard division is represented by a slash (/). This returns a floating-point
quotient;
• integer division is represented by a backslash (\). This returns an integer (eg, 5/3
returns 1);
• modulus is represented by: 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...);
• the exponentiation operator is represented by (^). Note that exponentiation is
executed from left to right (eg, 2^3^2 = 8^2);
• negation is represented by the dash (-). The dash means negation when in front of
a variable, and subtraction when between two variables;
• raising to a power of 0.5 is same as square root;
• concatenation combines two strings. It can be done with (+) or (&). var+var2
returns varvar2;
• comparison operators: =, <, >, <= (less than or equal to), >=, <> (not equal).
Strings are compared alphabetically.

Back to Top

Day 4 - Control Stuctures


• Logical operators (true when):
o AND (x and y are both true);
o OR (x or y is true);
o NOT (x is false);
o XOR (x or y is true, but not both);
o EQV (x and y are both true, or both false);
o IMP (x is false or y is true);

• Conditional logic controls (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;
• For nested conditions more than three levels deep, use:
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
• Looping logic controls: (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
• You can also make sure the code_block is run at least once by putting the
"while condition" below it:
Do
code_block
Loop While condition
• HTML tags that fall within ASP control structures are affected by them, as well;
• Use the (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
• Nesting loops results in each nested loop completing a cycle for every individual
count of the parent loop (eg, multiplication table example);
• Branching logic controls: two kinds: subroutines (for performing actions) and
functions (for computing values). Subroutines do *not* return a value. Branching
logic is used for code that is repeated often or may need to be changed frequently.
Feel free to include any other kind of logic within a branching logic control.
• Subroutine (only called by itself):
Sub routinename (arg) *Note: arg is not required*
code_block
End Sub
• Variables declared in the main part of your script are global - they can be
accessed by any logic control. Variables declared inside a subroutine are local to
it.
• Function (can be put into an expression, etc):
Function functionname (arg)
code_block
End Function

Back to Top

Day 5 - Built-in VB functions

• Typcasting converts between data subtypes:


o Cint(expression) casts expression to an integer. Floating-point is
rounded, number-like string is changed, True becomes -1 and False
becomes 0, etc;
o Clng(expression) casts expression to a long (stays the same,
basically?)
o Cbyte(expression) casts expression to a byte value (provided
expression is between 0 and 255);
o Cdbl(expression) casts expression to a double (stays the same,
basically?);
o Csng(expression) casts expression to a single (eg, 0.000556 returns
5.56E-04);
o Cbool... returns false if expression is zero, otherwise returns true.
Expression must be numeric;
o Ccur... returns a currency value (negligable?)
o 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;
o Cstr... returns a string. Basically, anything becomes "anything";

• Formatting functions:
o 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;
o 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;
o FormatNumber(value, arg1, arg2, arg3, arg4) - works just like
FormatCurrency, minus the dollar sign;
o FormatPercent(value, arg1, arg2, arg3, arg4) - works just like
FormatCurrency, but returns a percentage;

• Math functions (see pages 130-131 for them all). Note: 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;
• Placing 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 functions (note: #9/18/99# refers to November 18, 1999. Whenever inputting
a date, you must put it in between pound signs. "9/18" refers to November 18th of
the current year, whatever that is):
o Date returns the current date. It can be stored in variables or
utilized/output as is;
o Time returns the current time. It can be stored in variables or
utilized/output as is;
o Now returns the current date and time;
o 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;
o 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);
o 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;
o TimeSerial(hour, minute, second) ...etc;
o Timer returns the number of seconds elapsed since midnight;
o 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.
o Year(date) returns the year portion from date (a number);
o Month(date) returns the month portion from date (a number);
o 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");
o Day(date) ...etc;
o Weekday(date) ...etc;
o Hour(time) returns the hour portion from time;
o Minute(time) ...etc;
o Second(time) ...etc;

• String Functions (the first few are great for de-sensitizing user input. Feel free to
combine them!):
o UCase(string) returns string with all its letters converted to uppercase;
o LCase(string) returns string with all its letters converted to lowercase;
o LTrim(string) removes all spaces from left side of string;
o RTrim(string) removes all spaces from right side of string;
o Trim(string) removes all spaces from both sides of string;
o Space(number) returns a string consisiting of number spaces (not really
useful, except for within <pre> tags);
o String(number, char) returns a string consisting of char repeated
number times;
o Len(string) counts the number of characters in string;
o StrReverse(string) returns string with the characters in reverse
order;
o 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;
o Right(string, number) returns the number rightmost characters of
string;
o Left(string, number) ...etc;
o Mid(string, start, length) returns length characters from string,
starting at position start (length and start should be numbers);
o 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.
o 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;
o 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;
o 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;
o 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);
o Join(stringarray, delimiter) takes an array of strings and joins
them into one string, using delimiter to separate them (default is, again,
the space);
o LBound(array) returns the smallest valid index for array. This is
normally 0;
o UBound(array) returns the largest valid index for array. This is the
index of the last element in the array;
o Use the above to iterate through an array of unknown size: For iIndex
= LBound(myarray) to UBound(myarray)...;
o Asc(string) returns the ANSI code for the first character of string;
o 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);

Back to Top

Day 6 - Objects

• Functions make your code more simple and readable; Objects take that to the next
level. Objects are composed of properties (things that describe them), methods
(things that can be done with them), and events (something generated by the
object that causes special action to be taken). Objects have "instances" - for
example, object "car" has instances "Explorer," "Jeep," etc. Each of those has a
unique set of properties defined by "car";
• To access object properties: ObjectVariableName.Property;
• Methods receive arguments, and often affect the value of properties (eg, the
accelerate method increases the speed property). To access methods:
ObjectVariableName.Method;
• The six built-in ASP objects:
o Response - used to send output. Response also controls how and when
data is sent, and do stuff with cookies;
o Request - used to retrieve data from the client. QueryString data (seen at
the end of URLs) is an example of a request object;
o 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;
o Session - refers to a single client accessing an application. A new
instance is created for each session, and carries information between pages
for client;
o 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);
o ObjectContext - used to link ASP and the Microsoft Transaction Server
(MTS).
o ASPError - allows you to obtain information about script errors in your
pages.
• A "collection" is a set of name/value pairs. "?name=John&sex=Male" contains
two name/value pairs, which are stored in the 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.
• ASP components - objects created by a third party that you can download and use
to make programming easier;
• Use the Class statement to create a simple object:
Class classname
public propertyname
private propertyname
public Sub methodname(args)... End Sub
private Function methodname(args)... End Function
etc...
End Class
• Creating an instance of an object is called "instantiation". To do so, use: 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).
• Set the Color property of instance MyCar (object Car) like this: MyCar.Color
= "blue";
• A better way to change the value of a property is to do so through a method
included in the object (eg, the Sub and Function methodname(args)...);
• Use: Set objectinstance = Nothing to free up system memory, once an
instance no longer needs values;
• When an event is generated, special code called an event handler can be executed.
Two common events are 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.

Back to Top

Day 7 - The Response Object


• 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;
• The 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, "");
• Don't use the <%= shortcut for the Write method. You'll have to close and re-open
the VBScript brackets around it;
• Place <% 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;
o Response.Clear causes the buffer to be wiped out;
o 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);
o 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;
o Two ways to redirect a user to another page; <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;
o Response includes a collection called Cookies that can be used to write
cookies;
o 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;
o 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;
o Note that browsers are not reliable about caching as per instructions; it can
be frustrating getting them to work correctly.
• To send status codes to a browser: Response.Status = "401 Not
Authorized", for example. Other codes: "302 Object Moved" and "404 Object
Not Found"

Back to Top

Day 8 - Forms
• <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;
• The optional 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;
• The 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;
• Server-side applications can be accessed through querystrings appended to
hyperlinks (in GET-style fashion). When doing this, however, make sure to
replace the "&" that separates name/value pairs in the querystring with a
"&amp;", otherwise the browser will get confused;
• If using a mailto as the action attribute, use javascript to inform a user that their
form has been processed (they won't know otherwise);
• The 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:
o 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;
o password - simply a text field that masks user input as it is being typed;
o 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";
o 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;
o 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;
o 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;
o reset - has no required attributes. You can change the button's label with
the value attribute;
o 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;
• The 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;
• The 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;

Back to Top

Day 9 - Collecting the Form Information

• When a form has its method set to POST, you use the
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;
• If you group checkboxes with one name (different values), and a user selects more
than one checkbox, the named group is returned as a comma-delimited list. You
can:
o Use the 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;
o Give each checkbox a different name (same value), and then use multiple
"If" statements to parse through the results;
• If you will be collecting an unknown number of form results (for example, from
X select boxes...), you can use: 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.
• As opposed to using forms, you can make use of hyperlinks with a querystring
attached to the end;

Back to Top

Day 10 - The Request Object (& Cookies)


• When a browser requests a web page, it sends a "request header." When
responding, the server sends a set of "response headers." Both are referred to as
"HTTP headers";
• The Response.AddHeader method (Response.AddHeader HeaderName,
HeaderValue) allows you to send a custom response header;
• Headers typically sent by the client to the server:
o HTTP_ACCEPT - a list of MIME types the client will accept;
o HTTP_ACCEPT_LANGUAGE - what languages the browser expects;
o HTTP_CONNECTION - the type of connection established between client and
server;
o HTTP_HOST - the hostname of the client computer;
o HTTP_USER_AGENT - the browser type and version, and operating system of
client;
o HTTP_REFERER - the full URL of the web page containing the hyperlink
used to reach the currently executing ASP page;
o HTTP_COOKIE - the cookies sent from the browser;
• Use 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");
• The 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;
• "Environment variables" are bits of information the the web server makes
available to any program that requests them, including the name of the web
server, the name of the web server software being used, etc;
• *Note: when requesting a single environment variable or HTTP_header with
Request.ServerVariables, *all* are loaded into the collection. So, don't use the
collection except when you must;
• Commonly used environment variables:
o URL - the URL of the ASP page from after the domain name up to the
questrystring;
o PATH_INFO - same as URL;
o PATH_TRANSLATED - the full, physical path of the ASP page;
o APPL_PHYSICAL_PATH - the physical address of the Web's root directory;
o QUERY_STRING - equivalent to Request.QueryString;
o SERVER_NAME - the web server's computer name;
o SERVER_SOFTWARE - name of the web server software;
• Use Request.ServerVariables(environmentVariable) to read the above
variables;
• Many environment variables will not contain a value. For example, and variable
preceded by "CERT" will be empty unless the client and server use certificates;
• You can combine the SERVER_NAME and URL variables (in that order) to retrieve
the full URL of an ASP page;
• Use the 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.
• Read cookies as follows: Request.Cookies(cookieName)(keyName), write
cookies with: Response.Cookies(cookieName)(keyName1) = value;
• Use Request.Cookies(cookieName).HasKeys to determine if a cookie has keys;
• Use 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;
• Use the 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;
• Use the Secure property (set to "True") to prevent a cookie from being sent
without the HTTPS protocol;
• To test if a client accepts cookies, try to write one on the first page they visit, and
(at any relevent second page), try to read it with the statement: If
Len(Response.Cookies(cookieName)) = 0 Then ...;
• Remember: 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...)

Back to Top

Day 11 - The Session and Application Objects (+ QueryString shortcut)

• If state *must* be maintained for all visitors, and: A) security is not an issue, B)
there is little data to pass, then use the querystring. Pass information from page to
page by adding the appropriate query string to the end of each and every link
following the page that requests the needed variables. <a href =
"somepage.asp?<%=Request.QueryString%>"></a>

• The 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;
• A numeric ID, the 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;
• Set the end of a session with: Session.Timeout = time_in_minutes. This value
should probably never be higher than 20 minutes, or so. Destroy a session
instantly with Session.Abandon;
• To put an object in the Session, use: Set Session(variableName) =
Server.CreateObject(ObjectName);
• The Session object contains two collections: Contents, which contains all non-
object variables, and StaticObjects;
• The Count property can be used on the Session object (eg,
Session.Contents.Count returns the number of variables in Contents);
• An ISAPI (Internet Server Application Programming Interface) filter called
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;

• The Application object is used to store global variables - accessible from any ASP
page, by any user. Create application variables as follows:
Application(variableName) = value;
• To prevent more than one user from changing an application variable at once,
use: Application.Lock and Application.Unlock before and after the change
statement;

• Use: Sub Application_OnStart... End Sub, and Sub Session_OnStart... End Sub to
create all the session and application variables that will exists from the moment
the web server is up and running, and to set initial values for those variables.
These OnStart events must appear in the Global.asa file that is placed in the
website's root directory. Use the similar OnEnd event for cleanup type
maintenance;

Back to Top

Day 12 - Working with Common ASP Components

• Instantiate a component as you would an object: Set objComponent =


Server.CreateObject("classname.componentname"). Components in this
section have the classname "MSWC" - derived from the package the components
come in;
• Always remember to free the memory used by a component when you are done
with it: Set objComponent = Nothing;

• Ad Rotator (AdRotator) is a component included with IIS that makes it easy to


add a raondom changing banner to a site. To use it, you must create a rotator
schedule and a redirect page;
o Rotator schedule (save as text file):
REDIRECT URL
WIDTH pixel_width
HEIGHT pixel_height
BORDER border_thickness
*
FirstImageURL
HomePageURL
AltText
Weight
SecondImageURL ...
o Note: if a banner has no target page, a hyphen (-) should be used for
HomePageURL;
o Weight should be between 0 and 10,000;
o The Redirect Page (REDIRECT URL) will be called with: redirect_URL?
URL=HomepageURL&image=ImageURL, and will look (at simplest) like: <%
Response.Redirect(Request.QueryString("url")) %>
o Call your AdRotator instance with the GetAdvertisement method (its
argument is the Rotator Schedule);
o You can use one instance of AdRotator several times and several ways
with different schedule files;
o There's no easy way to record banner impressions with AdRotator - keep
in mind;

• Browser Capabilities (BrowserType) is a component that does just what the name
says. To keep its abilities up to date, download newer versions of "browscap.ini"
(the companion file to browscap.dll) from http://www.asptracker.com/;
o Properties you can check for w/Browscap: browser, version, platform,
cookies, backgroundsounds, vbscript, javascript, tables, frames,
activexcontrols...;
o Use BrowserType as follows: If ObjBC.Browser = "Netscape"
Then...;

Back to Top

Day 13 - Reading and Writing Files on the Web Server (+ Code Insertion)

• Server-side includes allow you to write commonly used code and stick it into any
page in a site. They are always executed *before* any ASP code is executed. To
insert a page into another page this way, use: <!--#include
virtual="fullpath/something.asp"--> ;
• Server.Transfer and Server.Execute are new methods to IIS 5.0 that also
enable code insertion;
o 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;
o 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"):
o has two methods that can be used to determine if a file or folder exists.
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;
o The 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;
o The GetFolder method (of objFSO) is used to instantiate the folder
object:
 All the appropriate attributes listed for GetFile, plus;
 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;

• To open a file (instantiate the text stream object) so that you may read it, or write
to it:
o Use the OpenTextFile method of the file system object: 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);
o Use the OpenAsTextStream method (if the file you want has already been
instantiated): Set objOpenFile = objFile.OpenAsTextStream(mode,
format);
o Use the CreateTextFile method (if you want to create or overwrite a file):
Set objNewFile = objFSO.CreateTextFile(filename, overwrite,
format);
o Before destroying an instance of the text stream object, you must close it:
objOpenFile.Close;

• To read a file (still the text stream object):


o Use the 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;
o AtEndOfStream is a property of the text stream object. Its value is True if
you are at the end of the text;
o The ReadLine method returns a string consisting of an entire line from the
file;
o The ReadAll method returns a string containing the entire file;
o Surrounding output with <pre> and </pre> tags is a good idea - it will
maintain the formatting of the text file;

• To write to a file (still the text stream object):


o Use the Write method: objOpenFile.Write("your text");
o The WriteLine method writes a string to a text file and then adds a
carriage return. With no argument, it simply adds a carriage return;
o WriteBlankLine(number) writes number carriage returns to the file;
o The moment you open a file (and specify ForWriting), you destroy its old
version. Use ForAppending (when opening the file) to avoid this;

Back to Top

Day 14 - Debugging ASP Scripts and Handling Errors

• Using Option Explicit will save you hours of debugging time;


• Common fatal errors:
o A typo (referring to a variable that has not been explicitely created);
o Trying to access an array element that does not exist;
o Refering to a nonexistant property or method of an object;
o Declaring a variable with a reserved name;
• Debugging nonfatal bugs: Test each user-input item with values that are expected,
near-boundry, boundry, and unexpected (eg, letters instead of numbers, etc);
• Use the 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
2000. 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:
o ASPCode - contains the error code genearted by IIS;
o Number - the error number;
o Source - contains the source code of the line that caused the error;
o Category - errors have three catagories: internal ASP, scripting language,
or object;
o File - the filename of the ASP page with the error;
o Line - line number on which the error occured;
o Column - returns the column position in which the error occured;
o Description - a brief description of the error;
o ASPDescription - more detailed description, only provided when the error
is an internal ASP error;
• Scripting language errors occur when illegal syntax is used in the server-side
script. For example, misusing a For control structure, or calling a function with an
incorrect number of parameters...;
• If an error occurs after a Response.Flush, or if you have Response.Buffer =
False, the custom error page won't be loaded;
• Errors from 400-499 are client errors. Errors from 500-599 are server errors. Find
a full list of error descriptions at:
http://www.webpartner.com/html/AlertsandErrors.htm;

Back to Top

Day 15 - Using Databases

• The columns of a database table ("the object") describe the properties of the
object, whereas each row is a unique instance of the object. Rows in a database
table are records, and columns are referred to as fields. A record is a single
instance of the object, as a field is a single property of the object;
• If a property of an object is an object in itself (eg, has its own properties), then it
should get its own table, and be referenced in the parent table. Merging the two
related tables creates a flat-file database, which is not as efficient as separate
tables (a relational database). A relational database represents each object,
related or not, as its own database. A normalized database is streamlined to not
contain any repetitive data;
• Any ODBC-compliant database an be accessed through ASP. Such a database
adheres to the Open DataBase Connectivity standard outlined by Microsoft;
• A database is the most effective and efficient method of storing information.
However, connecting to a database through ASP is expensive; small bits of data
are best read from a text file or cookie, which are much easier to read. When the
information being stored needs to be long lasting and is not user-specific, text
files are a good way to go. For example, a list of bad credit card numbers would
best be kept in a text file;
• A vast number of existing applications already use databases to store information.
You can probably access these databases through ASP;
• To create a database through Access 2000:
o Run Access. A dialog box will appear. Choose to create a Blank Access
Database. Name the database file 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);
o Data types supported by Access: 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;
o Save the table (and name it). Close the Design view, and select the table
you created from the inital set of options you were shown. Add some
information into the table, and you are all set!
• To communicate with a database through an ASP page, you need to use the
ActiveX Data Objects component (ADO). It contains two useful objects - the
Connection object and Recordset object

Back to Top

Day 16 - Reading from a Database Using ASP

• ASP communicates through OLEDB (a COM-based data access object) to a


database. It includes an ODBC driver so that it is compatible with all the ODBC
data sources;
• ActiveX Data Objects (ADO) contains six objects: Connection, Recordset,
Error, Field, Command, and Parameters;

• The 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;
• A System DSN is a file that contains information about the database such as where
it is and what kind of database it is. DSN stands for Data Source Name. To create
a System DSN:
o Go to Administrative Tools and load Data Sources (ODBC). Click the
System DSN tab. Click Add. Choose Microsoft Access Driver (*.mdb)
and click Finish;
o Enter 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;
• Open the connection object with:
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;
• You can replace "DSN=something.dsn" in a DSN-less connection with:
o "DRIVER={Microsoft Access Driver (*.mdb)};" &
"DBQ=PhysicalPath\something.mdb"

Even better, use the native OLEDB provider:

o objConn.ConnectionString = "Provider=ProviderName; Data


Source=DatabaseSource; Initial Catalog=DatabaseName; User
ID=UserID; Password=Password"
o For SQL: Provider=SQLOLEDB; Data Source=myMachine; Initial
Catalog=something; User ID=; Password=
o For Access: Provider=Microsoft.Jet.OLEDB.3.51;
Data Source=c:\inetpub\wwwroot\something.mdb
• Save 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;
• Close the connection object with:
objConn.Close
Set objConn = Nothing
• The Properties collection of the Connection object (objConn.Properties)
contains an instance of the Property object for every property supported by the
connection;

• The Recordset object is used to contain all the records in a table, or a subset of
those records: Set objRS = Server.CreateObject("ADODB.Recordest");
• Fill the recordset with records by using the Open method: objRS.Open
source, connection, cursortype, locktype, commandtype;
o source - either a command object or a string that relates to commandtype
("mytable");
o connection - either a Connection object or a string containing the
connection information;
o cursortype - indicates the way you want to move through the recordset.
Default is the ADO constant adOpenForwardOnly, which means you can
only move forward;
o locktype - affects whether you can write to the table, and if so, how.
Default is adLockReadOnly, which makes the table read-only;
o commandtype - indicates how the source parameter should be evaluated.
adCmdTable indicates that source is a table name;
• You can implicitely create a connection object by simply instantiating the
Recordset object, then opening it (with the connection parameter correctly set
to everything that would go into the Connection object's ConnectionString);
• ADO constants are not built into ASP - you must include the 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"-->;
• The METADATA tag may be used to import type-library constants into a page.
As an alternative to including adovbs.inc, you could use: <!--METADATA
TYPE="TypeLib" File="\msado15.dll"--> (you must put msado15 in your
root web, first). You can put this statement into your global.asa;

• Read the Recordset object with the following methods (objRS.method):


o MoveNext - advances to the next record;
o MovePrevious - goes back one record;
o MoveFirst - moves to the first record, even if adOpenForwardOnly is set;
o MoveLast - goes to the last record;
o Move number - skips ahead (or back) number records;
• The 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;
• Good error message technique/testing for empty recordsets: If objRS.EOF Then
(Reponse.Write "error message") Else (database operations...);

• Remember to always close (and set to Nothing) both objConn and objRS when
you are done with them!!!
• For more information on how to connect directly through OLEDB (circumventing
ODBC driver), read www.4guysfromrolla.com/webtech/063099-1.shtml;

Back to Top

Day 17 - Inserting, Updating, and Deleting Database Records (with the Recordset
object)

• the objRS.Open attribute locktype can be set to adLockOptimistic (value of 3),


which signifies that records will be locked when Update is called;
• Two methods of 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:
o 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
• Cancel changes with objRS.CancelUpdate. This only works if Update has not
been called yet;
• Delete records with objRS.Delete. This is good for cancel membership type
functionality...;
• In Access, you can set field values as required. After Javascript and even server-
side validation, this is a good last line of defense against blank data entering the
table;
• You can also insert, update, and delete using the command object (day 20);

Back to Top

Day 18 - Examining the Recordset Object

• Each column in a database table or Recordset object represents a particular


property of the object. Each row in a database table or Recordset object
represents and instance of the object;
• Each row in the 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;
• Each item in the 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;
• For all other properties of the Field object, the Fields collection should be
referenced explicitely. These properties are:
o Name - contains the name of the column that the cell exists in;
o Type - Contains the type of data that exists in the cell (adInteger,
adBoolean, etc...);
o Precision - Represents the maximum number of digits that can be used for
numeric values;
o NumericScale - Represents the number of decimal places for numeric
values;
o DefinedSize - Contains the maximum size, in bytes, of the data the cell
can contain;
o ActualSize - Contains the actual size, in bytes, of the data in the cell;
• The Count property of the Fields collection returns the number of elements in
the collection (columns in the table);
• The Fields collection can be accessed by index, starting with zero:
o 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
• Recall: 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;
• You can specify where the cursor should be used. On the client-side:
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;
• To sort a recordset: 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");
• Filter through recordsets using comparison and logical operators:
o If objRS(field) > numericValue Then...
-or-
If objRS.Filter = "field > numericValue" (*Note - this is global, former is
local*)
• The Filter property works with any logical statement (note - logical operators
are restricted to AND, NOT, and OR);
• When using Filter, you must put single quotes around string or date column
values in the equation (eg, objRS.Filter = "Symbol = 'MSFT'");

Back to Top

Day 19 - Using SQL Statements to Query Data

• With SQL, you can restrict the data returned by a database to only the information
you are interested in. Note: SQL is not case-sensitive by default;
• The syntax of an SQL query is as follows: 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):
o 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)
• If selectList is "*", then all columns are obtained;
• When using multiple logical operators in the WHERE clause, use parenthesis.
Without parenthesis, note that NOT takes highest precedence, followed by AND,
followed by OR;
• When comparing strings in a WHERE clause, you must surround the variable you
are comparing the column to in single quotes;
• The LIKE operator can be used in the WHERE clause to search for patterns in
strings:
o % -Translates to any string of zero or more chars;
o _ -Translates to exactly one char;
o [] -Translates to any specific char within a certain range;
o For example: 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);
• If the ORDER clause is placed before the WHERE clause, an error will result;

Back to Top

Day 20 - Advanced Database Techniques

• The 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);

• If there is any likelihood that a database will be altered by more than one user
simultaneously, the locktype attribute of objRS.Open is important. Its default is
read-only, which prevents updates altogether. The four types are:
o adLockReadOnly;
o adLockPessimistic - Records are locked immediately on editing;
o adLockOptimistic - Records are only locked when the Update method is
called;
o adLockBatchOptimistic - Records are not locked until a batch update
occurs. This should be used with client-side cursors;
• The pessimistic lock is less efficient than the optimistic lock, but also safer. If
there will be many simultaneous updates to a table, use the pessimistic lock ("not
many" being defined as a user or two?);

• You can create a 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;
o *objConn.Execute SQLstatement can be used to insert, update, and
delete records from a database, without using a recordset;
• Runtime SQL statements (all the SQL queries performed prior to now in the
guide) are less efficient than stored procedures. Stored procedures are SQL
queries that have been stored by the database program, and which result in a
saved execution plan the first time the procedure is executed. That plan makes
future executions of the query much more efficient. The value of the Source
attribute in objRS.Open is the stored procedures name;
• To create a stored procedure in Microsoft SQL Server: Expand the Databases tab.
Expand the Database to which you want to add a stored procedure. Click the node
entitled "Stored Procedures." Right click in the right pane and select "New Stored
Procedure." Replace "[Procedure Name]" in the resulting dialog box with
whatever name you want. Type the SQL query you want to execute after the AS.
(Note - comments should be surround with /* and */, or with -- ) Click OK.
• To create a stored procedure in Access: Click the Query tab in the Objects
toolbar. Double click the "Create a Query" option. Select the table or tables you
are interested in generating a query for, and click close. Choose what fields you
want the query to return. Choose how you want the fields sorted. Close the Query
Design view, and click "yes" when asked to save. Enter a name for the query.
• To run a stored procedure: strSQL = "EXEC nameofprocedure " &
inputVariable...
• *The 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.

• The 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).

Back to Top

• External Notes:
o Collaboration Data Objets (CDO) - interacting with Exchange
 CDONTS (a subset of CDO) is used to send and received simple
emails. The CDONTS.NewMail properties/methods are:
.Send - catch all method; takes from, to, subject, body, importance;

.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

You might also like