OUR MUST POPULAR POST

Friday, June 28, 2013

ACTIVE SERVER PAGES


What are active server pages?
Microsoft introduced several methods for developing scripts on the server some of them quite simple (such as the internet Database connector and the SQL web Assistant), and other not as simple. There was a confusing time when companies did their best to simplify the development and development of server side scripts but even for web authors.
The situation changed drastically in 1996 with the introduction of active server Pages (ASP), an elegant solution to the problem of scripting. Active server pages are basically HTML pages that contain VBScripts code, which is executed on the server. That is why they are also called server side script or simply server scripts. The result of the VBScripts statements (if any) is transmitted to the client. The HTML code is transmitted as is. As a consequence, every HTML pages you have authored can be turn in to an active server page by changing its extension from HTML to ASP. Not that you will see any benefit in renaming your HTML documents, but you are ready to activate them with the inclusion of scripts.
The server scripts produce text HTML tags that are sent to the client, where they are rendered on the screen. A server script can produce any out put, but only HTML documents can be rendered on the client. Since VBScript can contact the objects installed on the server, you are not limited to VBScript’s native commands.
You can contact any active components installed on the server computer to carry out complicated data processing, to access database, and so on. A server that supports active server pages it called active server, and currently two web servers supports ASP: the internet information and the personal web server.
The active server provides a few built in objects, which are discussed in the section “the active server’s Objects,” later in this chapter. These objects simplify the development of script by taking care of tasks such as reading the parameters passed by the client, querying databases, saving and recalling cookies on the client computer, and so on. In addition to the built in object, you can contact any object on the server from within your script with the CreateObject() function. Let’s start by building a few active server pages, and then we’ll look at the objects of the active server.

Connecting to your Web-Server
To connect to your own server, start internet Explorer and enter the following address in the browser’s address box:

