Active Server Pages PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 34

Contents

Articles
Active Server Pages 1
Active Server Pages/Prerequisites 2
Active Server Pages/Differences between ASP 3.0 and ASP.NET 3
Active Server Pages/Your first page 4
Active Server Pages/Basic ASP Syntax 5
Active Server Pages/Variable Types 8
Active Server Pages/Expressions 13
Active Server Pages/Conditionals and Looping 22
Active Server Pages/Server-Side Includes 28

References
Article Sources and Contributors 32

Article Licenses
License 33
Active Server Pages 1

Active Server Pages


How this book is organized
This book is organized into modules. Each module should take you about one hour to complete.
Modules are organized as follows:
• objectives
• content
• summary
• review questions
• exercises
Later modules build upon earlier modules, so we encourage you to read them in sequence.

Table of Contents
• → Prerequisites
• → Differences between ASP 3.0 and ASP.NET
• → Your first page
• → Basic ASP Syntax
• → Variable Types
• → Expressions
• → Conditionals and Looping
• Functions and Subroutines
• Database Access Using ADO
• → Server-Side Includes
• Debugging

Other ASP References


• Appendix A: Language Reference
• Protecting against user-input (XSS attacks)
Active Server Pages/Prerequisites 2

Active Server Pages/Prerequisites


