Server Objects

The ASP framework provides objects (and associated methods, events, and properties) that give information about the Web server and its environment, make processing forms easy and manageable, and provide a flexible system of data storage. You can roll all these abilities into a well-rounded, robust Web application that is easy to develop and maintain and is more extensible than you might have thought possible.

The five built-in objects in the ASP framework are as follows:

  • Application
  • Request
  • Response
  • Server
  • Session

These objects are an essential part of the ASP framework, and as such they occur frequently in Visual InterDev development and throughout this book. In the following sections we'll cover the basics of these objects with particular focus on the Request and Response objects.

Throughout the discussion you'll find that these objects have typical object-oriented features of methods, events, and properties. When a group of related properties for an object can be classified as a single unit, they are termed a collection. The Application, Response, and Request objects have collections, whereas the other objects have properties.

The Application Object

The Application object can be used to share information among all users of your application. The application is defined as all the .asp files within the virtual directory and its subdirectories.

The Application object has two methods named Lock and Unlock. Since the data is shared among users, these methods allow you to effectively lock and unlock access to the application object while you apply changes to its variables.

The events that relate to the Application object are Application_OnStart and Application_OnEnd. These events are declared in the global.asa file, which is part of a Visual InterDev Web project.

The syntax for setting a variable within the Application object is as follows:

Application("variable_name") = value 

You can then reference the value of the variable as follows:

MyVariable = Application("variable_name") 

The Application object also has two collections named Contents and StaticObjects. The Contents collection contains all of the variables that you've set within the Application object. The StaticObjects collection contains all of the application-level objects that have been declared with the <OBJECT> tag.

The Response Object

