INT213 Week 2

waisttherapeuticSoftware and s/w Development

Nov 4, 2013 (3 years and 9 months ago)

76 views

INT213


Week 2

Variables and State Management


Welcome



Overview for this week



VBScript and ASP



Working with Variables and State Management



Lab 2: creating ASP pages and Passing data between pages



Resource: Seneca Electronic Research Collection



http://libr
ary.senecacollege.ca/Library/DB/databases_all.html



Books 24x7



Safari


our textbook is available here

VBScript



What is VBScript?



VBScript is a subset of Visual Basic



Scripting Language vs. Programming Language



The downside of Scripting



Interpreted in a Hos
t at runtime vs. Compiled



Many hosts available, including Windows Script Host (WSH), Office
applications like Word, Outlook, etc., IIS for web development.



Scripts run slower

they have to be interpreted at runtime every time



There is no static checking to
see that variables and structures in your code are
“error free”. You have to test your script yourself to make sure things aren’t
broken. A compiler does this for you.



The Upside of Scripting



You can embed the scripts within other types of files and appl
ications. Compiled
code is stand
-
alone.



Script languages allow you to do things dynamically with variables, memory, etc.
in a more flexible way than compiled languages.



Scripting is faster to develop in, and more forgiving. It is meant to be used for
sma
ller jobs, and as a glue to connect more stable stand
-
alone
objects/applications.



Loosely Typed vs. Strongly Typed



A strongly typed language forces the programmer to declare, in advance, the data
type of every variable so that the compiler will know exactl
y what kind of value
to expect in that variable



In a loosely typed language, the programmer does not have to declare in advance
the data type of a variable. Usually, in fact, a loosely typed language does not
even provide a way to declare the data type.



VB
Script is Loosely Typed


Variables in VBScript




What is a Variable?



A variable is a name given to a location in memory where some data used by a program
is stored




You create a variable in VBScript using the Dim keyword:



Dim really means Dimension, or “Loc
ate and set aside enough memory to hold a Variant
and give it a name”



Dim <variable name>[, <variable name>…]



You can specify one or more variables to be declared on the same line, for example:

Dim x, y, z


vs.


Dim x

Dim y

Dim z



You can’t specify a value
on the same line as the Dim keyword, for example, this will
cause an error:

Dim x = 7




Variant


the Universal VBScript Data Type



VBScript is Loosely Typed: there is no concept of Data Type in VBScript

everything is
of type
Variant
. Unlike Visual Basic, t
here is no As keyword, since there is no need to
declare a type.



Internally, Variant is wide enough to hold the largest possible data types, so everything
fits.



The script host does keep track of data types behind the scenes using Variant sub
-
types.



A Vari
ant variable automatically chooses its subtype whenever you place a new value
into it. It does this by examining the value placed into it and making its best guess as to
what the appropriate subtype is, for example, put a string in a variable, it becomes a

string, use a number, it’s a number, etc.



We’ll learn later how to Coerce a variable from one sub
-
type to another using built
-
in
functions (e.g., CInt, CLng, CBool, CDate, etc.)




Naming Variables: What constitutes a valid variable name?



You must begin wit
h an alpha character.



All of the following are ok: strName, Some_Thing, Fruit



All of the following are not ok: +strName, 99RedBalloons, @Test



You can use any alphanumeric character, and also the Underscore, as long as you follow
the first rule (e.g., Two
_Words vs. TwoWords)




Your variable names must be less than 255 characters.



Make them short, but meaningful.



Your variable names should make clear their purpose



Variable names are NOT case sensitive.



You can’t use VBScript keywords (e.g., Dim)




Variables
vs. Literals vs. Constants



A literal is simply a string, number, date, etc. that you enter manually, or hard
-
code into
your script, for example:



WScript.Echo “Hello World” ‘ String Literal



MsgBox #5/16/99 12:30 PM# ‘ Date Literal



Response.Write 3 ‘ Numeric

Literal



A Variable is like a literal, but it can change at run
-
time. Once a variable is declared, you
can access its value by using its name anywhere a literal would normally be used.
Consider:

Dim x

Dim y

x = 1

y = 2

x = x + y



A Literal is throw
-
away i
n the sense that you can’t change it after you use it. Unlike a
variable, it has no name by which we might access it again. Consider:

Dim x, y, z

x = “INT213”



y = “Course: “ & “INT213”



z = z & “, INT213”