This is the address of the local computer and is the same on every machine. It’s a reserved IP address that connects you to the server running on the same machine from which the request is made. Entering this address (or simply 127.0.0.1) in the browser’s Address box displays the web server default document. You can copy in the server’s roots folder any HTML documents and open it by specifying its name along with your server’s address. Even better, create a virtual folder under the c:\INETPUB\WWW roots folder (name it MVB60, and place the HTML files you want to test there. The following address will open the calendar.htm file in the browser’s window:
http://127.0.0.1/MVB6/ calendar.htm

In the following section, you’ll see how to develop application s that run on the server and can be invoked from the s client. These applications are quite simple to develop (probably simpler than you think). They are scripts, just like the scripts you embed in HTML pages, only they run on the server. They are called active server pages, and as a VB programmer, you can start writing server side scripts immediately.

Building parameter strings
You can use two methods to built URLs that call special applications on the server and supply additional information to them:
The simple method is a supply all the required information in the <FROM> tag and let the browser contact the server and submit the values of all the control on the form.
The second method is to built the parameter string with VBScript commands and submit it to the server with the navigate method of the window object.
Starting with the sample method, let’s review the FORM.HTM page we looked at in previous chapter. The from section on the page, which was inserted with the following tags:
<FROM ACTION = “ASpages/Register.asp” METHOD = “GET”>

The action attribute specifies the URL of the applications to be invoked. The application is an ASP file that resides in the ASP pages virtual folder of the same web site, which uploaded the current page. The METHOD attribute specifies one of the two methods for submitting data from the client to the server. For the examples in this chapter, we are going to use the GET method. (The alternative is the POST method, but this has a limitation as to the maximum length of the string that can be submitted to the server.)

The form section of the FORM.HTM page contains the control and values listed.
When the submit button at the bottom of the form is clicked, the client transmits the following string to the server. The browser automatically builds this string (no script is needed in this page).


The DATETIME.HTM File
<HTML>
<HEAD>
<TITLE>simple ASP Demo</TITLE>
<SCRIPT LANGUAGE="VBScript">
document.write "<HTML>"
document.write "<H1>Welcome to the active server pages</H1>"
document.write "The current date is<b>" & date() & "</B><BR>"
document.write "The current time is<b>" & time() & "</B><BR>"
</SCRIPT>
</HEAD>
<BODY>
<B> Active server </B><BR>
Contain text, HTML code and scripts that executed on the client, just like ordinary HTML documents. The DateTime.asp file contains a client-side script, which prints the Date and the time on the client and then displays the document’s BODY.
</BODY>
</HTML>

The display of the above script


The date and time are displayed from within a client-side script, which calls the functions Date() and time(). This script is executed on the client, and as a consequence, the date and time are read from the local computer’s clock.
We’ll revise this page to display the time on the server. To do so, we’ll add statements that are executed on the server. Copy the DATETIME.HTM file to the SRVRTIME.ASP file and replace the script with the following:

<SCRIPT LANGUAGE=”VBScript” RUNAT=server>
Response.Write "<HTML>"
Response.Write "<h1>Welcome to the first ASP page</h1>"
Response.Write "The date is<b>" & date() & "</b>"
Response.Write "The time is<b>" & time() & "</b>"
</SCRIPT>

The display of above script


Included Files
Multiple scripts can call common procedures such as the Numtostring() function. To avoid repeating code or to maintain identical code in multiple files, you can include a file with one or more procedure definitions in an ASP files, you can include a file with one or more procedure definitions in an ASP file. The included file can also contain HTML code; it doesn’t really matter. It is the inserted as is in the current ASP file and processed along with the rest of the file.
HTML provides the #include directive, which inserts the contains of another files into an ASP file before processing it. The #INCLUDE statements is called a directive because it not an executable statement; it simply instructs ASP to perform a simple insertion.

The syntax of the #INCLUDE directive is:
<!-#INCLUDE VIRTUAL |FILE = filename” ->

The comment tags ensure that this line will not be sent to the client by mistake. If the file resides in a virtual folder (or a sub folder under a virtual folder), use the VIRTUAL key word. If you had rather specify an absolute path name, use the file key word. Either keyword must be followed by the path name to the file name to the file to be included. Included files do not used a special extension, but the extension INC is commonly used.

To include the NumStrings.Inc file in the Support folder under ASP pages, use the following line:
<!-#INCLUDE VIRTUAL= “/ASPages/Support/Support/NumStrings.inc”à

If the NumString.inc file resides in the same folder as the ASP files in which it will be included, you can use the #INCLUDE directive with the file keyword:
<!-#INCLUDES FILE = “NumString.Inc”->

If the included file resides in the support folder of the ASP file, the following line will insert it in the current ASP file:
<!-# INCLUDE FILE=”support/ NumStrings.Inc”->

Relative paths use the ASP file’s folder as the starting point. We can also use the ../qualifier to specify parent folders:
<!-#INCLUDE FILE = “…/support/ NumStrings.Inc”->

Mixing server-side and client side Scripts
An ASP file can contain both server side and clients side scripts. If you want to include a script section in your web page, simply insert the scripting commands between the <SCRIPT> tags in the file. The out put of another ASP file that a variation on the script that displays the server’s date on the client. The TIMESRVR.ASP page displays the time on the client through the client side scripts, and it displays the time on the server through a server side scripts. If the client and server computers are in different time zones, the difference in the times is an integer number of hours, plus a few seconds that it may take for the HTML code to arrive at the client.
Here is the listing of the TIMESRVR.ASP file. Notice that the client side script is inserted with the <SCRIPT> tag, as if it were included on a regular HTML page. The server side script isn’t really a script, just a call to the time () function. You could have inserted as many statements as necessary, as long as they were included in a pair of <%> tags.

<HTML>
<BODY>
<% theTime=Time%>
<% theDate=Date%>
<FONT FACE=“VERDANA” SIZE=“3”>
<H1>Server’s local Time</H1>
<BR>
The time at the server location is <%=theTime%>
<BR>
And the date is <%=theDate%>
<p>
<HR>
<H1>The clients local time is</H1>
<SCRIPT LANGUAGE=“VBScript”>
Document.write "The local time is"
document.write time()
Document.Write "<Br>"
Document.Write "and the date time is " & Date()
Document.Write "<hr>"
Document.Write "The date differenct is " & DateDiff("s", "<%= theTime %>", Time()) & "seconds"
Document.Close
</SCRIPT>
</BODY>
</HTML>

The display of above script


After this introduction to the basic structure of ASP files, we can turn our attention to the object of the active server and see how they can help you develop interactive web pages. In developing ASP applications we are primarily interested in interacting with the server rather than writing elaborate HTML code or even client side scripts.
The emphasis is in writing server side code that reads data submitted by the client, processes them on the server (most cases, with ActiveX components that reside on the server). And produces s web pages on the fly, which are Transmitted back to the client, with any other server, this process requires CGI scripts and, in general, programming in C-like languages. With active server pages and the built in objects, the tasks that would normally required perl or C++ programming can be taken care with VBScripts.
In the rest of the chapter, we are going to examine these objects and how they simplify scripting on the server. At the end of the chapter, we’ll look at the some of the basic component, which lets your scripts access databases on the server.

The Active Server Objects
HTML is great languages for displaying information on the client. HTML extensions made web pages colorful, then interactive. But HTML is a simple language. It wasn’t design to be a programming language, and no matter how many extensions is introduced. HTML will never become a proper programming language.
To design interactive web pages, we need a programming tool. VBScripts could be the missing link, but VBScript (and any other scripting languages) is also seriously limited because of security considerations. A scripting language that runs on the client must be safe, and practically speaking, making a language safe for scripting is tantamount to crippling it. So the answer is to do more on the server, the programming tool is still VBScript. However, when it’s executed on the server VBScript can access any object on the server computer (built in or custom). This means that VBScript on the server behaves more visual Basic, and your server side scripts look more like VB code.
Most of you will be interested in learning how to access databases on the server from the client. The simplest way to access databases through and active server
Page is via the Database component, which is based on the active data objects (ADO). ADO is component that’s installed along with ASP, and you can call it from within your ASP pages to access databases. The Ado component provides high performance connectivity to any ODBC complaint database or OLE DB data source. As such, it can be used from within a web page’s script to directly access remote databases. In other words, you can use the ADO component on the client script (provided that the component is already installed on the client computer ) to built a web front end for accessing corporate data, without developing additional scripts on the server.
Active server Pages follow the component-based development paradigm. All the standard functionality you need to build a web site comes in the from of objects, which can be classified in two major categories:

Intrinsic, Basic
Intrinsic objects provide methods and properties that you need to access details of the incoming requests (such as the parameters of the request), handle cookies, and create the response to send back to the client. Basic object provide functionality that is not absolutely necessary, but commonly used in web development, such as the ADO component for accessing databases, the file system component for writing to and reading from local files on the server, and more. The following two sections discuss these objects and give you some example of how they are used in web development. It goes without saying that you can build your own objects to address specific requirements.

Intrinsic objects
Asp includes a number of built in objects that free the developer from much of the grunt work of writing code to access such as extracting the parameter s submitted along with the URL, storing and retrieving cookies on the client computer, and directing the output to the client.

Request This object give you access to the parameter passed to the server by the client along with the URL. These parameter are usually the values of the control ion the form, but can be any string constructed on the client by the local script. Through the request object, you can also recall the values of existing cookies on the client or create new ones.

Response This object provides the methods you need to build the response, which is another HTML document. The output of the response object is the output stream, which is directed by the web server to the client, as if it were another HTML document.

Application This object maintains information that’s common to all uses of an ASP based application. The application object provides events that let you set up variables that will be used by all user of the application.

Session This object maintains information for single users, while they are interacting with the application. A separate session object is associate with each user, and its basic function is to maintain a state between pages for that user. You can define variables in the session object, and they will maintain their value even when the user jumps between pages in the application. The session object’s variables are released when the user terminates the session.

Server             This object allows your server side script to create instances of ActiveX component that resides on the server. The server object’s CreatesObject method is almost identical to the Visual Basic function by the same name, and it lets you incorporate the functionality of ActiveX components into your applications. Similarly, you can create object variables with the server object and extend your web pages with the server object and extend your web pages with capabilities that are way beyond HTML.

Basic Objects
To help you create web applications, the Active Server provides the following objects that supply the functionality that is not necessary (as is the functionality of the built-in objects), but that is commonly used in building applications for the web.

Database This object provides connectivity to any ODBC – compliant database or OLE DB data source. It is based on the Active Data Objects and allows web developer to easily link a database to an active web page to access and manipulate data.

File Access This is another useful object that lets you access text file stored on the server. As with client side scripts, server-side scripts must be safe for the host system. The file Access object is fairly safe, because it allows developer to write and read text files only in specific folders on the server.

Content Linking This object manages a list of URLs so that you can treat the pages in your web side like the pages in a book. You author the pages, and the content linking object automatically generates and maintains tables of content and navigation links to previous and following web pages. With the method and properties exposed by the content linking object, you can add, delete, and rearrange pages without editing the individual HTML files.

Browser Capabilities With this object, ASP files can recognize the capabilities of the requesting browser and dynamically optimize the content for specific browser features. If you weren’t able to write to code that automatically recognizes the type of browser of session, you’d have to create (and maintain) a series of duplicate pages for each browser, or you’d have to notify user that special feature on your site can be viewed only with the specific browser.

Advertisement Rotator As people realize the potential of the web as a business medium and more and more sites become commercial, the need to manage ads on a web increases. Web managers can’t afford to manually place ads in their designs. Ads must not only be rotated, but selected according to user preferences. If your web site has a search engine, it wouldn’t make sense to advertise cars to a visitors who’s looking for books or advertise magazines to people who are searching for programming tools. To simplify the handling of ads on a web site, active server pages come with the advertisement Rotator object. You can use this object to display ads based on preset criteria every time and ASP file is requested.
In this chapter, we’ll cover only a few of the basic components of Active Server Pages. We’ll discuss the built in objects and a few of basic objects, which will help you leverage your VB knowledge to the web. We won’t get in to every ASP related topic.

The Response Object
Use the response object to send information to the client. ASP files can contain Straight HTML code that’s sent directly to the client. However, you want to control the output programmatically from within the script, you must write it to the response object. The response object supports the following methods and properties.

The write method
Everything you write to the Response object with the write method is send to the client. Normally, the information written with the write method must be an HTML document just like the write method of the Document object. Here’s a simple, but working example of the Response object’s write method.

Using the Response.write Method

<HTML>
<SCRIPT LANGUAGE=“VBScript” RUNAT=server>
Response.Write "<HTML>"
Response.Write "<HEAD>"
Response.Write "<TITLE> Response .Write Demo</TITLE>"
Response.Write "</HEAD>"
Response.Write "<H1>"
Response.Write "Response object :write Method"
Response.Write "</H1>"
Response.Write "This documents was created on the fly by an ASP file on the server"
Response.Write "</HTML>"
</SCRIPT>
</HTML>

The outer pair of HTML tags delimits the ASP file (they are not really required), and the pair of HTML tags written to the Response object delimit the HTML file seen by the client. If there is one method used in nearly every ASP file, it is the response write method, and you will see many more examples of it in this chapter.
The write method of the response object is the primary way to send data to the client. The example in code above is quite Trivial. You could use straight test and HTML tags to produce the same output, or you could place the same arguments in the Document. Write method. All three methods would produce the same output.

The redirect method
This method redirects the client to another URL. If you move your site to another URL, write a short ASP application such as the following to redirect the visitor automatically to the new URL.

<HTML>
<%
Response. Write "Our site was moved at a new URL."
Response. Write "Your browser will be redirected to the new URL automatically"
Response. Redirect "http://192.168.0.3/she/datetime.htm"
%>
</HTML>

The Clear Method
This method clears the data written to the Response object and it used only when the buffer property is set to True. Normally, the output is buffered until the entire page has been processed, and only then is it sent to the client. To force the information collected so far in the output stream to be transmitted to the client, call the Response object’s clear method.

The Content Type Property
This property determines the type of document you will sent to the client. The content type property applies to the entire page and must be Set before you write any information to the output stream with the write method.

Note:
You’ll find the various content types in the files tab of windows explorer’s options dialog box. (In any Explorer window, choose view ~options and SELECT the file types tab)

For example, if you want to sent source code of an Asp page, Set context type to “text/plan”, rather than to “text /HTML”, which is the default content type:
<%
Response. ContentType= “text/plan”
%>

The browser displays the pages as text, instead of rendering it as an HTML page (it’s like opening a TXT file with the browser).

The cookies property
Use this method to send cookies to the client. Cookies are special string that are stored on the local computer with the response Property, and your ASP application can read them back with the Request method.
In effect, cookies are a way to pass values between the pages of your web. The HTTP protocol used on the web is stateless. Each document is requested by the client and Transmitted by the server, and the Transaction completes at this point. If the same client requests another document from the same server, neither the client nor the server have any recollection of the previous Transaction.
Maintaining variables between different pages is problem with a stateless protocol, which is solve with the help of cookies. If your web pages use the consistent, but user defined background color, you can store this value to the cookie, let’s call it Bcolor, and then read it before constructing and transmitting a new page. Bcolor is of the Response object. To read its value, you access the Cookies Property of the request object.

The BufferProperty
By default, the Response object sends its output to the client as soon as it can, and it doesn’t wait for the entire page to complete. If you want to process the entire page before sending any output to the client, set the Buffer property of the Response object to True. Let’s say that as you process the page (with an ActiveX component or by reading data from a database), you discover that you need not send the previous data to the client or that you must redirect the client to another URL. Is the buffer property was set to True, you can cancel the processing and clear the response object with the clear method of the response object. Here’s a typical scenario:

<%
Response. Buffer = TRue
{SCRIPT STATEMENT}
If supplierName = UserName Then
                Response. Clear
Response. Redirect “/Suppliers/AllSuppliers.HTML”
Response. End
End IF
%>

This script builds a page by reading data from a database, until it discovers that the visitor is actually one of the suppliers and then it clears the output created so far ends the Response object, and redirect the visitors to another page. If your scripts take too long to process, however, nothing will appear on the client’s monitor, and visitors may think they are not getting a response. Normal HTML pages are not buffered, so you should not buffer, so you should not buffer your ASP pages by default.

The RequestObject
To interact with the visitor, your script should be able to request information that the visitor enters on a Form and read the values of cookies. Reading data back from the client has been a sore point in server scripting. ASP has simplify the process of reading the data submitted by the client by encapsulating all the complexity of the operation in to a few property of the request object. This single feature of ASP would be adequate to make it a major server- scripting tool.






The request object has five properties, all of which are collections;

QueryString contains the values passed to the server with the GET method.

From contains all the forms on the page.

Cookies contains all cookies that have been written to the client by the web site.

Server Variables contains all the HTTP variables, which are determined by the server.

Client Certificate contains all the client certificates installed on the client.

The QueryString Collection
The collection you’ll be using most often in developing ASP applications is the QueryString collection. This property gives you access to all the parameters passed along with the URL by the client. If the names of the parameters are known at the time you develop the ASP file, you can request their values by name, with expressions such as the following.
ReqProdName = Request. QueryString (“productName”)

If the names of the parameters are not known when you develop the ASP file or if you want to process them all serially, you can use a loop such as the following:

Set params= Request. QueryString (“productName”)
          For Each param in params
          {process parameter param)
Next

A simple HTML page with a perform (the SRVRFORM.HTM page on the CD); the user can enter information by Selecting options in list boxes. When done, they can click the Recalculate button to submit the information to the server, where the cost of the selected configuration will be calculated and sent back to the client as a new HTML page.
The names of the listbox control on the SRVRFRM page are: Hard Disk, memory. CD, speaker, and software. The possible values for each Setting are listed in the <OPTION> tag of each <SELECT> tag. The Options of the SELECT Memory list box have the values 32,64,128, and 256. The Memory query parameter will have one of these values, depending on which OPTION was selected on the form.

The SRVRFORM.HTM FILE

<H1>SELECT the order form the list</H1>
<Form name=“orderdetail” method=get action=param.asp>
<TABLE>
<TR>
<TD> <B> SELECT Hard Disk </B> </TD>
<TD> <B> SELECT memory</B> </TD>
<TD> <B> SELECT CD Drive</B> </TD>
</TR>
<TR>
<TD>
<SELECT name=“HardDisk” Size= “1”>
<OPTION Selected value= 10GB>10GB ulTRa EIDE HardDrive </OPTION>
<OPTION value = “30GB”> 30GB ulTRa EIDE HardDrive </OPTION>
</SELECT >
<TD>
<SELECT name =Memory size = “1” >
<OPTION value =32MB> 32MB EDO RAM </OPTION>
<OPTION Selected value =“64MB> 64MB EDO RAM </OPTION>
<OPTION value =“128MB”> 128MB EDO RAM </OPTION>
<OPTION value =“256MB”> 256MB EDO RAM </OPTION>
</SELECT>
</TR>
<TD>
<SELECT name = “CDDrive” size = “1” >
<OPTION value = “None”> None </OPTION>
<OPTION Selected value = “CD40X”> 12 EIDE CD-ROM </OPTION>
<OPTION Selected value = “CD52X”> 24 EIDE CD-ROM </OPTION>
</SELECT>
</TR>
<TR>
<TD> <B> SELECT Speakers </B> </TD>
<TD> <B> SELECT software</B> </TD>
</TR>
<TR>
<TD>
<SELECT name = “Speaker” size = “1” >
<OPTION Selected value = “None”> None </OPTION >
<OPTION value = “S90”> Altec ACS90 speakers </OPTION >
<OPTION value = “S290”> Altec ACS290 speaker </OPTION >
</SELECT>
</TD>
<TD>
<SELECT name = “Software” size = “1” >
<OPTION Selected value = “WIN95”> MS Windows 95 </OPTION >
<OPTION value = “WIN98”>Microsoft Windows 98 </OPTION >
<OPTION value = “WINNT”> Microsoft Windows NT Workstation 4.0 </OPTION >
</SELECT>
</TD>
</TABLE>
<BR><BR>
SELECT the desire Options and click the recalculate button to see your system’s price
<Br><Input type=submit value=Recalculate>
</FORM>
</HTML>

The display of above Tag   


The ASP page that processes this form is called PARAM.ASP, and it resides in the ASPages virtual folder on the server (its URL appears in the FORM tag). This page doesn’t do much. (It doesn’t actually recalculate the price of the configuration, but once you know the Options specify the visitor, it’s a relatively easy to calculate the price of the selected configuration.) The PARAM>ASP scripts generates another HTML page on the fly with the names and values of the parameters and sends it back to the client. The server’s response.
The PARAM. ASP page that process the data on the server uses a for … Each loops to scan all the items of the QueryString collection and display their names in anew table. Each parameter is stored in the variable pvalue. The default property of this variable is the name of the parameters. To access the value of the parameters, use the expression params (pvalue).

<HTML>
<%
Response. Write "<HTML>"
Response. Write "<BODY>"
Response. Write "<TABLE border rules=all>"
Response. Write "<TR><TD><b>Parameter Name</b></TR><TD><b>Parameter Value</b></TR>"
Set params=Request.QueryString
For Each PValue in params
                Response.Write "<TR><TD>" & Pvalue & "</TR><TD>" & params(pvalue) & "</TR>"
Next
Response. Write "</table>"
Response. Write "</HTML>"
%>
</HTML>

The display of above script


To access individual parameters, you can use the collection Request. QueryString followed by the names of the parameter whose value you want. The following lines will return the specifications of the memory and the hard Disk, as entered by the visitor on the form in the page SRVRFRM.HTM:
MemorySpec=Request.QueryString(“memory”)
HdiskSpec= Request.QueryString(“HardDisk”)

TIP
It is possible for multiple controls on a form to have identical names. In this case, the QueryString collection contains an array of values. For example if the form contains three textboxes named “Name”, you can access them as Request. QueryString (“name”) (1), Request. QueryString (“name”) (2), and Request. QueryString (“name”) (3).

The form collection
The form collection is similar to the QueryString collection in that it contains that it contains data that the visitor enter on a form. Where as the QueryString collection contains all the parameters submitted to the server, regardless of whether they belong to form the form collection contains the value of the parameters that come from controls. It is possible to build a URL followed by a number of parameter on the fly from within a client script. These parameters will be reported by the QueryString collection, but not by the form collection.

To access the value of a specific parameter in the form collection, use the statement such as the following:

The server variables Collection:
This collection contains a number of standard environment variables, which you can access from within your script. Basically, the server variables collection contains all the information available about the client and the server. Here are some of the most commonly used server variables:

SERVER_NAME: the server’s DNS or IP address.

SERVER_PROTOCOL: The name and revision number of the protocol used for the request. It’s usually HTTP/1.0.

SERVER_PORT: The TCP/IP port number on which the accepts request it’s usually 80.

SERVER_SOFTWARE: The name and version of the HTTP server software on the software machine.

SCRIPT_NAME: the path to the script being executed.

QUERY_STRING: the information that follows the question mark(?) in a URL . The GET method uses this variable, and you can retrieve it with the QueryString collection. This string is encoded according to the following two rules:
·         Spaces are converted to plus sign.
·         Any character may be represented as a hexadecimal number (representing the character’s ASCII value) prefixed with the percent sign. The plus sign is encoded as%2B.

REQUEST_METHOD: The HTTP method being used to send client data to the server. The possible values are GET and POST.

CONTENT_TYPE The type of data send the server. This variable is always application/x-www-form-urlencoded.

CONTENT_LENGTH: the length of the string holding the data. This variables is used with the post method.

REMOTE _HOST: the full domain name of the client that made the request.

REMOTE_ADDR: the IP (internet protocol) address of the requesting client.

The file SRVRPARAM, ASP contain assort script that displays all the server variables.

<HTML>
<%
Response.Write "<HTML>"
Response.Write "<BODY>"
Response.Write "<TABLE BORDER RULES =ALL>"
Response.Write "<TR><TD><B>ParameterName</B></TD><TD><B>Parametervalue</B></TD></TR>"
Set params=Request.ServerVariables
For Each PValue in params
Response. Write "<TR><TD>" & Pvalue & "</TD><TD>" & params(pvalue) & "</TD></TR>"
Next
Response. Write "<TABLE>"
Response. Write "</HTML>"
%>
</HTML>

The display of above script

Figure 1

The cookies collection
The collection is discussed in detail in the section “storing and recalling cookies”, later in this chapter. Cookies are basically variables stored by the server on the client computer that can be access by name, similar to parameter.

The client certificates collection:
This collection contains all the certificate installed on the client computer and is needed only when your ASP applications installed ActiveX component on the client. The property is supported only by internet explorer clients.

The server object
The server object control the environment in which the server side scripts are executed. The single most important member of the server object is it’s create object method, which can create a new instance of an object from a registered class.

The create object method
This method is identical to the visual Basic CreateObject() function. It accepts as an argument the programmatic ID (Class ID) of an object and returns an instance of the object. The syntax of the create object method is:

Server. CreatesObject (“progID”)
To Access a database through the ADO component, for instance, you first create a connection object and the RecordSet object with the following statements (see the section “using ActiveX Data Object,” later in this chapter, for more details on accessing databases through ASP):
Set ADOconnection =server.createobject(“ADDB.connection”)
Set ADORS =server .createobject(“ADODB.RecordSet”)

Similarly, you must create object variables to access the other basic components of ASP, such as the file Access component and the advertisement Rotator component. You can also use the server’s createobject method to create object variables for accessing your own custom ActiveX components. See the section “Using the Active Dataobject” for information on how to contract databases through object variables. In the section “Contracting ActiveX Components” at the end of the chapter, you’ll see how to create object variables that contract custom ActiveX components running on the server.

The MapPath Method
Another commonly used of the server object is the server object is the MapPath method, which maps virtual folders to actual path names. This method is useful in developing server–sides scripts for a very simple reason: all the flies you access are store in virtual folder. You can rearrange the entire folder structure of a web site and then rename a few virtual folders, and your script will never know. In some situations, however, you need to know the actual path to a file, and the MapPath method will return this value.

The session and application object.
The session object maintains variables that apply to a specific session. Before we examine the members of this object and how it’s developing an ASP application, let’s look at how the ASP component maintains session with the stateless protocol.
As I mentioned, HTTP is a stateless protocol. Each time the client request a new document, a new transaction is initiated. Then how does the ASP know that a new request from a client belong to an existing session? The answer is that ASP uses cookies.
When the client connect for the first time, the server send the ASPSESSIONID cookie, which is stored on the client computer. Then, every time the client contract the server, the ASPSESSIONID cookie is Transmitted along with the request header.

Note: The header contains information that both computers use to communicate, but you don’t have to know what type of information Transmitted or change the default headers.

ASP processes this cookie and uses it to restore the variable values saved previously in the session object. The ASPSESSIONID cookie doesn’t have an expiration value and expires automatically when the client disconnects. The next time the same client connects a new cookie is sent, and a new session is created. To maintains information between sessions, you must store a cookie with an expirations date on the client, read it as soon as the client connect to the web server, and use it as a key to a database with relevant data( such as user preferences, access rights, and so on ).

Note: Some browsers don’t support cookies (a rather rare situation today). These browsers don’t support sessions either. Basically the only limitation that ASP imposes on the client (if it can be considered a limitation) is that it support cookies.

The application object plays a similar role. It maintains a Set of variables, not for each session, but for the application. Simple examples are a welcome message that’s display on each clients window and a visitor counter. To implement a visitor counter with ASP, all you have to do is create an application–wide variable and increment it every time a client hits your home page (which must be an Asp document).
To create a new session or application variable, you need only reference it in your code ( this is VBScript; you are not required to declares variables ). The statement:
<% session (“Uname”) = Request.QueryString(“UserName”)%>

Assign the value of the cookie UserName (which presumably has been set by the client) to the session variables Uname. You can also assign function values to the Session variables, as the following statement does:
<% Session(“connected”) = Now( )%>

The name of the variables is on the left side of the above expressions. You can use session variables to build all types of expressions and statements with VBScript. The following statements terminate a client connection if it’s been active for more than 12 hours:
<%
If Hour(now() -session(“connected”) )>12 then
session.Abandon
End if
%>

The abandon method terminates the current session. Application variables are declared and used in the same manner, but since multiple scripts can access Application variables, there is always a chance that more than one script will attempt to change the value of an application variable. The application object provides the lock and unlock methods, which must be called before and after Setting the variables:

Application.lock
Application.(“VisitorCounter “) = Application(“VisitorCounter “)+1
Application. Unlock

The session and Application object support object variables too, created with the createobject method of the server object. The difference is that object variables stored in the session object cant be accessed by other session. If you have many clients accessing the same object (the same component on the server), you will be creating many instance of the same component, which may affect performance. This isn’t as simple as it sounds. An object can be accessed by multiple session only if it has been designed to support multiple threads of execution.


The start and end events
Both the sessions and the application object support start and end events, which signal when a session or an application start and when it ends. The start events are:
  • Session_OnStart
  • Application_OnStart

The end events are
  • Session _OnEnd
  • Application_OnEnd

These events handler include code you should run whenever and application or a session starts or ends. If an application and a session start at the same time, the Application_OnStart event is executed first. These events are important in developing ASP applications, but they are not available from within the script. You must enter them in the GLOBAL.ASA file, which lives in the root folder for the application (the folder where the first asp file to be requested by the client is stored). Typically, the GLOBAL.ASA file contains the start and end events of the session and Application objects, as well as variable definitions.
For example, if you want to implement a variable that stores the number of visitors hitting the site, initialize it in the application_OnStart event. Enter the following code in the GLOBAL.ASA file:

<SCRIPT LANGUAGE=“VBScript” RUNAT=server>
Sub application_OnStart
                Application(“visitors”) =0
End Sub
</SCRIPT>

This event takes place every time the web server software starts. Since you don’t want to reset this counter every time you stop and restart the server, you can save the value of the variable variables to a text file on the server’s disk, as explained in chapter 20. In the application_OnStart event, you read the value of the variable from the text file, and in the session_OnStart event, you Increase it by one:

<SCRIPT LANGUAGE=“VBScript” RUNAT=server>
Sub session_OnStart
Application.Lock
Application(“visitors”) = Application(“visitors”)+1
Application.UnLock
End sub
</SCRIPT>

You must also enter this procedure in the GLOBAL.ASA file. This technique works well. The number will not increase each time a visitor hits the home page during the same session, because the session_OnStart event is only triggered the first time.
Displaying a fancy counter on your pages is a different story. You can simply display this number in a large front on your Homepage, or you can generate a GIF file on the fly and display it on the home page. The structure d graphic control that comes with internet Explorer $ lets you create elaborate graphic with simple text commands. This control is probably the simplest way to display a graphic chat shows the number of the visitors.
If you pages call a specific component frequently during a session, you can declare an object variable in the sessions start event. This variable will be available from within any page during the current session. Here is simple example that creates an object variable referencing the object component:

<SCRIPT LANGUAGE=“VBScript” RUNAT=server>
Sub session_OnStart
Set session (“MyObj”) = server. CreateObject (“MyObject”)
End sub
</SCRIPT>

Any page in the Current session can use the MyObj object variables, and each session’s MyObj variable is independent of the other sessions “MyObj’ variable.


Storing and Recalling Cookies

You have certainly noticed that some of the sites you’ve visited (Microsoft’s home page is one of them) can be customized according to the visitor’s preferences. How is this done? How does the server know each visitor’s preferences between sessions? If each user had a fixed IP address, it would be possible (although not very practical) for the server to maintain a database with IP addresses and the preferences for each user. The IP address of the client computer is given by the Server Variables collection of the Server object. But clients have different IP addresses each time they connect, so this approach is out of the question.
Cookies are also used to pass information between pages of the same site. Let’s say you’re building a Web site for online orders. The site is made up of many pages. And visitors can order items from each page. How do you keep track of the visitors’ orders? Each page can have its own script, and each page can have its own variables, but their scope is limited to the page on which they were declared. There is no way for two or more pages to share common variables. This is direct consequence of HTTP being a stateless protocol. Each time a new page arrives at the client, the browser forgets everything about the current page (except for its URL so that it can jump back to it). Orders made on one page can be stored on the client computer in the form of cookies and read by any other page of the same site.
Since cookies are managed by the browser, Web can’t access your computer’s hard disk directly (that’s why cookies are safe). Moreover, when a page requests the values of the cookies, the browser supplies only those cookies that were stored by pages of the same site. In other words, cookies left on your computer by Microsoft’s Web site can’t be read by pages of other sites. The browser supplies each page with the cookies left by other pages of the same site.
Cookies have expiration dates too. If a cookie is stored without an expiration date, it ceases to exist after the current session. A cookie with as expiration date remains on the client computer until it expires.
To store a cookie on the client computer, use the Cookies property of the Response object. The Coolies property is a collection, and you can create and access individual cookies by name. To computer until it expires.
To store a cookie on the client computer, use the Cookies property of the Response object. The Cookies property is a collection, and you can create and access individual cookies b name. To create a new cookie, use a statement such as the following:
<% Response.Cookies (“FavoriteSport’)=“Hockey”

If the cookie FavoriteSport exists on the client computer, its value will be over written. If it does not exist, a new cookie is created. This cookie is released as soon as the current session ends.

You can specify the expiration data time with the Expires property of the cookie, as follows:


<%
Response.Cookies(“FavoriteSport”). Expires=December 31,1998
12:00:00 GTM”
%>

Cookies have other properties too:
Domain: If specified, the cookie value is sent only to requests from this domain. This property is used along with the Path property.

Path: If specified, the cookie is sent only to requests made from this path on the server, and not to every page on the same site.

HasKeys: Specifies whether the cookie contains multiple keys (in which case it’s a dictionary). This property is read-only.

To create cookies with keys, use the same cookie name with multiple attributes, as in the following statements:

<%
Response.Cookies(“Preferences”)(“Books”)= “Mystery”
Response.Cookies(“Preferences”)(“News”)= “Sports”
%>

To request the value of a specific cookie from the client, use the Cookies collection of the Request object. The number of cookies in the Cookies collection is given by the Request. Cookies, Count property.
You can write a For … Next loop that scans the collection, or you can write a For Each…Next loop such as the following:

<%
For Each cookie In Request.Cookies
{process current cookie, which is Request. Cookies (cookie)}
Next cookie
%>

Normally, the script on the server knows the names of the cookies and can request them by their names:
BookType= Request.Cookies(“FavoriteSport”)

If you need to fine out the names of the cookies, use the For Each…Next structure . At each iteration, the value of the cookie variable is the name of the cookie and Request. Cookies (cookie) is its value
If a cookie has keys, you must access them as elements of a collection. Let’s assume you‘ve sent a cookie with keys to the client with the following statements:

<%
Response.Cookies(“Background”) = “Planets.bmp”
%>

Building a RecordSet

After you establish a connection to the database, you can assess it with SQL statements. To issue a SQL statement, use the Execute method of the Connection object, and pass the SQL statement as an argument. The syntax of the Execute method is:

DB Connection. Execute SQL Statement
The SQL Statement argument can be a string with the SQL statement or the name of a stored procedure. IF the SQL statement returns records (as does the select statement), the Execute method returns a RecordSet and should be called as follows:
Set SelRecords= DBConnection. Execute9SQLStatement)