The Response object is used to send information to the browser. It has collections, properties, and methods. In fact, the only collection it has is the Cookies collection, which can be used to set cookie values. This is the opposite of the Cookies collection in the Request object, which is used to read cookie values. (We'll discuss cookies later in this chapter.) In this section, we'll just take at look at some of the more common properties and methods such as the Buffer, Expires, and ExpiresAbsolute properties and the Clear, End, Flush, Redirect, and Write methods.

The most common application of the Response object is to send string output for display in the browser. This can be done by simply using an equal sign (=) in front of the information to be sent or by using the Response.Write syntax, as you'll see in the following examples.

In the first example, variables and values have been inserted into the HTML stream by starting the VBScript line with an equal sign:

MyName = "Ken Spencer" = "Hello, my name is " & MyName 

The preceding syntax sends the following string to the browser:

Hello, my name is Ken Spencer 

If you are familiar with Visual Basic, you might find this syntax a bit strange. It is unusual to start a line with an equal sign—it's an exception to the otherwise simple rules about how to use equal signs in Visual Basic. However, it isn't quite as strange as it seems. In the above example, starting the line with an equal sign is shorthand for

MyName = "Ken Spencer" Response.Write("Hello, my name is" & MyName) 

The above code uses the Response object and a method named Write. The Write method takes a string as an argument and writes it to the HTML stream, effectively writing it to the browser. That is exactly what is happening, and it makes perfect sense in the context of Visual Basic syntax. Because you often type Response.Write, VBScript just made it a little easier for you.

The Response object sends output to the client. You will most often use the Write method and its associated "equal sign first" shorthand, but it's important to remember that the Response object has additional methods and properties as well.

Controlling the Response object's properties

The Response object has a set of properties that you can use to adjust how ASP sends output to browsers. When the Buffer property is set to True, IIS collects or buffers all output destined for the browser. It holds on to it until all the server script code on the page finishes processing, at which time all the HTML is sent at once. This is useful because you might have code in your ASP that cancels output to the browser or that redirects the browser to a different page. Having IIS buffer the output to the browser saves time in these situations. If HTML were sent to the browser while your script is executing and you come to a point where you want to jump to another page, all the time it took to send the HTML across the Internet to that point would be wasted.

After you decide to set buffering on the Response object to True, you can use the Redirect and End methods. Redirect lets you send a command to the browser that causes it to connect to a different URL. A good use of this is to direct users to a certain page on your Web site based on their input on a form, as shown in the following syntax:

<% If Request.Form("age") > 21 Then     Response.Redirect "http://www.mysite.com/GrownUps.asp" Else     Response.Redirect "http://www.mysite.com/Children.asp" End If %> 

The End method does just what it says. When you reach a Response.End statement in your script, script processing stops and whatever is in the buffer is sent to the browser. If you want to end the script and not send the output to the browser, you must first use the Clear method of the Response object to clear the buffer and then use the End method to end the script:

<% If Request.Form("Attitude") = "bad" Then     ' If the user has a bad attitude, then      ' stop processing the script and clear      ' the output that has been buffered to this point     Response.Clear     Response.End End If %> 

When a page is sent to the browser, the page is usually cached on that machine so that the browser doesn't have to download the page the next time it's visited. Using the Expires property of the Response object, you can control how long a page is valid in the cache. If the user revisits the page in less than the number of minutes you set in the Expires property, the cached version is used; otherwise, a new version is downloaded.

<% ' This page is good only for one hour. After that, ' be sure to reload this page Response.Expires = 60 %> 

Sometimes you want to let a page be cached until a certain date or time. The ExpiresAbsolute property takes a date or a time value, at which time the cached version of the page expires.

<% ' Cache this page until the fourth of July, 2:00pm Response.ExpiresAbsolute = #July 4, 1999 14:00# %> 

The date that ExpiresAbsolute takes is a standard VBScript date and/or time (hence the pound signs). You must have the correct time zone information set on your server because the time is converted to Greenwich Mean Time (GMT) before it is sent to the browser, ensuring that the time is accurate regardless of the client's location.

Saving data with cookies

A cookie is a variable that you store on the user's machine so that it's available the next time the user logs onto your application. This is often advantageous. Cookies are a great way to maintain application information and preferences that are specific to a particular user. An example of this is the customizable Web site. Some Web sites let you set preferences according to your tastes. The Microsoft Network (MSN) has a home page that lets you set your favorite sites, the types of information you're interested in, and so forth. The site saves a cookie on your machine and then retrieves this cookie each time you hit the MSN site. MSN then has a way of knowing who you are, that you've visited the site before, and what your preferences are.

The user is usually unaware that cookies are in use, and cookies have no adverse effect on the user's machine. In fact, hundreds of Web sites already use cookies, and most people who spend time browsing the Web have cookies stored on their machines. However, some browsers can be set to notify users that a cookie is being sent so the user can cancel cookie reception.

To get cookies from the user, you use the Cookies collection in the Request object. Conversely, the Response object's Cookies collection allows you to set the cookie's properties. If the cookie does not exist, it is created. If it already exists, it takes the new value that is assigned to it.

Here is the syntax for setting a cookie using the Response object:

Response.Cookies(cookie)[(key)|.attribute] = value 

The attribute parameter specifies information about the cookie, such as its expiration date and whether it is secure. A secure cookie is encrypted when it is stored on the user's machine. Table 10-5 lists the available cookie attributes:

Table 10-5. Cookie attributes.

Cookie Attribute Description
Expires Write-only. The date on which the cookie expires.
Domain Write-only. If specified, the cookie is sent only to requests to this domain.
Path Write-only. If specified, the cookie is sent only to requests to this path.
Secure Write-only. Specifies whether the cookie is secure.
HasKeys Read-only. Specifies whether the cookie contains keys.

You can create two types of cookie. The first is a single-value cookie: one cookie, one value. For example, you can write a single value to the cookie Username using the following code:

<% ' Simple cookie named Username, with  ' only one value, "Smith" Response.Cookies("Username") = "Smith" %> 

You can also specify a key when assigning the value. This creates the second type of cookie—a dictionary. A dictionary is a cookie with an array of keys in which each key has a unique value. The following code writes multiple values to the dictionary CarAttributes:

<% ' Cookie Dictionary called CarAttributes, with keys ' named "color", "style", and "brand" Response.Cookies("CarAttributes")("color") = "Red" Response.Cookies("CarAttributes")("style") = "Sports" Response.Cookies("CarAttributes")("brand") = "ACME" %> 

As mentioned earlier, if a cookie exists, the value is discarded when you assign a new value. If you assign a value to a cookie dictionary, you lose all the keys in that dictionary. If you assign a key value to a simple one-value cookie, you lose the cookie value. It is important to know what type of cookie you're using before you set its value. Often you'll know the type because you set the value of the cookie in the same application. But if you're not sure of the type, you can check the HasKeys attribute. The HasKeys attribute is True for a dictionary and False for a single-value cookie.

The Request Object

One of the ways information can be passed from a browser to the server is via an HTTP request. The Request object retrieves information sent via an HTTP request from the browser. Five types of variables can be passed to your application through the Request object. Each type has its own collection in the Request object. They are:

  • QueryString The values of variables in the HTTP query string
  • Form The values of form elements in the HTTP request body
  • Cookies The values of cookies sent in the HTTP request
  • ServerVariables The values of predetermined environment variables
  • ClientCertificate The values of fields stored in the client certificate that is sent in the HTTP request

You can access variables by referring to the Request object, then the collection, and then the particular variable you're trying to access. When retrieving a variable, naming the collection is optional. If you don't include the collection, all the collections are searched for the variable that you're looking for, in the above order. The syntax is:

Request[.Collection](variable) 

It's good practice to use the name of the collection even when it's optional. There is less chance for confusion when someone else reads your code or when you return to the code after not visiting it for a long time.

QueryString and Form

The QueryString and Form collections of the Request object allow you to access the values of variables in the HTTP query string and the values of form elements in the HTTP request body, respectively.

Reading data from cookies

Cookies are written to the client machine using the Response object. The Cookies collection of the Request object lets you retrieve the cookies from the client machine. The syntax for using the Cookies collection is:

Request.Cookies(cookie)[(key)|.attribute] 

As the syntax implies, each cookie can be an array, or more appropriately, a collection of values. Each value has a name called a key.

ServerVariables

This collection consists of several predefined server environment variables that can prove handy in your ASP code. You generally use this collection to read information about the server or the user's browser. The variables shown in Table 10-6 are read-only.

Table 10-6. Server environment variables.

HTTP Variable Description
ALL_HTTP All HTTP headers sent by the client.
ALL_RAW Retrieves all headers in the raw form. The difference between ALL_RAW and ALL_HTTP is that ALL_HTTP places an HTTP_ prefix before the header name and the header name is always capitalized. In ALL_RAW, the header name and values appear as the client sets them.
APPL_MD_PATH Retrieves the metabase path of the Web Application Manager (WAM) for the ISAPI DLL.
APPL_PHYSICAL_ PATH Retrieves the physical path corresponding to the metabase path. IIS converts the APPL_MD_PATH to the physical (directory) path to return this value.
AUTH_ PASSWORD The value entered in the client's authentication dialog box. This variable is only available if Basic authentication is used.
AUTH_TYPE The authentication method the server uses to validate users when they try to access a protected script.
AUTH_USER Raw authenticated user name.
CERT_COOKIE Unique ID for client certificate, returned as a string. Can be used as a signature for the whole client certificate.
CERT_FLAGS bit0 is set to 1 if the client certificate is present.
  bit1 is set to 1 if the Certifying Authority of the client certificate is invalid (not in the list of recognized CA on the server).
CERT_ISSUER Issuer field of the client certificate (O=MS, OU=IAS, CN=user name, C=USA).
CERT_KEYSIZE Number of bits in Secure Sockets Layer connection key size. For example, 128.
CERT_SECRETKEYSIZE Number of bits in server certificate private key. For example, 1024.
CERT_SERIALNUMBER Serial number field of the client certificate.
CERT_SERVER_ISSUER Issuer field of the server certificate.
CERT_SERVER_SUBJECT Subject field of the server certificate.
CERT_SUBJECT Subject field of the client certificate.
CONTENT_LENGTH The length of the content as given by the client.
CONTENT_TYPE The data type of the content. Used with queries that have attached information, such as HTTP POST and PUT.
GATEWAY_INTERFACE The revision of the CGI specification used by the server. Format: CGI/revision.
HTTP_<HeaderName> The value stored in the header HeaderName. Any header other than those listed in this table must be prefixed by HTTP_ in order for Request.ServerVariables to retrieve its value.
HTTPS Returns ON if the request came in through secure channel (SSL) or it returns OFF if the request is for a nonsecure channel.
HTTPS_KEYSIZE Number of bits in Secure Sockets Layer connection key size. For example, 128.
HTTPS_SECRETKEYSIZE Number of bits in server certificate private key. For example, 1024.
HTTPS_SERVER_ISSUER Issuer field of the server certificate.
HTTPS_SERVER_SUBJECT Subject field of the server certificate.
INSTANCE_ID The ID for the IIS instance in textual format. If the instance ID is 1, it appears as a string. You can use this variable to retrieve the ID of the Web-server instance (in the metabase) to which the request belongs.
INSTANCE_META_PATH The metabase path for the instance of IIS that responds to the request.
LOCAL_ADDR Returns the Server Address on which the request came in. This is important on multihomed machines where there can be multiple IP addresses bound to a machine and you want to find out which address the request used.
LOGON_USER The Windows NT account that the user is logged into.
PATH_INFO Extra path information as given by the client. You can access scripts by using their virtual path and the PATH_INFO server variable. If this information comes from a URL, the server decodes it before passing it to the CGI script.
PATH_TRANSLATED A translated version of PATH_INFO that takes the path and performs any necessary virtual-to-physical mapping.
QUERY_STRING Query information stored in the string following the question mark in the HTTP request.
REMOTE_ADDR The IP address of the remote host making the request.
REMOTE_HOST The name of the host making the request. If the server does not have this information, it sets REMOTE_ADDR and leaves this empty.
REMOTE_USER Unmapped user-name string sent in by the user. This is the name that is really sent by the user as opposed to the ones that are modified by any authentication filter installed on the server.
REQUEST_METHOD The method used to make the request. For HTTP, this is GET, HEAD, POST, and so on.
SCRIPT_NAME A virtual path to the script being executed. This is used for self-referencing URLs.
SERVER_NAME The server's host name, DNS alias, or IP address as it would appear in a self- referencing URL.
SERVER_PORT The port number to which the request was sent.
SERVER_PORT_SECURE A string that contains either 0 or 1. If the request is being handled on the secure port, this is 1; otherwise, it is 0.
SERVER_PROTOCOL The name and revision of the request information protocol. Format: protocol/revision.
SERVER_SOFTWARE The name and version of the server software answering the request (and running the gateway). Format: name/version.
URL Gives the base portion of the URL.

The following code loops through the entire collection of variables and outputs them into an HTML table:

<TABLE>     <TR>         <TD><B>Server Variable</B></TD>         <TD><B>Value</B></TD>     </TR> <% For Each name In Request.ServerVariables %>      <TR>         <TD><%= name %> </TD>         <TD><%= Request.ServerVariables(name) %> </TD>     </TR> <% Next %> </TABLE> 

This code is similar to the code in the ASP documentation, except the </TABLE> tag has been moved after the Next statement so the code works correctly. This code demonstrates how you can walk through a collection using For Each and provides a good example of how to retrieve all the server variables.

ClientCertificate

If the Web browser is using Secure Sockets Layer (SSL) to connect to your Web server and the server requests certification, a series of client certificate objects in this collection will contain information about the client's certification. You can tell when an SSL connection is being used because the address in the browser begins with https:// instead of http://.

The syntax for retrieving these certificates is

Request.ClientCertificate(Key[Subfield] ) 

Table 10-7 lists the possible key values, along with their uses.

Table 10-7. Client certificate key values.

Key Use
Subject A list of values that contain information about the subject of the certificate. Subfields are used with this key to extract the individual values from the list.
IssuerA list of values that contain information about the issuer of the certificate. Subfields are used with this key to extract the individual values from the list.
ValidFrom A valid date that indicates when the certificate becomes active.
ValidUntil A valid date that indicates when the certificate expires.
SerialNumberA string that represents the serial number. This string is a series of hexadecimal bytes separated by hyphens.
Certificate The entire certificate (all the previous keys). It is represented in a binary format, so it's best to use the other keys to attain the values.
Flags A set of flags that provide additional client certificate information. The following flags can be set:
ceCertPresent—A client certificate is present.
ceUnrecognizedIssuer—The last certification in this chain is from an unknown issuer.

A variety of SubField values are available to extract specific information from the Subject and Issuer keys. A complete description of SubField values is available in the Object Reference in the ASP online documentation.

Retrieving data with cookies: the Request object

The Cookies collection of the Request object lets you retrieve the cookies from the client machine. The Cookies collection is a collection of the cookie values stored on the user's machine.

The syntax for using the Cookies collection of the Request object is

Request.Cookies(cookie)[(key)|.attribute] 

As the syntax implies, each cookie can be an array, or more appropriately, a collection of values. Each value has a name, called a key. You can check a cookie to see if it has simply one value or if it has more than one key—each of which has a value—by checking the cookie's HasKeys property. HasKeys will be either True or False, so you can use it in an If…Then...Else statement:

<% If Request.Cookies("MyCookie").HasKeys Then %> MyCookie has the following values: <P> <% For Each key in Request.Cookies("MyCookie") %> <% = key %> has the value  <% = Request.Cookies("MyCookie")(key) %> <P> <% Next %> <% Else %> My Cookie's value is  <% = Request.Cookies("MyCookie") %> <% End If %> 

First you use the cookie's HasKeys property in the If statement. If there are keys in the cookie, you use the For Each statement to iterate through the collection of keys and print the value of each one. You can then use the For Each statement to loop through all the collections in the Request object, not just the cookies. This technique is useful if you don't know how many objects are in a collection.

If you do know what you're looking for in a collection, you might be better off referring to the exact item that you need in the collection rather than looping though them all with the For Each statement.

The Server Object

The Server object is exactly what its name implies. It provides methods and properties that let you interact with the actual machine that your application is running on—namely, the Web server.

The Server object has a ScriptTimeout property and the following four methods: CreateObject, HTMLEncode, MapPath, and URLEncode.

While only a few methods and properties are available in the Server object, they are extremely useful. The Server object opens the door to using server-side ActiveX components within your Web applications. It lets you instantiate components in your Web application that you've written in Visual Basic, Visual C++, or any other development environment that can create COM components.

The CreateObject method of the Server object is probably the most important method of any built-in ASP object. By passing it the Programmatic ID (ProgID) of a server component, you create an instance of that component and assign an object variable to it.

You can create objects for any COM component on your system, but you cannot create instances of the objects that are built into ASP. For instance, you can't create a Session object using this syntax. You can, however, take advantage of the five server-side ActiveX components that are supplied with ASP:

  • Ad Rotator
  • Browser Capabilities
  • Database Access
  • Content Linking
  • TextStream

The Session Object

The Session object is similar to the Application object in that it also contains events within the global.asa file. Unlike the Application object, however, the Session object stores information for a particular user session. The Session object persists for the entire session and thus provides a very elegant solution to the common persistence-of-state problem—when you need to keep track of a user from one web page to the next, as in a "shopping cart" type of application. This is difficult to do given the stateless nature of the HTTP protocol.

The syntax for setting a variable within the Session object is as follows:

Session("variable_name") = value 

You can then reference the value of the variable as follows:

MyVariable = Session("variable_name") 



Programming Microsoft Visual InterDev 6. 0
Programming Microsoft Visual InterDev 6.0
ISBN: 1572318147
EAN: 2147483647
Year: 2005
Pages: 143

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