ASP (or Active Server Pages) is a scripting tool for dynamic webpages. It is a technology that can be compared to
Cold Fusion, JSP, and PHP. While primarily made for the Microsoft Windows platform, there are implementations
of ASP technology on other environments.
ASP is the technology that powers the dynamic websites, not the language that the pages are scripted in. There are a
number of languages that can be used to script or program a dynamic website. However, most people assume that
ASP and vbscript (one of the languages used) are the same.
With the release of the .Net platform, Microsoft also updated ASP to ASP.Net. There are a number of improvements
to ASP that ASP.Net provides, but that would be a book unto itself. This textbook focuses on what is now called
"classic" ASP. One important difference is that ASP.Net pages are named *.aspx and ASP 3.0 pages are named
*.asp, and ASP 3.0 pages are interpreted and ASP.Net pages are compiled thus ASP.net pages work faster. ASP.Net
uses the Microsoft .Net framework and can use any language that .Net supports. ASP 3.0 is limited to VBScript and
JScript (Microsoft's version of Javascript).

Do I need to know HTML?


Yes and No... The output of ASP is usually HTML, so it is strongly recommended that you are familiar with at least
HTML 4.01 [1]. While many programmers prefer visual editors like Macromedia's Dreamweaver and Ultradev,
Microsoft's Frontpage and Visual InterDev, beginners will benefit more from using a plain text editor until
comfortable with the basic concepts.

Do I need to know a programming language?


You should be familiar with at least one object-oriented programming language. This book will teach you how to
program in ASP, but it will not teach you how to program. You should understand the following concepts:
• variables
• global variables, and how they differ from local variables
• functions, and
• how to pass parameters to functions
• decision-making statements such as if-then and if-then-else
• looping statements such as the for loop and the while loop

Do I need to install web server software on my computer?


There are sites such as 1asphost.com [2] that provide free web sites with ASP capabilities. You can upload your ASP
files, and the server will do all the ASP processing for you.
Find similar services by doing a Google search for "free asp hosting". [3]
You may also install software on your computer to process ASP files locally. Internet Information Services [4] will
come in handy for users of Microsoft Windows operating system. And there are Apache webservers [5] available for
most of today's operating systems.
In order to execute ASP 3.0 locally, you will need Windows 2000 Professional or higher. All versions of Windows
from 2000 include Internet Information Services with the exception of Windows XP Home. Installation is simple,
just go to Add/Remove programs and then the Add/Remove Windows components section. Just keep in mind that
just because you have IIS installed that does not mean that ASP files will execute.
Active Server Pages/Prerequisites 3

References
[1] http:/ / www. w3. org/ TR/ REC-html40/
[2] http:/ / www. 1asphost. com
[3] http:/ / www. google. com/ search?hl=en& lr=& ie=UTF-8& q=free+ asp+ hosting& btnG=Search
[4] http:/ / www. microsoft. com/ windowsxp/ evaluation/ features/ iis. mspx
[5] http:/ / www. apache. org

Active Server Pages/Differences between ASP 3.


0 and ASP.NET
The most important difference between ASP and ASP.Net is that ASP uses interpreted VBScript or JScript, and
ASP.net uses any .Net language (including VB.Net, C#, J#, etc) compiled.
ASP 3.0 left all its code in the front of the application. There was no way for a programmer to "hide" the sensitive
code which he or she may not want anybody to see. The fact the code ran at run-time also slowed performance.
ASP.NET allows the programmer to create dynamic link libraries containing the sensitive code. This may be a
disadvantage from an open-source perspective but compiling code into dll's greatly improves performance.
ASP.NET is firmly rooted in XML. Customarily, the dll's ASP.NET creates start out as namespaces. All of the
classes in the namespaces are then compiled into a single dll binary.
1. ASP is mostly written using VB Script and HTML intermixed. Presentation and business logic is intermixed
while ASP.NET can be written in several .NET compliant languages like C#, VB.NET and business logic can be
clearly separated from Presentation logic.
2. ASP had maximum of 4 built in classes like Request, Response, Session and Application whereas ASP.NET
using .NET framework classes which has more than 2000 in built classes.
3. ASP does not have any server based components whereas ASP.NET offers several server based components like
Button, TextBox etc and event driven processing can be done at server.
4. ASP did not support Page level transactions whereas ASP.NET supports Page level transactions.
5. ASP.NET offers web development for mobile devices which alters the content type (wml or chtml etc) based on
the device.
6. ASP.NET uses languages which are fully object oriented languages like c# and also supports cross language
support.
7. ASP.NET offers support for Web Services and rich data structures like DataSet which allows disconnected data
processing.
Active Server Pages/Your first page 4

Active Server Pages/Your first page


Objectives
• Embed ASP scripting code into a web page.
• Upload your ASP page to a server.
• Test your page by viewing it in a web browser.

Content
ASP is delimited with "<% and %>"
within these delimiters is your custom code that is executed in the server.
Here is a small fragment of an ASP code (it outputs "My First ASP" on your browser):

<%
Response.Write "My First ASP"
%>

Or you could put the text into a pre-defined variable:

<%
Dim MyText

MyText = "My First ASP Page"


Response.Write MyText
%>

Here is a way to separate your code from your page layout.

<%@LANGUAGE="VBSCRIPT" CODEPAGE="1252"%>
<%

Dim MyText

MyText = "My First ASP"

%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"


"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=iso-8859-1">
<title>My First ASP</title>
</head>

<body>
<%=(MyText)%>
</body>
Active Server Pages/Your first page 5

</html>

Active Server Pages/Basic ASP Syntax


Objectives
In this section you will learn about the different parts of Active Server Pages scripting. We don't want to get too deep
in discussion of how to write ASP scripts, but instead just want to introduce the different elements of ASP scripting.

Content
Active Server Pages or ASP is a scripted language which means that it doesn't have to be compiled in order to run.
Instead, the program code is parsed, interpreted and evaluated in real-time. This means that you do not have to
compile code in order to execute it.
Code is executed by placing it within a web page on a Web server. ASP was developed by Microsoft and because of
this, is only completely reliable on Microsoft's IIS (Internet Information Server.) We encourage you to use Microsoft
IIS to develop Active Server Page code.

Statements
A statement is like a sentence in English, it describes one task for the ASP interpreter to perform. A block of code is
made up of multiple statements strung together on a web page.
There are various types of statements which we will talk about in the future including: "(flow) control, output,
assignment, and HTTP processing.
In Active Server Pages, it is important to realize that each statement must appear on a line by itself. There is no
special delimiter that indicates the end of an ASP statement. Unless you consider the carriage-return as the delimiter,
which you really shouldn't.
You can use the colon character ":" within a program block to place multiple statements on the same line such as:

<%
Response.Write "Error" : Response.End
%>

In practice, it is best to avoid such programming constructs since it will make your code harder to read and maintain.
Another way to include more than one statement on a line is by using multiple code blocks like in the following:

<% If I < 0 Then %>Negative<% End If %>

Here, you have two different statements (even though they look like one statement) broken into two different code
blocks. Active Server Pages allows this construct on your web pages since it is sometimes necessary to write code
like this to eliminate white space that appears on your web page.
Active Server Pages/Basic ASP Syntax 6

Variables
One of the hallmarks of a good scripting language is that the variables in the language are loosely typed. This means
that there is minimal type-checking done on the values of the variables your program code uses. Active Server Pages
was built correctly as a scripting language to be loosely typed. This allows you, as the programmer, to worry less
about what type a variable is which frees you from a lot of work converting values and testing for the correct type.
You are not required to declare your variables before you use them (or even at all if you so wish). The one exception
to this rule is when the page directive "Option Explicit" is in effect. If you place the following at the top of your ASP
page, you will be required to declare all variables:

<% Option Explicit %>

If you don't want this requirement in all your scripts, you can leave it out. It is a useful tool to throw onto a page to
check for mis-spelled or mis-used variable names. If you mis-spelled a variable, you will likely see "variable not
defined".
Variables are declared with a Dim statement and can include a single variable at-a-time or a comma-delimited list of
variable names like shown in the following example:

<%
Dim sPhoneNo
Dim sFirstName, sMidleInitial, sLastName
%>

There is no such thing as a global variable in the ASP language. All variables are specific to the web page they are
processed in. Once the page is done processing the values are lost. One exception to this is the Application object. It
can hold a number of different values, each of which is associated with a string value. Another way is to pass
variables in a web form or part of the URL in the Request object. More information on these topics will be covered
later.

Comments
Comments are notations you can make on your web page within an ASP script block that will not be output on the
web page. For all intents and purposes, they are hidden from your site visitors since they cannot view the ASP source
code for your web pages. This allows you to make comments about what your code is doing.
Active Server Pages uses the quote character (') to define comments. This comment is a "line comment" meaning
that it will comment out everything following it up until the end of the line. There is no multi line comment in ASP.
In order to comment multiple lines, each line must be preceded by a quote (').

<%
' example comment - show the current date
Response.Write Now()
%>
Active Server Pages/Basic ASP Syntax 7

Server-Side Includes (SSI)


Server-Side Includes allow you to retrieve code from one web page and insert it into another page. This allows you
to create common pieces of code and HTML which only need to be maintained in one place. Other web pages can
include this content within their pages using this server directive.
If you are using server-side include directives, you cannot place ASP code within the directive. This is because the
directive is evaluated before the ASP code is interpreted. So trying to do something like the following is illegal:

<!-- #include virtual="/lib/<%= sLibName %>" -->

But this doesn't mean that you can't place ASP code inside an included file. So if you include a file called
/lib/common.asp, you can place ASP code inside that file (just like you would a normal ASP page) and it will be
evaluated by IIS and the results will be placed in the calling page.
An interesting note is that your main page can use a ".html" extension and include (via SSI) an ASP page and the
included file will be interpreted and processed as ASP and included in the HTML page.
The two different types of Server-Side includes allow you to retrieve and include files based on the absolute path
(based on the Web site root) or relative to the calling page as shown below;

<%' absolute path - based on web site root %>


<!-- #include virtual="/pathtoinclude/include.asp" -->
<%' relative path - based on folder of calling page %>
<!-- #include file="../../folder1/include.asp" -->

There are benefits to using both. A good rule of thumb is this: if you expect you will be moving entire folders (or
trees) of your web application then relative paths are more appropriate. If you expect things to stay pretty much
where you created them then you should use absolute paths.
Please note: When using IIS6 (Windows 2003 Server), relative paths are not enabled by default, which will cause
any Server-Side includes using relative paths to cease functioning.

Review Questions
• What are the three different types of script delimiters?
• What file extension must be used when writing an ASP web page?
• Which web server must be used to interpet ASP web pages?
• How do you declare a variable?
• How do you enforce the rule that all variables must be declared?
• What are the benefits of server-side includes?
• When should you use absolute server-side includes (SSI)?
• How do you terminate a statement in ASP?
• What is an "interpreted" scripting language?
• How do you write comments in Active Server Pages?
• How do you make "block comments" in ASP?
• Which database works best with ASP?
Active Server Pages/Basic ASP Syntax 8

External Links
ASP Tutorials [1]

References
[1] http:/ / www. pickatutorial. com/ tutorials/ asp3_0_1. htm

Active Server Pages/Variable Types


Objectives
In this section you will learn about variables in Active Server Pages. This includes naming conventions, how they
are declared, different primitive types and naming conventions. After studying this section, you should have a firm
grasp of the types of variables available to you and how to work with different types in a web application.

Content
All variables in ASP are loosely typed. This means that you don't need to declare variables with a type. It also means
that you can assign the value of any variable to any other variable. There are a few exceptions to this rule as we will
see.
Basically, every variable in ASP has the major type of Variant. It is "variant" meaning that the type of value it holds
can vary. Basically, the ASP interpreter will handle all conversion between types automatically when you group
more than one variable or type together in a single expression.

Variable Scope
There are three different scopes for variables used in ASP. The first is page scope meaning that the variable is
available for the entire duration. These are typically declared at the top of the page. The second type of variables are
procedure scoped variables which are declared inside a procedure or function declaration. The third type of variables
are scoped with a class definition which is used for object-oriented programming.

<%
Dim sStr1 ' page-scoped variable
....

Procedure DoSomething
Dim mStr2 ' procedure-scoped variable
End Procedure

Function DoSomething
Dim mStr2 ' function-scoped variable
End Function

Class clsTest
Private msStr4 ' class-scoped variable
Public msStr5 ' class-scoped variable
End Class
Active Server Pages/Variable Types 9

%>

Page-scoped variables will be visible to all code included on your web page including procedures and functions. You
can even access page-scoped variables within a class although good object-oriented design would strongly
discourage this practice.
Procedure-scoped variables will only be visible within the procedure in which they are defined. It is perfectly
acceptable to use the same variable name for a page-scoped variable and a procedure-scoped variable. Keep in mind,
that when you do this, you will hide the page-scoped variable and will have no way to access it within the procedure.
Class-scoped variables can only be accessed through an instance of the class. There is no notion of static variables or
static methods in the simplified ASP scripting language. You will need to use the ObjectName.VariableName
syntax in order to access member variables directly. Only variable declared Public can be accessed in this way.
Private class variables can only be accessed by code defined within the class. More information about using classes
in Active Server Pages will be discussed later.

Valid Variable Names


To be valid, an ASP variable name must follow the following rules:
• Must begin with an alphabetic character
• All other characters must be alphanumeric or underscore ("_")
• Name must not exceed 255 characters in length
• Name must be unique within the scope it is defined
• Name must not be the same as a reserved word of built in functions, procedures, and objects.
Variable names, just like statements are case-insensitive. This means that if you declare a variable with the name
"myVar", you can access it using "MYVAR" or "myvar" or even "MyVaR".
One way to avoid using reserved words and make it easier to identify what type of variables you are using is to use a
naming convention. Usually the first letter or few letters of the variable names what information it holds.
Examples:
• nCount n for integer or number, holds a value that is used to count something, like for control loops.
• sName s for string, holds a value that represents a name.
• bIsActive b for boolean, holds true or false values, in this case true if something is active, false if it is not.
Following a naming convention can help avoid messy code, and leads to good programming habits. It also allows
somebody else to work with your code and help debug it or modify it. Along with a naming convention, use
comments as well to document what the variable is to be used for in the ASP page.
Examples:
• Dim nCount 'Used to count values in control loops.
• Dim sName 'Used to store the user's name that they enter in a web form.
• Dim bIsActive 'Used to test if the user's account is active.
You will learn more on naming conventions later on in this document.
Active Server Pages/Variable Types 10

Declaring Variables
To declare a variable, you use the Dim statement for page and procedure-scoped variables. After the Dim statement,
you can put a comma-separated list of variable names. If you prefer, you can just put one variable on each line. This
allows you to add comments about each variable you declare.

<%
Dim sAction ' form action
Dim sQuery ' database query
Dim I, J, K
%>

You should place your variables in a consistent location on the page or within your procedures. Typically, most
people place the declarations at the very top (beginning) of the page or the top of the procedure. Others think it
makes more sense to place the variable declarations right above the location where they are first used.

Primitive Types
When we talk about primitive types, we are talking about low-level variables types that cannot be broken down into
smaller primitive types. Basically, these are the "built-in" variables that Active Server Pages understands.
These are sometimes referred to the "sub-type" of the variable since the major type of the variable is "variant". Each
variable may have one of the sub-types shown in the following table. If you have used other programming
languages, then these primitive types will be very famaliar to you.

Type Name Values Memory Example

Boolean True or False 2 Bytes? true

Byte 0 to 255 1 Byte 127

String Any unicode characters Unlimited "unicode: ê"

Int -32,768 to 32,767 2 Bytes 147

Long -2,147,483,648 to 2,147,483,647 4 Bytes 3458972

Single 1.401298E-45 to 3.402823E38 (pos) 4 Bytes 23.546234


-3.402823E38 to -1.401298E-45 (neg)

Double 4.94065645841247E-324 to 1.79769313486232E308 (pos) 8 Bytes 43872452.23445


-1.79769313486232E308 to -4.94065645841247E-324 (neg)

Currency -922,337,203,685,477.5808 and 922,337,203,685,477.5807 8 Bytes 132412.34

Datetime 01/01/100 to 12/31/9999 8 Bytes '09/23/2004 12:34 AM'

Object An object reference 8 Bytes? Server.CreateObject("...")

Special Values
In addition to the values shown above, the following special values may also be assigned to Active Server Page
variables:
Active Server Pages/Variable Types 11

Type Name Values Memory Example

Empty vbEmpty 2 Bytes? vbEmpty

Null null 2 Bytes? null

The empty value is the default value for newly declared variables (never assigned any value.) If tested in a boolean
context, it is equivalent to "false" or tested in a string context it is equivalent to the empty string ("")

Conversion and Verification


You don't need to concern yourself much with setting the type of the variable. This is done pretty much
automatically for you. In the event that you want to set the type that is assigned to a variable, you can use the ASP
conversion function that corresponds to each type.
Also, there are verification functions available to make sure a variable is compatible with the specified type. This
doesn't mean that the variable has that sub-type. Rather, it means that the variable can successfully be converted to
the type.

Type Name Convert Verify

Boolean CBool n/a

Byte CByte IsNumeric

String CStr n/a

Int CInt IsNumeric

Long CLng IsNumeric

Single CSng IsNumeric

Double CDbl IsNumeric

Currency CCur IsNumeric

Datetime CDate IsDate

Object n/a IsObject

Empty n/a IsEmpty

Null n/a IsNull

Literal Values
Literal values are values you insert into your ASP code and use in expressions. By itself, a literal value has no use,
but when used in a statement such as an assignment or output statement

<%
' examples of literal values
Dim sString, nInt, fFloat, dDate, bBool

sString = "Hello There"


nInt = 1234
fFloat = -25.324
dDate = DateSerial(2004, 10, 28)
bBool = True
%>
Active Server Pages/Variable Types 12

You will notice that there is no way to specify a date literal in ASP. Therefore, you need to use a function call to
build a date value using DateSerial or you can use Now() to get the current date and time.
The value for a literal value is bound by the limits specified in the table for primitive types above. If you attempt to
use a value that is outside the acceptable range for any of the types, you will receive an error message indicating this
fact and your ASP page will terminate execution.

Constant Definitions
In some cases, you might want to create "named constants" instead of using literal values all of the time. This is
particularly useful if you create a common include file that will be used in multiple scripts on your site. You define
constants using the Const keyword like so:

<%
Const PI = 3.141592654
Const RECS_PER_PAGE = 25
Const FSO_FORREADING = 1
Const FSO_FORWRITING = 0
%>

It is common practice to use all uppercase variables for your constant definitions although this is not required. It
simply makes your code easier to read and maintain.

Naming Conventions
A naming convention is a standard way of naming all of the variables used on your site. There are various different
methods used for naming variables and a whole chapter could be devoted to this subject. One of the most popular is
hungarian notation where the first letter of the variable name indicates the dominant sub-type for the variable.

Type Name Letter Example

Boolean b bIsMale

Byte z zAge

String s sFirstname

Int n nAge

Long l lPageHits

Single f fScore

Double d dMass

Currency m mBalance

Datetime d dExpiration

Object o oFSO

The Microsoft standard proposed for Visual Basic is to use a 3-letter naming convention for their variables. This is a
little more clear for reading and maintaining code. Some would consider this overkill for a light-weight scripting
language.
Active Server Pages/Variable Types 13

Type Name Letter Example

Boolean bln blnIsMale

Byte byt bytAge

String str strFirstname

Int int intAge

Long lng lngPageHits

Single sng sngScore

Double dbl dblMass

Currency cur curBalance

Datetime dat datExpiration

Object obj objFSO

Active Server Pages/Expressions


Objectives
In this section, you will learn how to build expressions in Active Server Pages. After studying this section, you will
learn how to build an expression and learn how to combine varibles and string literals in combination to manipulate
data.

Content
An expression is a group of literal and variables which are organized in a structured format using operators. The best
example of an expression is a mathematical expression such as x + 3.
Expressions are made up of a collection of mathematical, comparison, bit-wise and logical operators as well as literal
values and ASP variables which are placed together for evaluation by the ASP Interpreter. Once an expression is
evaluated, it can be assigned to a variable, used as the argument to an ASP procedure or output on an ASP page.

Assignment
One of the most basic statements you can make in ASP is an assignment. This basically evaluates an expression and
places the result into a variable. The equals sign (=) separates the variable that gets the result (on the left side) and
the expression to build the result (on the right side).

<%
Dim nX, dX, sName, bIsAdmin

' assign literal values


nX = 13
dX = 7645.34
sName = "Barney Google"
bIsAdmin = True

' or you can assign complex expressions like


Active Server Pages/Expressions 14

Dim dDateTime

dDateTime = Now()
nX = 13 + 23 - 10
dx = (5 * nX) / 2.0
sName = "Barney is " & CStr(nX)
%>

Don't worry too much about some of the more complicated expressions found in this example. All of this will be
explained later in this chapter. You should note that the left side of the expression is always a variable. You are only
allowed to put a single ASP variable on the left side of the equals sign.

Evaluation Order
The way an expression is evaluated, depends on the operator precedence. Precedence is kind of an importance
assigned to an operator. Operators that have the highest precedence are evaluated first and those that have the lowest
are evaluated last. When two operators exist that have the same precedence, the operators are evaluated from
left-to-right.
Take for example the following expression:

dX = 6 - 3 * 4 + 2

In this example, you will see we have three different operators. The "+" and the "-" operator have the same
precedence while the multiplication operator (*) has a higher precedence. In this case, the multiplication takes place
first reducing the expression to:

dX = 6 - 12 + 2

Now there are two expressions that have the same precedence. In this case, we evaluate the left-most expression first.
After two more reductions we get the final result:

dX = -6 + 2
dx = -4

You should note also that if we had evaluated the expression from the other direction we would get a completely
different result. This order of evaluation follows the same method used in mathematics (if you remember your basic
algebra.)

Grouping Sub-Expressions
If you want to over-ride the default order-of-evaluation (precedence) for evaluating an expression, you can group
expressions that should be evaluated first in parentheses. You can thing of it as an expression embedded in another
expression or a "sub-expression".
If you remember the example from the previous section, we can modify it to change the order-of-evaluation like so:

dX = (6 - 3) * 4 + 2

And just like in Algebra, we know that we have to evaluate these sub-expressions first. So the first step in reducing
this type of expression is to evaulate the sub-expression:

dX = 3 * 4 + 2
Active Server Pages/Expressions 15

The final reduction will yield a result of 14 which is a completely different result than we got before. Be careful
about how you group your expressions. It can cause a lot of problems and increase the complexity of your code. If
you want to keep your code simpler, you can always create new variables to store the results of sub-expressions.

' Using variables to evaluate sub-expressions


Dim dX, dY
dY = 6 - 3
dX = dY * 4 + 2

Mathematical Expressions
The folowing table lists all of the binary mathematical operators. They are "binary" because they require two
arguments. The first argument is on the left-side and the second argument is on the right-side. So the operator "+" in
the expression "5 + 6" has the binary arguments "5" and "6".

Symbol Operator Example

+ Addition nX + 5

- Subtraction nX - 5

* Multiplication dX * 1.5

/ Division dX / -1.5

\ Integer Division dX \ 6

% Modulus (remainder) nX % 6

The following table lists all of the unary mathematical operators. A unary operator only has a single argument to act
on.

Symbol Operator Example

- Negation -nX

Of course you can combine binary and unary operators in one expression. The results of one binary operation might
serve as the argument to your unary operation.

' combining the binary "+" with the unary "-"


dX = -(nX + nY)

There are many advanced mathematical functions that can be used to do complex arithmetic which we will talk
about later. These will not be covered in this chapter.

String Operators
When working with strings, Active Server Pages provides a wealth of functions for manipulating strings. But since
we are only talking about operators that may be used in an expression, we will only be dealing with the one string
operator here: the string concatenation operator.
String concatenation means that you want to append one string to another. This operation is a binary operation
meaning that it takes two arguments: the left-side is the string you want to append to and the right-side is the string
that you want to append.

Dim sFirst, sLast, sFullName


sFirst = "Bill"
sLast = "Gates"
Active Server Pages/Expressions 16

sFullName = sFirst & " " & sLast

As you can see in the example above, we are using the string concatenation operator to append three string values
together: "Bill", " ", and "Gates". Two of the strings are stored in variables while the space character is just a string
literal.
You may concatenate as many variables as you want together using the string concatenation operator. It has been
shown that string concatenation under Active Server Pages is very inefficient. So if your page is performing slowly
and you have a lot of string concatenations, you should look for ways to eliminate them.

Comparison Operators
Comparision operators, as you might have guessed, are used to compare two different expressions and return a value
of "true" or "false". In most cases the two expressions being comparted will evaluate to a number, but it is possible to
compare string values, dates and booleans.
The following table lists the binary comparison operators. These operators require two expression arguments: one on
the left-side of the operator and one on the right-side. Just like mathematical expressions, you may combine
two-or-more of these expressions together. In the next section we will explain how to these are combined using
logical operators.

Symbol Operator Example

= Equality nX = 5

<> Inequality (Not Equal) nX <> nY

< Less Than nX < 5

> Greater Than nX > -5

<= Less Than or Equal nX <= 5 + nY

>= Greater Than or Equal nX >= dY * 5.0 - 2

These operators are most commony used in an If Then statement which will take an action based on the boolean
result of an expression. Unless you already have a boolean value stored in an ASP variable, you will need to write an
expression like the following:

If nX &gt; 60 Then Response.Write "You Passed!"


If nX &lt; 60 Then Response.Write "You Failed"

Of course, your expression can be as complicated as you want as long as it evaluates to a boolean value.

Logical Operators
Whereas mathematical expressions are used to manipulate numbers, logical operators are used to work with the two
boolean values "true" and "false". These operators are always used to combine two expressions that result in boolean
values.
Active Server Pages/Expressions 17

Symbol Meaning Example

And True only if both arguments are true, otherwise false nX > 5 And nX < 10

Or True if either argument is true, false only when both arguments are false nX < 5 Or nX > 10

In addition to these binary operators, there is also one unary operator:

Symbol Meaning Example

Not Negation, true becomes false and false becomes true Not (nX >
5)

The negation operator basically will give you the opposite value of the expression. So if the expression evaluates to
"true" and you perform the Not operation on it, it becomes "false". Conversely, "false" will become "true" when Not
is applied.
So using these logical operators, we can group many comparison expressions together to create a very complex
expression like so:

' example of a complex expression with four comparisons)


If (nX = 2) Or (nX &lt; 10 And nX &lt; 20) And Not (nY * 5.0 -
2 &lt;= 17.0) Then
Response.Write "Yes"
End If

The first comparison (nX = 2) looks just like an assignment. You can never put an assignment in an expression like
this. Assignment only occurs at the start of an expression, where the first symbol is an ASP variable which is
followed by the assignement (=) operator.
You will notice that we used parentheses to group the expressions. Even in some cases where parentheses are not
required, it sometimes makes your expressions easier to read when you put them in there.

Bit-Wise Operators
For advanced programming, Active Server Pages has operators for working with individual "bits". A "bit" is the digit
used in the binary number system and was formed from a contraction of the words "binary digit". It can only have
one of two different values: "0" and "1".
In the old days of computer, programmers were severely limited in storage and had to make the most of the available
storage. One way they did this was by combining multiple variables into a single "byte". This has carried through to
modern-day computer systems and this is why we need bit-wise operators.
In computer terms, we talk about "bytes". A byte is composed of 8 "bits" and therefore can have 2 ^
(raised-to-the-power) 8 or 256 possible values. An integer is composed of two bytes so it can have a value of 256 ^ 2
or 65536 possible values.

The 8 bits from a byte and their integer equivalents

+-------------------------------------------------------+
| Bit7 | Bit6 | Bit5 | Bit4 | Bit3 | Bit2 | Bit1 | Bit0 |
+------+------+------+------+------+------+------+------+
| 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 |
+-------------------------------------------------------+
Active Server Pages/Expressions 18

For all of the bits that are set (equal to 1) above, you need to add their integer equivalent to determine the resulting
byte value. So If bits 6, 4, 1 and 0 were set, the equivalent byte value would be: 64 + 16 + 2 + 1 = 83.
Going the other way around, we can convert an integer to binary. We just take the integer value and subtract the
biggest binary value we can and note the corresponding bit. We continue to do this subtracting binary values until we
come up with the resulting bit string:

' convert integer value (221) to binary


221 - 128 = 93 (binary 0x10000000)
93 - 64 = 29 (binary 0x11000000)
29 - 16 = 13 (binary 0x11010000)
13 - 8 = 5 (binary 0x11011000)
5 - 4 = 1 (binary 0x11011100)
1 - 1 = 0 (binary 0x11011101)

When working with the bit-wise operators, we sometimes have to convert between binary and integer like this and
vice-versa.
In Active Server Pages, bit-wise operators are only used on numeric expressions to manipulate individual bits. The
numberic expression can evaluate to integers, longs, single or double-precision numbers. After evaluating the
bit-wise operation, the resulting value will be compatible with the orignal arguments.
The following bit-wise operators require two arguments: one on the left-side of the operator and one on the
right-side.

Symbol Meaning Example

& Bit-wise And nX & 5

| Bit-wise Or nX | 48

^ Bit-wise Exclusive nX ^ 48
Or

<< Shift Bits Left nX << 2

>> Shift Bits Right nX >> 1

The following operators are "unary" operators meaning they only require one argument. The single expression
argument must be to the right-side of this operator.

Symbol Meaning Example

~ Bit-wise Negation ~ nX

Truth Tables
Truth tables display the results of the binary operators on a bit-by-bit basis. You can think of each bit in the
arguments being evaluated one-by-one. Bits are matched up based on their position in the bytes. So for a 16-bit
integer, each bit would be operated on individually and the resulting bits would be strung together in the same order
to generate the resulting number.
When viewing these tables, think to yourself "When performing a bit-wise and (&), bit 0 from argument 1 and bit 0
from argument 2 are anded together and the result is X. Next bit 1 from argument 1 and bit 1 from argument 2 are
anded together and the result is Y". And continuing on for all the bits in the arguments.
Active Server Pages/Expressions 19

And (&) Operator Truth Table

Arg #1 Arg #2 Result

0 0 0

0 1 0

1 0 0

1 1 1

Or (|) Operator Truth


Table

Arg #1 Arg #2 Result

0 0 0

0 1 1

1 0 1

1 1 1

Exclusive Or (^) Operator Truth


Table

Arg #1 Arg #2 Result

0 0 0

0 1 1

1 0 1

1 1 0

Negation (~) Operator Truth


Table

Arg #1 Result

1 0

0 1

Manipulating Date and Time Values


ASP has some built-in functions to manipulate datetime values. Thought technically not operators, we mention them
here for completeness since datetime is a valid data type and it is often necessary to calculate dates and times.
Active Server Pages/Expressions 20

Date and Time Functions

Function Purpose

Date Get the current date according to the local machine


dNow = Date()

Time() Get the current time as a datetime value according to the local machine
dTime = Time()

Now() Get the current date AND time according to the local machine
dNow = Now()

DateAdd(Interval, Number, Date Add a specific Number of Interval to the supplied date
DateAdd("d", 3, Now())

DateDiff(Interval, Date1, Date2) Calculate the number of Interval difference between Date1 and Date2
dDaysLeft = DateDiff("d", Now(), dBirthDay)

DatePart(Interval, Number, Date) Retrieve a specific part of a date such as the hour or month
DatePart("yyyy", Now())

DateSerial(Year, Month, Day) Construct a datetime value from the year, month and day components
dBirthday = DateSerial(1998, 12, 23)

TimeSerial(Hour, Minute, Construct a datetime value reflecting the time components.


Second) dNapTime = TimeSerial(14, 0, 0)

DateValue(DateTime) Convert a date string into a datetime value.


DateValue("12/23/1998")

TimeValue() Convert a time string into a valid datetime object.


dTime = TimeValue("10:51:43 PM)

Day(Date) Retrieve the day-of-the-month (0-31) for a specific datetime value


Day(Now())

Month(Date) Retrieve the month (1-12) for a specific datetime value


nMonth = Month(dBirthDay)

Year(Date) Retrieve the year for a specific datetime value.


Year(Now())

Hour(Datetime) Retrieve the hour (in 24-hour military time format [0-23]) for the datetime
value
Hour(Now())

Minute(Datetime) Retrieve the minute (0-59) component for a specific datetime value
nMinute = Minute(dBirthDay)

Second(Datetime) Retrieve the seconds (0-59) for a specific datetime value.


Second(Now())

FormatDateTime(Datetime) Format the specified datetime value in a standardized format


FormatDateTime(Now(), vbLongDate)

Information about optional arguments for these functions and valid interval types will be discussed in a later chapter.
You should note that none of the mathematical operators apply to datetime values. You must use the various
conversion and calculation functions above to manipulate dates.
Active Server Pages/Expressions 21

Line Continuation Operator


If you have a really long line in ASP that you would like to split into two lines, you can use the line continuation
operator. This is an underscore (_) placed at the end of the line that tells the ASP interpreter that statement or
expression continues on the next line.

if ((bDaysLeft < DateDiff("d", Now(), dBirthDay)) Or _


(bDaysLeft > DateDiff("d", Now(), dChristMas)) Then
Response.Write "Hooray!"
End If

In the example above, we use the line continuation to continue a boolean expression. You may use it to continue any
type of expression or statement. It makes sense to split up long lines for readability. Just be careful how you split
lines so that you don't make the line more confusing to read.

Summary
There are eight different types of operators in ASP:
• Assignment Operators
• Mathematical Operators
• String Operators
• Comparison Operators
• Logical Operators
• Bit-wise Operators
• Grouping Operators
• Line Continuation Operator
All but the assignement operators can be used for building expressions. Operators are evaluated based on precedence
and the grouping operators. If two operators have the same precedence, then the operators are evaluated from
left-to-right.
All date and time values must be manipulated using functions. The mathematical operators are invalid on datetime
values.

Review Questions
• What must be on the left-side of the assignment operator?
• What must be on the right-side of the assignment operator?
• What are the eight major types of operators?
• What is meant by operator precedence?
• Which operator is used to group expressions?
• How are datetime values used in expressions?
Active Server Pages/Expressions 22

Exercises
• Write the conditional expression to test a variable (nSpeed) is less than or equal to the speed limit (nSpeedLimit)
• Write an expression to convert a temperature in farenheit to degrees and vice-versa
• Create a function that calculates the number of days from now until Christmas.
• Create a page that inputs a user's birthday and then calculates how old that person is.

Active Server Pages/Conditionals and Looping


Objectives
In this section we will introduce the basic program flow-control statements available to you in Active Server Pages.
This includes conditional statement and looping constructs. After studying this section, you should have a good
understanding of how to use Active Server Pages to make decisions based on expressions. You should also
understand how to repeat a block of program code based on conditions you define.

Content
Conditional statements are used by your program to make decisions and decide what the program should do next. An
example of this would be deciding whether a user has entered the correct password for your site by comparing the
password entered with the correct password. If the user passes the test, they are sent to their account management
Web page. If they fail, they are sent back to the login screen with an error indicating the "password is invalid".
This kind of decision making is common in all programming languages. You need to master this aspect of Active
Server Pages in order to write dynamic web applications.
Another important concept is looping. Looping simply means that you repeat the same block of code multiple times.
Since you are going through the code once, going back to the beginning and repeating it again, the direction of
program execution looks like a loop (or a circle) which is why we call it looping. We will introduce you to all of the
looping methods available to you in this chapter.

Program Flow
In general, program flow starts at the very top of the page and continues all the way down the page in the same way
that you read a book. All pages are executed this way in ASP and it makes the code very easy to follow until you get
to conditional statements and looping constructs.
Because of the logical flow of the program, it is easy to trace through your program code and output debugging
information to see what your script is doing as it gets processed by the ASP interpreter. Through use of the
Response.End statement, you can place breakpoints in your script to stop execution at specific points. More about
this will be discussed later.
One topic that will not be covered in this section is procedure and object method calls. We will talk about these in
later sections.
Active Server Pages/Conditionals and Looping 23

Conditionals
A conditional statement is one where an expression is evaluated and based on the result one or more actions may be
taken. This allows you to check for a certain condtion and take a specific action that is required when the condition is
or is not met.

If-Then Statement
The "If-Then" statement is the most basic conditional statement. When put on a single line, this statement says "If
the condition is met, then do this." For example, we could test to see if someone is old enough to vote with:

If nAge > 18 Then Response.Write "Yes, you can vote!"

You may optionally, create an If-Then statement that encloses a block of statements. A block of statements means
more than one statement grouped together. In this case, the entire block of statements will be executed only when the
condition is met. We use indenting in this case to help us read the code and determine where the block starts and
ends.

If nAge > 18 Then


Response.Write "Yes, you can vote!"
bCanVote = true
End If

As you can see in this program block, the If Then statement defines the start of the program block while the End If
statement defines the end of the program block. The program block is indented to make it easier to match the start
and end of the block. All of the statements in this program block will only be executed if the conditional statement is
met (nAge > 18). When it is not, nothing will be done.

If-Then-Else
The If Then statement is great, but what if you want to perform two different actions. One action to be taken when
the condition is met and one action to be taken when the condtion is not met. That is what the If Then Else statement
was create to handle. It basically says: "If the condition is met, then do this, otherwise do this".

If nAge > 18 Then bCanVote = true Else bCanVote = False

As you can see from the example above, you can put the entire If Then Else statement in one line. In many cases,
you will want to avoid this since it tends to make the length of the line very long. Instead, you will probably want to
use the program block form like so:

If nAge > 18 Then


Response.Write "Yes, you can vote!"
bCanVote = true
Else
Response.Write "No, you can not vote."
bCanVote = false
End If

In this case, only one of the two program blocks will be executed. The first will be executed when the condition is
met. The second will be executed when the condition is not met. So you can think of the If Then Else statement as
saying "one or the other but not both".
Although we are using more than one statement in the program blocks shown above, you could also put a single
statement within each program block. For debugging purposes, you can even have no statements at all within a
Active Server Pages/Conditionals and Looping 24

program block. This allows you to comment out all the statements in a program block and your script will still run no
problem.
You will notice that in the conditional expression for the If Then statement, we did not have to enclose the condition
with parentheses "(" and ")". You can always use parentheses for grouping expressions together but they are not
required to enclose conditional statements.

Select Case
The If Then statements are great if you are just evaluating a "true" or "false" condition. But if you want to evaluate
an expression other than a boolean and take some action based on the result, you will need another mechanism. This
is why the ASP language includes the Select Case statement. This allows you to basically "select" from a list of
many cases, the action to perform.
The cases for a Select Case are all literal primitive values. You must have an "exact match" in order to match a
"case". You may include more than one value to match, but you may not define ranges of values to match, nor may
you define a pattern to match.

Select Case nAge


Case 15, 16
Response.Write "You are almost old enough to vote"
Case 17
Response.Write "You might want to register to vote"
Case 18
Response.Write "Yes, you can vote!"
Case Default
Response.Write "Catch-all for all other ages"
End Select

This select statement is a little deceiving, because it will only tell you that you can vote if the age is 18 and only 18.
If the age is greater than 18, then none of the specific cases will be matched. Instead, the optional catch-all case
(Case Default) will be executed when the age is greater than 18.
Of course, you don't need to include the Case Default if you don't need it. By leaving it off, you are basically saying
"do nothing if an exact match for a case is not found".
You can use any expression for the Select Case as long as it evaluates to a primitive type. You can not use an object
expression because there is no such thing as an object literal to compare it to. However, you can call an object
method that returns a primitive type and use this as the expression.
In the example shown above, you can see that we are using the carriage return to separate the Case from the block to
be executed. There is no need to terminate this type of program block. It is terminated by the instance of the next
case or the End Select. You may also put the case and the action to perform on the same line by using the colon (:)
as a statement separator:

Select Case nAge


Case 15, 16 : Response.Write "You are almost old enough to vote"
Case 17 : Response.Write "You might want to register to vote"
Case 18 : Response.Write "Yes, you can vote!"
Case Default : Response.Write "Catch-all for all other ages"
End Select
Active Server Pages/Conditionals and Looping 25

Looping Constructs
Looping constructs are used for repeating the same step over-and-over again. There may be many reasons to use a
loop. In database-driven web applications, you will often use a loop to iterate over each record returned from a
recordset.

For Next Loop


The "for next" loop allows you to repeat a block of code using an incremental counter. The counter is initialized at
the start of the loop and then incremented at the end of the loop. At the start of each repetition, the counter is checked
to see if it has exceeded the ending value. This is best explained by using an example:

For I = 1 To 10
Response.Write "I = " & I & "&lt;br&gt;"
Next

In this example, we have created a loop that is repeated 10 times. We know it executes exactly ten times because you
can read the statement as "for every whole integer from 1 to 10, do this".
The variable "I" is initialized with a value of 1 and the first repetition of the program block (indented) is executed.
The output will be "I = 1". Don't worry about the "<br>" part, this is just HTML code to create a line break on the
web page.
The second time through the loop, the counter (I) is incremented and takes on a value of 2. So the second line output
by this block is "I = 2". This process repeats as I is incremented one at a time until the counter exceeds the end value.
So in this case, the last line printed will be "I = 10".
In a more advanced case, we can change the way in which the index is incremented. If we wanted the counter to
increment by 2, we would write the For Next loop as follows:

For I = 1 To 10 Step 2
Response.Write "I = " & I & "&lt;br&gt;"
Next

The output of this code will be:

I = 1
I = 3
I = 5
I = 7
I = 9

This time we only get five values output by the loop. This is because we are incrementing the counter by 2 instead of
by 1 (the default.) Notice that we do not have to finish on the ending value (10). After incrementing the counter from
9 to 11, the loop checks to see if we have exceeded the ending value (10) and exits the loop.
You can also count backwards like this:

For I = 10 To 1 Step -1
Response.Write "I = " & I & "&lt;br&gt;"
Next

And of course, you can substitute expressions and variables for the starting and ending values and even the amount
to "step through" the loop:
Active Server Pages/Conditionals and Looping 26

For I = nX + nY To YourFunc(nZ) Step nStep


Response.Write "I = " & I & "&lt;br&gt;"
Next

Do While
Another looping construct is the Do While loop which will repeat a block of program code as long as the condition
is met. This is kind of like the If Then conditional statement in that it expects a boolean expression. Here is what it
looks like:

I = 1
bFound = False
Do While I < 10
Response.Write "I = " & I & "&lt;br&gt;"
I = I + 1
Loop

What we have here is a loop that does exactly the same thing as the For Next example shown in the previous
section. Why would you want to use this construct instead of a "for next"? The problem becomes obvious when it is
not easy to determine how many repetitions of the loop you need to do.

X = 239821.33
Do While X > 1
Response.Write "X = " & X & "&lt;br&gt;"
X = X / 2
Loop

In this case, we do not know how many times we will have to divide the value of X by two until we end up with a
value less than or equal to 1. So we just use the Do While loop to handle the logic for us.

Do Until
Almost identical to the Do While looping construct is the Do Until. It works exactly the same way except that it
repeats the program block until the condition evaluates to "true". You could basically do the same thing with "Do
While" by enclosing your expression with Not (expr), but the creators of ASP realized that the code would be cleaner
using this more logical statement.

X = 239821.33
Do Until X <= 1
Response.Write "X = " & X & "&lt;br&gt;"
X = X / 2
Loop

Here, we have created a loop that does exactly the same thing as our "do while". We just reversed the logic of the
conditional statement and changed the keywords to Do Until. In this case, it doesn't make the code that much cleaner
to read. But as we will see later, there are definite cases where you will want to use Do Until.
Active Server Pages/Conditionals and Looping 27

While
The While loop works exactly the same as the Do While except that it has a little shorter construct. Please read the
section on "Do While" to understand how this looping construct works.

X = 239821.33
While X > 1
Response.Write "X = " & X & "&lt;br&gt;"
X = X / 2
Wend

Unlike the "Do" loops, the While loop program block is terminated by the Wend statement.

Summary
Active Server Pages has many different control flow statements to handle the execution of your ASP page. The
conditional statements are: If Then, If Then Else and Select Case. The looping constructs are For Next, Do While,
Do Until and While. Conditional expressions in ASP do not need to be enclosed in parentheses ("(" and ")").
For Next loops manipulate a counter and repeat the program block until the counter exceeds the ending value. Do
While, Do Until and While loops repeat based on the evaluation of a boolean expression (meaning an expression
resulting in the value of "true" or "false").

Review Questions
• What types of conditional statements are available in ASP?
• What types of looping contructs are available in ASP?
• What are the three parameters for a For Next loop.
• How do you count backwards using a For Next loop.
• What loop would you use to repeat until a condition is satisfied?
• What loop would you use to repeat while a condition is satisfied?
• How do you terminate a program block for a Do While loop?
• How do you terminate a program block for a While loop?

Exercises
• Create a For Next loop that outputs integers from 10 to 100 that are evenly divisable by 10
Active Server Pages/Server-Side Includes 28

Active Server Pages/Server-Side Includes


Objectives
In this chapter we will discuss the use of server-side includes (SSI) to simplify the process of building and
maintaining a website. For maximum flexibility, I use SSI for both site templates and common code modules
(libraries).

Content
Server-side includes have been around long before Active Server Pages was ever conceived. Basically, it was
designed as a web server extension that looked for special macros contained inside of HTML comments. Nearly all
webservers support at least some subset of server-side includes. The most useful of these macros is the "server-side
include".
So when a web page is accessed, the web server would first scan the source file (or resource) that the visitor
requested. If no processing macros were found, then this file is simply delivered to the user without modification.
When a macro is found, the web server will do the appropriate processing of the macro (completely replacing the
HTML comment with the appropriate results). All of this is done before the content gets delivered to the user (or the
remote host).

What it Does
The specific processing directive we are interested in here is the server-side include. This allows you to import the
contents of another document into the current one. This is extremely useful for reusing common blocks of ASP code
and HTML. One of the most common uses of this is for creating a website template.
Another popular use is for creating code libraries that can be included in the web pages where you need them. I
typically create a generic site-wide library that all pages must include, a header and footer template, a database
library, an e-mail library and a form processing library. By reusing common code, you can eliminate the errors that
may occur when you copy code from one page to another.
There are two different types of server-side includes we will discuss here: "virtual includes" and "file includes". The
only difference is in the way that they access the directory structure for the website.

Virtual Includes
A virtual include will import the contents of another file based on the document root of the webserver. The path to
the file should begin with a slash (/) which represents the root of the website (not the root of the filesystem).
Internet Information Server (the default webserver for Microsoft Windows) may be configured so that you cannot
use a File Include to import the contents of a file from a parent directory. In this case, you will need to use the
Virtual Include to accomplish this task.
Shown below is an example of two virtual includes used to pull in a header and footer template into the current page.
Contained within an HTML comment (delimitted by ''), you will see the processing directive (#include virtual). The
path and filename inside the quotes is the resource we want to bring into the current document.

<!-- #include virtual="/lib/header.asp" -->

<h1>Hello World</h1>
Active Server Pages/Server-Side Includes 29

<!-- #include virtual="/lib/footer.asp" -->

It is important to note that you can import many different types of files into the current document. You should realize
that the webserver simply replaces the contents of the included file directly into your HTML document. Also, you
cannot embed any preprocessing macros inside an ASP code block (delimitted by <% and %>).
The include process works recursively, so that if you include one file that //also contains// server-side include
directives, then those will be included recursively so that all macros are processed.

File Includes
Another type of include statement is #include file. This statement works just like the virtual include except that the
path to the file must be relative to the directory where the current page resides. In other words, you cannot access the
directory structure starting from the document root (meaning the root of the website.)
Below is the same example as before with the virtual includes replaced with file includes. When running this script
under IIS, you may get an error when trying to access a parent directory in this manner. For this reason, I prefer to
use virtual includes whenever possible.

<!-- #include file="../lib/header.asp" -->

<h1>Hello World</h1>

<!-- #include file="../lib/footer.asp" -->

Alteratives to Server-Side Includes


Active Server Pages contains a couple of statements that work similar to server-side includes. These are also useful
for the same purposes as server-side includes. However, none is a substitute for the other. They all have their
different purposes and you should know when to use each.

Server.Execute
This will execute another Active Server Page file from the website. You can do this conditionally using the If Then
... End If syntax. This is different from the server-side include statement which will be executed wherever it appears.
Another difference between this statement and a server-side include is that all variables, functions and classes
defined in the calling script will not be accessible in the executed script. This is a huge barrier to using this as an
include and it is the main reason why I prefer server-side include to this statement.

If Application("ShowForum") Then
Server.Execute("/module/forum.asp")
End If

I have used this to build a modular web portal application with good success. Through a control panel, the user can
configure which modules they would like to display on their website. The template engine checks this configuration
and pulls in only the modules that we need to display and arranges the layout accordingly.
Active Server Pages/Server-Side Includes 30

Server.Transfer
The Server.Transfer statement is similar to Execute in that it executes an external ASP file on the webserver.
However, unlike Execute, this function does not return control to the calling script. Instead, control is transferred to
the script and, when the script finishes execution, the processing of the request terminates.
This is useful for use as a redirect. Basically, you test for certain conditions in your script and transfer control to
another script based on which condition is met. So maybe you could have a login page that contains a form which
posts to itself. If the user login is authenticated, you can transfer processing to a member control panel.

If bIsLoggedIn Then
Server.Transfer("/account/index.asp")
End If

You should note that if any HTML is output to the browser before the Server.Transfer statement is reached, the
output of the new ASP file will be appended to the HTML that has already been output. While you could do a
standard redirect using the ASP built-in statement Response.Redirect, that would discard any HTML that has
already been output and rebuild the response from the beginning.

Summary
Server-side includes provide a powerful mechanism to reuse code in Active Server Pages. You can use it to create a
website template, code libraries, and HTML modules which may be reused throughout your site.
The two types of include statements are the virtual include and the file include. Use the virtual include to include
ASP or HTML files using a path specifier that begins with a slash (/) denoting the document root of your website.
The file include includes the content of a file with a path specifier that is relative to the directory of the calling
script. The contents of the external file will be imported into the original document before any ASP code is
processed.
Alternatives to server-side include the Server.Execute statement which executes the external file as a stand-alone
script and then combines this output with the output of the calling script. The other is the Server.Transfer statement
which passes control over to the external script permanently (control never returns).

Review Questions
• What does a server-side include do?
• What are the two types of server-side includes?
• What happens if you include a file which contains server-side includes?
• What are some alternatives to the server-side include?
• Explain how these alternatives work to execute external ASP code
Active Server Pages/Server-Side Includes 31

Exercises
• Create the include files (header and footer) for a real simple HTML template
• Write a virtual server-side include to import the HTML template files.
• Write some ASP code to call Server.Execute to display a weather module
• Write some ASP code to call Server.Transfer to log off a user from a member area.
Article Sources and Contributors 32

Article Sources and Contributors


Active Server Pages  Source: http://en.wikibooks.org/w/index.php?oldid=1489964  Contributors: Adrignola, EvanCarroll, Jguk, Kencyber, Kernigh, ManuelGR, Mkn, Mpoulin, Panic2k4,
Quarx, Rgeis, Robert Horning, Trapdoor, Vera64, Webaware, Wknight8111, 40 anonymous edits

Active Server Pages/ Prerequisites  Source: http://en.wikibooks.org/w/index.php?oldid=1479297  Contributors: Adrignola, EvanCarroll

Active Server Pages/ Differences between ASP 3. 0 and ASP. NET  Source: http://en.wikibooks.org/w/index.php?oldid=1360617  Contributors: Chrisbbehrens, Derbeth, Jguk, Kencyber,
Panic2k4, Webaware, 9 anonymous edits

Active Server Pages/ Your first page  Source: http://en.wikibooks.org/w/index.php?oldid=1069798  Contributors: Daniel USURPED, Jguk, Kencyber, Mpoulin, Quarx, 7 anonymous edits

Active Server Pages/ Basic ASP Syntax  Source: http://en.wikibooks.org/w/index.php?oldid=1479293  Contributors: Adrignola, Dysprosia, EvanCarroll, Jguk, Kencyber, Orion Blastar, 42
anonymous edits

Active Server Pages/ Variable Types  Source: http://en.wikibooks.org/w/index.php?oldid=1433571  Contributors: Cjw0527, Jguk, Kencyber, Orion Blastar, 12 anonymous edits

Active Server Pages/ Expressions  Source: http://en.wikibooks.org/w/index.php?oldid=998052  Contributors: Jguk, Kencyber, 2 anonymous edits

Active Server Pages/ Conditionals and Looping  Source: http://en.wikibooks.org/w/index.php?oldid=998050  Contributors: Jguk, Kencyber, 4 anonymous edits

Active Server Pages/ Server- Side Includes  Source: http://en.wikibooks.org/w/index.php?oldid=1479301  Contributors: Adrignola, Kencyber, 2 anonymous edits
Image Sources, Licenses and Contributors 33

License
Creative Commons Attribution-Share Alike 3.0 Unported
http:/ / creativecommons. org/ licenses/ by-sa/ 3. 0/

You might also like