Here we are repeatedly using the String Litera
l (i.e., it is not a String Variable
because it is hard
-
coded into our script) “INT213”. We should consider making a
variable to hold this string instead of repeating it every time to reduce the chance we
misspell it, and also to make it easier to change
later (e.g., if we want to re
-
use the
script for a new course):

Dim course

course = “INT213”



y = “Course: “ & course



z = z & “, “ & course



There is another step we can take. If we know that the value of the variable will never
change, we can create a
Constant:

Const COURSE = “INT213”



Notice the use of Const instead of Dim. Also notice that the name COURSE is all in
capitals. This is the convention in most languages to show that something is constant
instead of variable. Finally, notice that we can p
rovide a value on the same line as the
declaration. Since it can never change, it needs to get a value as soon as it is
declared.



Constants also allow us to create more readable scripts. Consider a script for dealing
with numeric error codes:

Const DRIVE
_FULL = 10005

Const NO_DISK = 10006

Const BAD_DATA = 10007



This makes it much easier for you and other programmers to understand what
the numbers mean later on in code. Whenever DRIVE_FULL is encountered
in the script, the engine will instead see 10005, f
or example:

Dim error

error = DRIVE_FULL

MsgBox error



You will encounter lots of built
-
in named Constants in VBScript, for example:

MsgBox "Drive error!", 48

MsgBox "Drive error!", vbExclamation




Option Explicit



Why bother declaring variables at all?



Decla
ring variables in VBScript is optional, but recommened. If you misspell a variable
name, VBScript hosts will simply create a new variable in memory for you. You’ll get
no error, just a strange result that can be hard to debug. Consider:


lngFirst = 1

ln
gSecond = 2

lngThird = lngFirst + lngSecond

MsgBox lngThird


vs.


lngFirst = 1

lngSecond = 2

lngThird = lngFirst + lgnSecond

MsgBox lngThird





You might think, “Hey, this isn’t a big deal, I’ll catch the error when it gets printed.”
Maybe, but what if you

are working with really large or really small numbers? And what
if you aren’t printing anything, just adding records to a database?



Option Explicit tells VBScript that our code requires that all variables be explicitly
declared before they can be used



NO
TE: in ASP pages, you do this:


<%Option Explicit%>

<html>



</html>




Variable Scope and Lifetime



A variable’s scope is a boundary within which a variable is valid and accessible. The
boundary within which a variable is declared is directly related to the
lifetime of that
variable.



Script
-
level scope: Script
-
level scope means that the variable is available to all of the
scripts within a script file. Variables that are declared outside of the boundaries of a
VBScript procedure, function, or class automatical
ly have script
-
level scope.



Procedure
-
level scope: Procedure
-
level scope (also known as “local” scope) means that
the variable is available only within the procedure or function in which it is declared.
Other code outside of the procedure, even if that cod
e resides within the same script file,
cannot access a procedure
-
level variable.



A variable declared within a script file, but not inside a Procedure is “global” to the
script, meaning that you can access it from any other part of the script.



The Lifetime

of a variable is tied to its scope.



Variables that are declared at the Script level live in memory as long as the script is
running.



Variables declared as part of a Procedure live only as long as the procedure is
executing. This is nice because you can r
e
-
use the same variable many times over
with different calls to the procedure.



Try to declare your variables where they get used. Don’t make everything global unless
absolutely necessary. Try to use Procedures to return values instead of working with
glo
bal variables, since it saves memory.



Saving a bit of memory may not seem like a big deal with there is only 1 instance of
your script running. But on a web server, there can be thousands of simultaneous
instances of your script running, all creating vari
ables and competing for the same
memory resources.




Exercise
: Examine Sample Script from Textbook


ASP




What is ASP?



Active Server Pages


What makes them “Active”? Why “Server”?



ASP files are like HTML files, but can contain text, HTML, VBScript, XML, et
c.



An ASP Web Application will be a collection of file types:



.html



.asp



Global.asa (an application initialization file, which we’ll visit later)



.inc (include files, which contain commonly used scripts)



images, and other static resources



Server
-
side scrip
ts get run by the server before the page is served. The client does not
have access to the script.




ASP files have an .asp extension.



You need to put them in a location managed by IIS so that the server can make them
available to outside requests, for exa
mple C:
\
Inetpub
\
wwwroot



