BMIS 289: Spring 2002 Gonzaga University - PowerPoint PPT Presentation

1 / 65
About This Presentation
Title:

BMIS 289: Spring 2002 Gonzaga University

Description:

a href='http://cnn.com?news=sports' BMIS 289: Spring 2002. Making QueryStrings cont. ... Breaking It Down. Dim i. For i=0 to Ubound(Scores) ... – PowerPoint PPT presentation

Number of Views:174
Avg rating:3.0/5.0
Slides: 66
Provided by: barneyG
Category:

less

Transcript and Presenter's Notes

Title: BMIS 289: Spring 2002 Gonzaga University


1
BMIS 289 Spring 2002Gonzaga University
  • Class 07Request/Response, Sessions/CookiesAr
    rays

2
Agenda
  • Program 5 Overview
  • Data type conversion note
  • Request/Response
  • Sessions Cookies
  • Arrays
  • Midterm Overview

3
Program 5
  • This program has three distinct parts
  • 1. Ask how many checks the user wants to input.
  • 2. Generate that number of check input forms.
  • 3. Collect the information from the check input
    forms and compute a new check register balance.

4
Program 5 Step 1 (page 1)
  • This is a simple input form (no different than
    what weve done before).
  • We capture three separate fields
  • Account owners name
  • Beginning balance
  • Number of checks to input (1-5)

5
Program 5 Step 2 (page 2)
  • First we retrieve the form information from page
    1, store them in variables, and then write them
    as hidden HTML input form fields in our page 2
    form.
  • We will need this information in page 3 later.
  • Using hidden form fields assures us that the data
    will get passed on to page 3 when the page 2 form
    is processed (but hides it from the user)

6
Program 5 Step 2 (page 2)
  • On page 1 we asked how many checks the user
    wanted to input, so now we must generate those
    input fields.
  • Each check has common input fields (check number,
    amount, deposit/check, etc).
  • Since we know the number of check inputs we need
    to generate (from page 1) this action would be
    perfect for a loop.
  • The only problem is that the HTML form fields
    must have unique names.

7
Program 5 Step 2 (page 2)
  • If we were hard coding this page we might choose
    to name each field like so
  • CheckNumber1, CheckNumber2
  • CheckAmnt1, CheckAmnt2
  • CheckDate1, CheckDate2
  • Our loop code could accomplish the same thing,
    for example
  • FOR count1 to 5 current_cnum check_number
    count Response.Write
    name current_cnum NEXT

8
Program 5 Step 3 (page 3)
  • On this page we must echo the check inputs from
    page 2 AND calculate a new balance for the check
    book.
  • Again we must perform a loop, but this time we
    want to extract the information entered into the
    check fields (instead of generating the fields).
  • As on page 2, each time through the loop the a
    unique html field name must be generated. Only
    now we pass that field name into Request.Form()
    to extract the corresponding input.

9
Program 5 Step 3 (page 3)
  • Once we have extracted the inputs for a
    particular check we then output the check
    details, and compute any changes to the balance.
  • If the check was a deposit then add to the
    running balance.
  • If the check was not a deposit then subtract from
    the running balance.
  • When the loop ends we will have our new balance.

10
A note about data type conversion
data_type_conversion.asp
  • We would assume that this code converts the
    balance variable to the currency data type

TypeName(balance) "
" balance
ccur(balance) Response.Write TypeName(balance)
"
" balance 12.00 Response.Write
TypeName(balance) "
"
11
Data type conversion cont.
  • The actual output looks like this
  • The first conversion does, indeed, change the
    data type of the variable to Currency.
  • However, when 12.00 is assigned to the variable
    ASP automatically converts it to double.
  • To avoid these misconceptions you should do data
    conversion on every line that requires it.

EmptyCurrencyDouble
12
Request Response Refresh
  • Recall that HTTP consists of two forms of
    communication the Request and Response.
  • HTTP Request
  • Message going from Browser ? Server
  • HTTP Response
  • Message going from Server ? Browser
  • Weve already covered methods like Response.Write
    and Request.Form, but there are others

