Page #29 (Chapter 3 - Building ASP Applications)

Chapter 3 - Building ASP Applications

Visual Basic Developers Guide to ASP and IIS
A. Russell Jones
  Copyright 1999 SYBEX Inc.

Creating a Self-Modifying ASP Application
Using interpreted ASP code has many advantages. For instance, because the code lives in text files, it's easy to change. Also, after the ASP engine has been installed, you don't have to install any more DLL installations, registrations, or support files. In this project, you'll see some of the power of ASP files by writing a self-modifying application. Don't worry if you don't completely understand everything in the project at this time—you will by the time you finish this book.
Using Visual InterDev or your favorite HTML editor, start a new text file. This file will consist of a form with a drop-down selection list. When you select a color from the list and submit the form, the file will rewrite itself to reflect your choice, then redisplay itself.
Listing 3.1 shows the entire code.
Listing 3.1: Self-Modifying ASP File (selfMod.asp)
<%@ Language=VBScript %>
<% option explicit %>
<%Response.Buffer=True%>
<%
dim submitted
dim backcolor
dim fs
dim ts
dim s
dim afilename
dim colors
dim curColor
dim V
dim aPos
dim i
set colors = server.CreateObject("Scripting.Dictionary")
colors.Add "Black", "000000"
colors.Add "Red", "FF0000"
colors.Add "Green", "00FF00"
colors.Add "Blue", "0000FF"
colors.Add "White", "FFFFFF"
submitted=(Request("Submitted") ="True")
if submitted then
     Session("CurColor")=Request("newColor")
     curColor = Session("CurColor")
     afilename=server.MapPath("selfMod.asp")
     Response.Write afilename & "<BR>"
     Response.Write Session("CurColor") & "<BR>"
     set fs = server.CreateObject _
         ("Scripting.FileSystemObject")
     set ts = fs.OpenTextFile(afilename,ForReading,false)
     s = ts.readall
     ts.close
     set ts = nothing
     aPos = 0
     do
         aPos = instr(aPos + 1, s, "bgcolor", _
             vbBinaryCompare)
     loop while (mid(s, aPos + 7, 1) <> "=")
     aPos = aPos + 9
     if aPos > 0 then
         s = left(s, aPos) & Session("CurColor") & _
             mid(s, aPos + 7)
         set ts = fs.OpenTextFile _
             (afilename,ForWriting,false)
         ts.write s
         ts.close
         set fs = nothing
         Response.Redirect "selfMod.asp"           
     else
         set fs = nothing
         Response.Write "Unable to find the position " & _
             "in the file to write the new color value."
         Response.End
     end if
else
     if isEmpty(Session("Curcolor")) then
         Session("CurColor") = "FF0000"
     end if
     curColor = Session("CurColor")
end if
%>
<html>
<head>
</head>
<body>
<form name="frmColor" method="post"
     action="selfmod.asp?Submitted=True">
<input type="hidden" value="<%=curcolor%>">
<input type="hidden" value="<%=Session("curcolor")%>" id=hidden1
     name=hidden1>
<table align="center" border="1" width="80%" cols="2">
     <tr>
         <td align="center" colspan="2" bgcolor="#FF0000">
             <% if curColor = "000000" then %>
                 <font color="#FFFFFF">
             <% else %>
                 <font color="#000000">
             <% end if %>
             Select A Color
                 </font>           
         </td>
     </tr>
     <tr>
         <td align="left" colspan="2" bgcolor="#FFFFFF">
             Select a color from the list, then click the                    
             "Save Color Choice" button.
         </td>
     </tr>
     <tr>
         <td align="right" valign="top" width="20%">
             <b>Color</b>:
         </td>
         <td align="left" valign="top" width="80%">
             <select name="newColor">
                 <%
                 for each V in colors
                      Response.Write "<option "
                      if colors(V)=curColor then
                          Response.Write "selected "
                      end if
                      Response.Write "value='" & _
                          colors(V) & "'>" & V
                      for i = 1 to 12
                          Response.Write " "
                      next
                      Response.Write "</option>"
                 next
                 %>
             </select>
         </td>
     </tr>
     <tr>
         <td align="center" valign="bottom" colspan="2">
         <input type="submit" value="Save Color Choice"
             id=submit1 name=submit1>
         </td>
     </tr>