The Execute method accepts two optional arguments:

The number 0of records affected by the operation (this parameter is set by the drive)

Whether the SQL statement is SQL text or the name of a stored procedure

The method’s compete syntax is:
DBConnection.Execute SQLStatement, numRecords, SQL Text

The SQLText argument can have the value adCmdText(for SQL statements)or adCmdStored object with the statement procedures).

Example of the page that is used to transmit info, store info and delete info from the database.

 

Final.htm page (Used to submit info in the database)

<HTML>
<BODY bgcolor=green>
<H2>Input the value</H2>
<Form name=frmdetail method=post action="final.asp">
Name: <Input type=text name="TxtName"><BR>
Address: <input type=text name=txtaddress></BR>
<input type=submit value="Submit">
</BODY>
</HTML>


Final.asp page (Used to store in the database)
<%
response.write "<HTML>"
response.write "<BODY bgcolor=green>"
response.write "<H1>Here is the value that you send</H1>"
Dim val1, val2
val1=request.form("txtname")
val2=request.form("txtaddress")
response.write "Your name is: " & val1 & "<BR>"
response.write "Your address is: " & val2
Set conn=server.createobject("Adodb.connection")
conn.provider="Microsoft.jet.oledb.4.0"
conn.properties("Data Source")=server.mappath("newdb.mdb")
conn.open
strsql="insert into customers values('" & val1 & "','" & val2 & "')"
conn.execute (strsql)
response.write "<BR>"
response.write "<A href=http://localhost/sw/final.htm>Done</A>"
response.write "<BR>"
response.write "<A href=http://localhost/sw/finalview.asp>View All Record</A>"
response.write "</BODY>"
response.write "</HTML>"
%>

 