13
QueryString
  • A querystring is simply a collection of variables
    and their associated values that are appended to
    the end of a URL.
  • Take this example URL
  • http//gonzaga.edu?variable3
  • Here we have one querystring variable (called
    variable), with the value 3, appended to the
    end of the URL http//gonzaga.edu

14
QueryString cont.
  • A querystring is indicated by adding a ? to the
    end of a URL and then appending variable/value
    combinations.
  • A querystring can contain multiple variables
  • http//gonzaga.edu?v13v2hello
  • Here we have two variables v1 and v2 with values
    of 3 and hello respectively.
  • Notice how the symbol was used to separate
    the two variables.

15
Making QueryStrings
  • There are three primary ways to create URLs with
    query strings
  • User types the query string manually into the
    browser address bar (not likely to happen).
  • Embed querystring into HTML directly.
  • Use GET method when posting form data.
  • Embedding a querystring into HTML

16
Making QueryStrings cont.
  • Using the form method GET
  • If you use GET, instead of POST, as the value to
    the METHOD attribute of an HTML form then your
    browser will automatically generate the
    querystring to send to the server.
  • typetext nameusername
    typesubmit valuesubmit
  • If I enter cfukai into the username text field
    then this querystring will be appended to the end
    of process.asp
  • ?usernamecfukai

17
Getting QueryString Values
  • A querystring is very similar to using a form to
    POST data to an ASP page.
  • Likewise, retrieving the data from a querystring
    with ASP is very similar.
  • Request.QueryString()
  • me)
  • This is a lot like Request.Form()

RequestQueryString.htm, RequestQueryString.asp
18
The Buffer
  • In ASP, the buffer is a temporary storage space
    on the server where an HTML stream is held before
    being sent to the client.
  • When you add into the buffer it is added to the
    end, like a queue. The Response object has
    properties and methods we can use to manipulate
    the buffer
  • Buffer, Flush, Clear, End

19
Response.Buffer
  • This is a property than can have two values
    true, false
  • Must be set before any HTML is written to the
    browser.
  • It is used to tell ASP that we will be manually
    controlling when the HTML stream is sent back to
    the browser.
  • Response.Buffer is true by default in Win 2000,
    false by default on NT4.

20
Buffer Methods
Buffer_manip.asp
  • Flush this is a method that sends any already
    buffered HTML directly to the browser.
  • After it is called ASP continues processing the
    rest of the page and returns anything else.
  • Clear erases any already-buffered HTML, but not
    any HTTP Response Headers.
  • End stops processing of the ASP script and sends
    any buffered output to the browser.
  • See example on page 274-275.

21
Redirection
Redirect_Menu.htm, Redirect.asp
  • Sometimes we want our code to redirect its
    execution to another page.
  • Syntax Response.Redirect
  • Response.Redirect ends the execution on the page
    that called it and transfers it to the page that
    is called.
  • Note this does not transfer variables or any
    other data from our code.
  • Execution never returns back to the page that
    called Response.Redirect.

22
Redirection
  • Redirection is often used on login pages.
  • We could have a login page that would redirect to
    an error page if the user failed to login
    appropriately.
  • Example
  • mypassword
    Then Response.Redirect error.asp End If

23
Web Applications
  • A web application is a program that is written
    for the web.
  • A web application is like any other program. The
    primary difference is that the browser is the
    interface.
  • Web applications are made up of several pages,
    databases, and other support files that act as
    one application.

24
Maintaining State
  • The key to writing any sort of web application is
    identifying every unique user of our application
    and tracking them, and their actions, as they
    move from page to page.
  • AKA maintaining state
  • Unfortunately, HTTP was designed to be stateless.
    All it really cares about is delivering HTML.
  • ASP provides some tools to overcome this
    weakness
  • Cookies, Sessions, Application Variables

25
Cookies
  • Cookies are simply small text files that are
    written to a users hard drive by their browser.
  • They contain variables and their associated
    values.
  • For example, many sites offer a auto-login
    feature. This is accomplished by
  • Writing a cookie to the users hard drive that
    contains the valid user name and password they
    entered.
  • When the user returns to the site an ASP page
    checks to see if a cookie it wrote exists on the
    users hard drive. If it does, ASP can then take
    the information from the cookie to login
    automatically.