</table>
</form>
</body>
</html>
<%set colors = nothing%>
Web development environments such as Visual Basic and Visual InterDev create Web applications for you automatically, but if you're not using one of these tools, you'll need to create one manually.
If you're still using IIS 3, ignore this procedure. If you're using IIS 4, though, you must create a Web application before IIS will run the global.asa file. If you ever notice that an application isn't running any of the code in global.asa, you should check to make sure that the virtual directory containing your global.asa file is marked as a Web application. To mark the virtual directory for your project as an application, open the Internet Service Manager, select or create your application's virtual directory, then right-click the virtual directory name in the left-hand pane.
Look at the button to the right of the Name field in the Application Settings portion of the Virtual Directory properties dialog. If the button's caption is Create, click the button to create a new Web application, then enter the name for the application in the Name field. If the button is called Remove, then the directory is already marked as a Web application, and you don't need to do anything (see Figure 3.5).
Setting Up the Project in Visual InterDev
To set up the project outlined in this section in Visual InterDev, you should reference the Microsoft Scripting Runtime Library. You'll also need to allow write access to the virtual directory through the Internet Service Manager program before the project will work. To specify write access, open the Internet Service Manager program, find your virtual directory in the Default Web Site, and right-click it. Select Properties. In the dialog box, make sure the Write check box is checked. For IIS 4, the dialog box looks like Figure 3.5.
In the rest of this chapter, I'll explain the code in the selfMod.asp file.
<%@ Language=VBScript %>
This line is required in every ASP file (but of course, the language doesn't have to be VBScript—remember, ASP files can host multiple languages).
<% Option Explicit %>
Just as in VB, the Option Explicit command forces you to declare variables before you use them. Although the command is not required, you should always use this in both ASP and VB.
<%Response.Buffer=True%>
The server normally writes the HTTP headers immediately, then begins sending output as the ASP engine generates it. If you want to redirect within your code (which requires a change to the HTTP headers), you have to include this line. When you set the Response.Buffer property to True, the server buffers the entire response until page processing is complete. For long requests, this can slow down the perceived response time, because the user has to wait until the entire request has finished processing before the browser can begin to display the result. You should usually use this command in a page only if you plan to redirect, write cookies, or alter the HTTP headers.
set colors = Server.CreateObject("Scripting.Dictionary")
There are several things to explain in this line. First, the Server.CreateObject method is equivalent to the following VB code:
Dim colors as Dictionary
Set Colors = New Dictionary
In an ASP file, you need to enter both the project name (Scripting) and the class name (Dictionary) to obtain a reference to an object.
At any rate, the next five lines simply add the colors to the Dictionary object with the color name as the key and the HTML color string (which is a text representation of a long, or RGB, value) as the value. Each of the six-character strings represents three hexadecimal byte values. Colors are a combination of red, green, and blue. Each color may take a value from 0 to 255 (00 to FF in hex) and requires two characters. You read the value in pairs. The pairs of characters represent the red, green, or blue values, respectively.
colors.Add "Black", "000000"
colors.Add "Red", "FF0000"
colors.Add "Green", "00FF00"
colors.Add "Blue", "0000FF"
colors.Add "White", "FFFFFF"
This form submits to itself by posting the values entered by the user back to the same page that the form came from—unheard of for straight HTML forms, but common as dirt with ASP files. Submitting a form to itself puts all the code that deals with the form in one file, where you can test it easily, and makes one less file to maintain. If the user has submitted the form, you want to process the submitted request; otherwise, you just want to display the form. The following line determines whether the form is being shown for the first time or whether the user has submitted the form. The Request object will contain a string value of "Submitted= True" if the form has been submitted. The following code assigns a local variable called submitted a Boolean value of True if the form was submitted by the user:
submitted=(Request("Submitted") ="True")
if submitted then
     Session("CurColor")=Request("newColor")
     curColor = Session("CurColor")
  Note In the preceding code, note that you do not have to dimension Session variables before using them—even if Option Explicit is in effect.
Another way to test whether a user has posted a form is to check the value of Request.ServerVariables("REQUEST_METHOD"). The value will be POST when the user has posted content, and GET when you should display the form. I've used both and prefer using the local variable method. I find that using a local variable is more intuitive and works regardless of whether you use the Post or Get method.
You can think of the Session object as a Dictionary object (although it's not) because it exhibits almost identical behavior:
afilename=Server.MapPath("selfMod.asp")
The Server.MapPath method translates a virtual directory or filename into a physical directory or filename. In this case, when you pass it the name of the current file, it will return the full physical drive:\pathname\filename for the file. On my system, it returns
"c:\inetpub\wwwroot\ASPProject1\selfMod.asp"
The next few lines create two of the other objects in the Microsoft Scripting Runtime Library—a FileSystemObject and a TextStream object. The FileSystem-Object provides methods and properties to work with the native file system. One of those methods is the OpenTextFile method, which returns a TextStream object. The TextStream object lets you read from and write to text files. In this case, open the file in read-only mode, then read the entire file at one time by using the ReadAll method. Finally, close the TextStream.
set fs = server.CreateObject("Scripting.FileSystemObject")
set ts = fs.OpenTextFile(afilename,ForReading,false)
s = ts.readall
ts.close
set ts = nothing
At this point, the content of the string "s" is the same as the file that's running! You can do this because the ASP engine doesn't lock the file while it's executing—it reads the whole file into memory. You're going to search the string for the first occurrence of the word bgcolor that's followed by an equals sign.
aPos = 0
do
     aPos = instr(aPos + 1, s, "bgcolor", vbBinaryCompare)
loop while (mid(s, aPos + 7, 1) <> "=")
aPos = aPos + 9
The code loops to find the last occurrence of the word bgcolor because the first occurrence is inside the loop itself! The final line sets the value of the aPos variable to point to the color string value in the first row of the table—the position after the first pound (#) sign in the file, right before the color value you're going to update.
After it finds the position of the color string for the first row of the table, the code simply substitutes the selected color value and saves the file. It then redirects so that the browser will request the just-altered file.
if aPos > 0 then
     s = left(s, aPos) & Session("CurColor") & _
         mid(s, aPos + 7)
     set ts = fs.OpenTextFile(afilename, ForWriting, _
         false)
     ts.write s
     ts.close
     set fs = nothing
     Response.Redirect "selfMod.asp"                            
else
     set fs = nothing
     Response.Write "Unable to find the position " & _
         "in the file to write the new color value."
     Response.End
end if
If the form was not submitted, the file provides a default color value of red—FF0000—and assigns it to both a Session variable and a local variable called curColor. In general, you should assign Session variable values to local variables if you're going to use them more than once in a file, because looking up the Session variable value based on the key you provide takes several times longer than simply retrieving the value of a local variable. This follows the same principle you use in VB; always assign objects to local variables if you're going to use them more than once in a routine. Similarly, it's the principle behind the introduction of the With…End With block in VB. Local references are much faster than COM references.
if isEmpty(Session("Curcolor")) then
     Session("CurColor") = "FF0000"
end if
curColor = Session("CurColor")
That's almost all the VBScript code in the file. The remainder of the file displays the table, the drop-down list, and the button inside a <form> tag.
<form name="frmColor" method="post"
     action="selfmod.asp?Submitted=True">
There are several types of input controls. The available input types correspond roughly to text fields, buttons, combo boxes, and list boxes, although they act slightly differently than the equivalent Windows common controls.
You saw the text field and submit button types in the previous project. The drop-down list is slightly different. It's not an <input> tag at all, it's a <select></select> tag. The <select> tag contains a list of <option> tags that contain the list data. Each option tag can take a value parameter that specifies the value returned to the server. By default, the browser returns the option value for the item that's visible in the drop-down list. This is similar to a VB list box, which contains both visible items and itemdata. The ItemData array contains a list of long values, one for each item in the list. In contrast, the <option> tag can take any type of value, although it returns them all as text. You can also preselect a specific option by adding a selected parameter to that option tag. The selected parameter does not require a value.
One special type of input control is hidden. A hidden input doesn't display, so you can use it to pass values from one file to another. In this case, I'm using hidden inputs just so you can view the value by selecting View Source from the browser.
<input type="hidden" value="<%=curcolor%>">
<input type="hidden" value="<%=Session("curcolor")%>">
This is a trivial example that you would never use in practice because you would have problems if more than one person accessed the file. However, it does illustrate two important points about ASP files:
  Because ASP files are text files, you can change them easily. To update an ASP-based application, you simply update the text files that contain the application code. No registration entries to worry about, no need to stop the server, no DLLs or large executables, and no installation programs to write. That's powerful stuff.
  ASP files can rewrite themselves. You can't do that in VB (although you can write VB code that writes ASP pages). You can do this because the code contained in the ASP file is loaded into memory for compilation from the ASP file. After the file is loaded, the ASP engine releases the file lock. Depending on your server settings, the ASP engine can cache the file—but it does check to see if the file has changed for each request. Therefore, when you change the file, the ASP engine will display the contents of the changed file for the next request.
In the next section, you'll learn how to cache data in HTML or simple ASP files, rewriting them as needed when the data changes.



Visual Basic Developer[ap]s Guide to ASP and IIS
Visual Basic Developer[ap]s Guide to ASP and IIS
ISBN: 782125573
EAN: N/A
Year: 2005
Pages: 98

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net