Finalview.asp Page (This page display all the info store in the database with delete facility)

<%
response.write "<HTML>"
response.write "<BODY bgcolor=green>"
response.write "<H1>The records inside the database are:</H1>"
response.write "<TABLE>"
response.write "<TR><TD>Name" & "</TD>Address" & "</TR>"
Set conn=server.createobject("adodb.connection")
Set rs=server.createobject("adodb.recordSet")
conn.provider="microsoft.jet.oledb.4.0"
conn.properties("data source")=Server.Mappath("newdb.mdb")
conn.open
Set rs=conn.execute("SELECT * from customers")
do while rs.eof=false
response.write "<TR><TD>" & rs(0) & "<TR>" & rs(1) & "</TR>"
rs.movenext
loop
response.write "<A href=http://192.168.0.220/final.htm>Done</A>"
conn.close
response.write "</TABLE>"
response.write "<FORM name=frmdetail method=post action=deleteRecord.asp>"
response.write "Enter the Name to delete:<input type=text name=txtdelName>"
response.write "<input type=submit value=DeleteRecord name=cmddelete>"
response.write "</FORM>"
response.write "</HTML>"
%>


DeleteRecord.Asp page (This page is used to delete the record Set in the finalview.asp page)

<%
response.write "<HTML>"
response.write "<BODY bgcolor=green>"
response.write "<H2>The record of " & request.form("txTDelname") & " has been deleted successfully</H2>"
Dim val1,strsql
val1=request.form("txTDelname")
Set conn=server.createobject("adodb.connection")
Set rs=server.createobject("adodb.recordSet")
conn.provider="microsoft.jet.oledb.4.0"
conn.properties("data source")=Server.Mappath("newdb.mdb")
conn.open
strsql="Delete from customers where name='" & val1 & "'"
conn.execute(strsql)
Set rs=conn.execute("SELECT * from customers")
response.write "<H2>The record remaining in the database is</H2>"
response.write "<table>"
response.write "<TR><TD>Name" & "<TD>Address" & "</TR>"
do while rs.eof=false
response.write "<TR><TD>" & rs(0) & "<TD>" & rs(1) & "</TR>"
rs.movenext
loop
response.write "</table>"
response.write "<a href=http://localhost/sw/final.htm>Done</a>"
response.write "</BODY>"
response.write "</HTML>"
%>

 

A Typical GLOBAL.ASA File

This file is placed on the root directory of the site. It includes the sever variables and events handlers related with site and application. This page loads before the request page form the client.

<SCRIPT LANGUAGE=VBScript RUNAT=Server>
Sub Application_onStart
                Application(“Viewers”)=0
End Sub
Sub Session_onStart
                Application.Lock
Application(“Viewers”)=Application(“Viewers”)+1
Application(“Viewers”)=Application(“Visitors”)+1
Applilcation.Unlock
Session(“User”)=Request.ServerVariables(“REMEOTE_ADDR”)
End Sub
Sub Session_onEnd
                Application.Lock
Application(“Viewers”)=Application(“Viewers”)-1
Applilcation.Unlock
End Sub
</SCRIPT>

No comments:

Post a Comment

Thanks for comment me