26
Cookies cont.
  • Domains (e.g, gonzaga.edu) and servers can only
    read cookies they have set.
  • So gonzaga.edu cant read cookies set by cnn.com
  • ASP writes cookies using the Response object, and
    reads cookies using the Request object.
  • Cookies are very popular because they are stored
    on the client (and not the server), but a user
    may elect to disable cookies in their browser.

27
Setting A Cookie
  • Syntax
  • Response.Cookies()
  • Where is the name of the cookie,
    and is the value that variable will have.
  • Example
  • onse.Cookies(Email) Email

28
Reading From A Cookie
Cookie1.asp, cookie2.asp, cookie3.asp
  • Syntax
  • Request.Cookies()
  • Where is the name of a cookie.
  • This method returns the value that is currently
    in that cookie.
  • Example
  • According to the cookie, your email is Request.Cookies(Email)

29
Persisting A Cookie
  • By default, when you set a cookie the browser
    automatically destroys it once the browser is
    closed.
  • To save it on the users hard drive (the cookie
    jar ?) we need to set an expiration date for it.
  • Example
  • cfukai_at_gonzaga.edu Response.Cookies(Email).Ex
    pires Date 30
  • This code sets a cookie that will persist for
    about 30 days from the date it is set.
  • Date is the current date on the server.

30
Deleting A Cookie
  • To delete a cookie set the expire date to any
    date prior to the current day.
  • Example
  • 30
  • This method might fail though, depending on how
    the user has their time configured, but most
    users should have their machines configured to
    within a month of the actual date.

31
Sessions
  • Sessions are a way for ASP to track every unique
    user of our web application as they move from
    page to page.
  • A users session begins when they access their
    first .asp page on the web site. The users
    session continues as they move from page to page.
  • In ASP we use the Session object to add
    information about a users session and read
    information from it.

32
What We Can Do With Sessions
  • Sessions let us do three primary things
  • Store information about each users session
    (e.g., form inputs) using session variables.
  • Be notified when a user session begins.
  • Be notified when a user session ends.

33
Setting A Session Variable
Session1.asp, Session2.asp, Session3.asp,
Session4.asp
  • We dont have to declare session variables.
  • The first time we use them they are automatically
    declared.
  • We can access session variables as long as the
    users session is active.
  • Example
  • Page1.aspRequest.Form(Email)
  • Page2.aspYour email address is Session(Email)

34
Global.asa
  • When we talk about sessions and web applications
    we need to consider a file called global.asa
  • This file includes event handlers, which are sub
    procedures that allow us to run code when certain
    events (like a user session beginning) occur.
  • The global.asa file must be placed in the root of
    the web applications virtual directory.

35
Global.asa Example
Global.asaPage.asp
  • Global.asa
  • Page.asp

Sub
Session_OnStart Session("30DaysAgo") Date -
30 End Sub

36
Session Event Handlers
  • There are two separate session event handlers
    that can be used in global.asa
  • Session_OnStart
  • Session_OnEnd
  • The Session_OnStart handler is run every time a
    user session begins on the web server.
  • The Session_OnEnd handler is run every time a
    users session ends.

37
Ending A Session
  • There are two ways a users session can end
  • The session times out
  • The session is abandoned
  • Timeout
  • If a user is inactive for longer than a
    pre-determined period of time then the session
    automatically ends.
  • This time can be set through the Session.Timeout
    property
  • Session.Timeout 30
  • This line sets the session time out to 30
    minutes, by default it is 20 minutes.
  • Abandon
  • A session can be manually ended by calling the
    Abandon method of the session object

38
Application Variables
  • Application variables are similar to Session
    variables. Once you set an application variable
    it is available on any page in your web
    application.
  • The difference is that application variables can
    be accessed by all users of the web application.

39
Setting App. Variables in Global.asa
  • Typically, application variables are set in
    global.asas Application_OnStart event handler
  • Sub Application_OnStart Application(MainPhone)
    555-5555End Sub
  • This application variable can be accessed on any
    page in the web app
  • Phone