Your .asp file will contain a mixture of HTML and VBScript. The VBScript gets embedded
in the HTML using the special tags <% … %>



These tags are not HTML. Rather, they tell the ASP Scripting Host (i.e., asp.dll) that the
text cont
ained within is VBScript that needs to be executed prior to serving the HTML to
the client.



We make calls to one or several of the ASP intrinsic objects to create the dynamic element of
the page.



ASP provides a set of intrinsic objects that allow us to acc
ess information about the request
being made of the server, as well as the response that the server will send:



Response, Request, Application, Server and Session



Also, we can incorporate any standard COM object (or active server component, as we call
them)

into a page. For example, we can interact with Databases, the server’s Filesystem, etc.
by using VBScript to call “functions” in pre
-
compiled COM objects that “wrap” this
functionality.


The Intrinsic ASP Objects:




Response



The Response Object is used to

send output to the user from the server.



The Response object is basically like a file. You can Write data to it (including
variables) and this gets passed over the network to the client’s browser as part of the
HTML body or HTTP Headers.



For the most par
t, we’ll use Response.Write to send data to the client’s browser, for
example:



Response.Write “Today’s Date is” & Now



You can also use Response to do server
-
side redirects:



Response.Redirect “update.asp”



You can also use Response to set Cookies on the clie
nt machine (if the client accepts
cookies). This is State Management on the client
-
side:



Response.Cookies(“user”) = “dhumphrey”



Response.Cookies(“lastpage”) = 17



By default this would expire when the client browser was closed. But we can extend
this:



Res
ponse.Cookie(“lastpage”).Expires = #Jan 10,2007#



Be careful with cookies though: cookies must be set BEFORE any HTML gets sent to
the client, since they are part of the HTTP headers, not the HTML body. If you send
<html>, ASP/IIS will first end the HTTP H
eaders, so it will be too late to set the
cookie.




Request



When a browser asks for a page from a server, it is called a request. The Request Object
is used to get information from the user.



If Response is for Output, Request is for Input. You use Request
to access variables, be
they Server variables, Cookies, Form values, the Query String, etc.



Form



HTML form elements are named, just like VBScript variables. We can access the
value of Textboxes, Radio Buttons, Drop Down Lists, etc. by accessing the Form
c
ollection, for example:

Dim customer

customer = Request.Form("customerName")



More on Form variables next time…



Cookies



Cookies are small text files of Key/Value pairs that can be stored on a client
machine.



When I go to Amazon.ca, I see this:



Hello, David
Humphrey. We have Recommendations for you. How do they
do this? Cookies. My browser is sending them information that tells them
who I am when I reconnect to the site.



Dim username



username = Request.Cookies(“username”)



Response.Write(username)



Query St
ring



When I go to one of my courses in Blackboard, the URL of the site looks
something like this:



http://my.senecacollege.ca/webapps/portal/frameset.jsp?tab=courses&url=/bin
/common/course.pl?course_id=_269560_1



The course I’m looking at is _269560_1, which

is some primary key value in
a database somewhere.



Dim course



course = Request.QueryString(“course_id”)



ServerVariables



Allows access to various Server Variables, including information about the Server
itself, the HTTP headers, the client, etc.



For exampl
e, to determine the client’s IP Address:



<% Response.Write(Request.ServerVariables("REMOTE_ADDR")) %>



Server



The ASP Server object is used to access properties and methods on the server, for
example, if you want to read/write files on the server, or connec
t to a database.



More on Server later in the course.



Session



HTTP is a stateless protocol, meaning that each connection between a client and server
gets torn down when the request/response is completed. However, web applications
involve many round trips f
rom the client to the server.



IIS/ASP create a unique session cookie for each client so that repeated connections by the
same client within a given timeframe can be associated. This is helpful because it allows
us to store information on the server in Ses
sion Variables between requests by the client
(e.g., a shopping cart).



In VBScript we have access to these Session Variables using the Session object.



Session Variables are per
-
user, so if 2 people are connected to your site, you’ll have 2
separate Session
s with their own sets of variables.



The server creates a new Session object for each new user, and destroys the Session
object when the session expires.

Request.Session(“Colour”) = “Blue”


or


Dim chosenColour

chosenColour = Request.Session(“Colour”)



Appl
ication



Application is just like Session except that there is only 1 Application for ALL users of
the site. This is useful if you want to store global information for everyone.

Request.Application(“count”) = Request.Application(“count”) + 1