40
Setting App. Variables In A Page
  • Setting application variables in an ASP page is a
    little different.
  • Suppose we let a user change the application
    variable and while theyre doing that their
    machine locks up.
  • While the web server was waiting for the locked
    client to finish changing the application
    variable another user could change the
    application variable, causing data corruption.

41
Setting App. Variables In A Page Cont.
  • To avoid this we want to lock the application
    variable were changing (so no other clients can
    change it), change it, and then unlock it
    again.
  • Example
  • 555-5551 Application.UnLock

42
Application Event Handlers
  • Also, like sessions, the application object has
    two event handlers in global.asa associated with
    it
  • Application_OnStart
  • Application_OnEnd
  • Application_OnStart is called the very first time
    a user accesses the web application.
  • Application_OnEnd is called immediately after the
    last active session within that application ends.

43
Break
44
Arrays
  • Variables are handy ways for storing individual
    items of data, but theyre not so good if you
    want to store a lot of related information.
  • An array is the programming construct we can use
    to store related data.
  • Arrays are simply a collection, or a list of
    variables.

45
Arrays Cont.
  • Arrays look a lot like normal variables but they
    have two separate parts to their name
  • The first part is the name itself, which is the
    same for every variable in the array.
  • The second part is a number that is to the right
    of the array name and is surrounded by
    parenthesis. This number is used to access
    individual items in the array.
  • Suppose we had a list of scores called Score
  • The first score would be Score(0), the second
    score would be Score(1), the third Score(2),
    and so on

46
Array Indexes
  • The number to the right of the array variable
    name is the array index.
  • The index is how we reference individual
    variables in the array.
  • By default array indexes start at zero. So the
    first item in any array would be at index 0
  • So if we had an array to hold the names of the 50
    states the 50th state would be at array index 49.

47
Array Example
  • Suppose we wanted a list of 5 scores. Heres how
    the code would look

20Scores(2) 15Scores(3) 11Scores(4) 20
48
Walking Thru The Array Code
  • Dim Scores(4)
  • Declares an array with 5 individual elements
    (variables) in it.
  • By default, VBScript will assign the first
    variable the array index of 0, the next 1, and so
    on.
  • Scores(0) 19
  • Take the first variable in the array and put the
    value 19 in it.
  • Notice how this is just like assigning a value to
    an ordinary variable. Array variables are just
    like regular variables, except they are related
    to each other by the array name (Scores in this
    example).

49
What Can You Do With Array Variables?
  • Anything you can do with a normal variable (and a
    little more, as we will see later).
  • You can output it
  • Response.Write Scores(0)
  • You can process it
  • PercentScore Scores(0) / n
  • You can convert it
  • IntScore Cint(Scores(0))
  • Arrays can hold any type of variable (numbers,
    strings, objects, etc).
  • The real power of arrays is when you combine them
    with loops.

50
Looping Thru Arrays
  • Arrays can be quickly traversed using FOR loops.
  • The ASP function Ubound() gives us the largest
    index in an array.
  • In other words, it gives us the size of the
    array.
  • A FOR loop uses a counter variable to iterate. We
    can use this counter variable to represent the
    array index and gain access to individual array
    items.

51
Processing An Array Cont.
Output_onedarray.asp
  • Taking the previous code example of an array of
    scores, we could output every score in that array
    using a FOR loop

Dim i For i0 to Ubound(Scores) Response.Write
Scores(i) "
" Next
52
Breaking It Down
  • Dim iFor i0 to Ubound(Scores)
  • Declare a variable that will server as the loop
    counter and array index.
  • Loop runs from 0 to 4 (the first index starts at
    0 and the last index is 4).
  • Response.Write Scores(i)
  • The loop code output the value at array index
    i
  • Next
  • Increment the array index / counter variable

53
Multi-Dimensional Arrays
  • Up until now we have focused on single-dimension
    arrays. Which are essentially just lists of
    variables, consecutively stored in memory.
  • But what if we wanted to store information like
    this
  • The solution is to use a multi-dimensional array.

54
Multi-Dimensional Arrays Cont.
  • The election results in the previous slide are an
    example of a two-dimensional array.
  • A two-dimensional array is just a table of data.
    Remember that tables have rows and columns.
  • A two-dimensional array is declared like this
  • Dim TwoDArray(num_rows, num_cols)

55
Two-Dimensional Array Code Ex
  • Here is the code to create the election results
    table we showed two slides ago

Dim ElectionResults(2, 1) ElectionResults(0, 0)
"Gore" ElectionResults(1, 0)
"Bush" ElectionResults(2, 0) "Other" ElectionRes
ults(0, 1) "50,996,116" ElectionResults(1, 1)
"50,456,169" ElectionResults(2, 1) "3,874,040"
56
Looping Thru 2-Dimensional Arrays
  • A FOR loop is used to process a 2D array just
    like it is used to process a 1D array.
  • The difference is that we need two loops
  • One FOR loop to process each row in the array.
  • One FOR loop to process every column (cell) in
    a given row.
  • Psuedocode would look something like this
  • For row0 to numrows 1 For col0 to numcols
    1 output 2darray(row, col) NextNext

57
Ubound in 2D Arrays
  • How do we determine the number of rows and
    columns in a 2D array?
  • The ubound function has a second parameter,
    dimension, which tells ubound which dimension of
    the array you want to get the highest index from.
  • If no dimension argument is provided VBScript
    assumes the 1st dimension (the row)
  • Numrows Ubound(ElectionResults) 1
  • Numrows Ubound(ElectionResults, 1) 1
  • The number of columns is the second dimension
  • Numcols Ubound(ElectionResults, 2) 1

58
Iterating through a 2D Array
2dray.asp
  • Assume this code is processing the
    ElectionResults array

for row 0 to ubound(ElectionResults) for col0
to ubound(ElectionResults, 2) Response.write
ElectionResults(row, col) " " next response.wr
ite "
" next
59
Breaking It Down
  • for row 0 to ubound(ElectionResults)
  • This is the outer loop, it iterates through the
    rows in the array.
  • for col0 to ubound(ElectionResults, 2)
  • This is the inner loop, it iterates through the
    columns in every given row
  • Response.write ElectionResults(row, col) " "
  • The inner loops code.
  • It outputs a particular columns (cell) value.
  • Note that the outer loop iterates 3 times, and
    the inner loop has 2 iterations per execution of
    the outer loop.

60
Dynamic Arrays
  • As we have seen, an array has to be declared with
    a given size. But what if we dont know how many
    array variables well need before declaring?
  • Answer use a dynamic array.
  • A dynamic array is an array whose size (number of
    array variables) can change as we move through
    our code.
  • Generally we should avoid using these because
    they can be a performance drain (but sometimes
    there is no other way to solve the problem).

61
How NOT To Do Dynamic Arrays
  • Most new programmers assume code like this is
    legal
  • This is not legal code, and it will generate a
    compiler error.

Scores(NumElements)
62
How To Make A Dynamic Array
  • There are two parts to creating a dynamic array
  • Declare it
  • Size it
  • Declaring a dynamic array
  • Dim Scores()
  • You MUST declare the array with no size at first.
  • Size the array.
  • NewArraySize 10ReDim Scores(NewArraySize)

63
Notes About Dynamic Arrays
DynamicArray.asp
  • When you size a dynamic array (i.e., you use the
    ReDim keyword) all the elements that are already
    in the array are destroyed.
  • To keep whats in the array when you resize it
    use the Preserve keyword
  • Dim Scores(4)code that sets the 5 scoresReDim
    Preserve Scores(9)
  • After we resize the array there are 5 new array
    variables added onto the end of the list of 5
    scores that are already there.

64
Midterm Next Week
  • Review the class lecture PowerPoints and all the
    chapters youve been assigned so far.
  • Combination of multiple choice, fill in the
    blank, true/false, and short answer (including
    writing code).
  • Study guide will be emailed to you later this
    week.
  • Program 6 assignment will be handed out next
    Wednesday (it will relate to the material we
    covered today).

65
ENDStudy for Midterm
Write a Comment
User Comments (0)
About PowerShow.com