Vous êtes sur la page 1sur 6

Active Server Pages How much will Active Server Pages cost?

Microsoft® Active Server Pages (ASP) is a server-side scripting environment that you can use to Active Server Pages is a component of IIS 3.0, which is a free, downloadable, and integrated feature of
create and run dynamic, interactive Web server applications. With ASP, you can combine HTML Windows NT Server 4.0.
pages, script commands, and COM components to create interactive Web pages and powerful Web-
based applications that are easy to develop and modify.
Features
Combine HTML pages, script commands, and COM components to create interactive Web pages and
powerful Web-based applications that are easy to develop and modify. What can Active Server Pages do for my business?

Active Server Pages can develop a new generation of Web-based applications, including extending sales
Product Overview and customer service to the Web, and providing access to corporate databases and applications to any
browser on an intranet.
What is Active Server Pages?
What ActiveX Server Components are supported?
Microsoft® Active Server Pages (ASP) is the server-side execution environment in Microsoft Internet
Information Server (IIS) 3.0 that enables you to run ActiveX™ scripts and ActiveX server components on Active Server Pages allows organizations to extend the power of scripting on the server with ActiveX
the server. By combining scripts and components, developers can create dynamic content and powerful server components. These components can be created using Microsoft Visual Basic, Visual C++®, Java,
Web-based applications easily. and other languages.
What is dynamic content? What scripting languages does Active Server Pages support?
Web pages that are customized for each user on the fly, based upon their actions or requests. For example, Active Server Pages provides native support for both Microsoft JScript and VBScript. ActiveX scripting
new visitors to your site can be shown a different welcome page than returning users see, or pages in an plug-ins are available for REXX, PERL, and Python.
online catalog can be queries to a database so customers always see the most current information and
availability.
What browsers does Active Server Pages support?
Who should use Active Server Pages? Active Server Pages can work with any Web browser. The output of an ASP file is plain HTML, the
content of which can be customized for the capabilities of the client.
Organizations will use the Active Server Pages technology to put a Web front end on existing business
solutions, or to create entirely new Web-based applications. Since ASP provides a very open development
Does Active Server Pages maintain state for me?
environment, with support for both Microsoft Visual Basic®, Scripting Edition (VBScript) and JScript™,
organizations can leverage the investments they already have in these scripting languages.
Yes. Active Server Pages allows you to define application and session variables that can be carried across
multiple pages in a Web site. This can be as simple as remembering a user's name, and it is necessary in
Who can create dynamic content with Active Server Pages? applications such as online shopping to track product selections.
Webmasters, information systems (IS) professionals, and programmers familiar with Hypertext Markup
What about legacy data?
Language (HTML) and languages such as Microsoft Visual Basic, JavaScript, PERL, REXX, or C++.
Active Server Pages makes it easy to bring legacy database applications to the Web.
What do I need to run Active Server Pages?

The Active Server Pages feature of IIS 3.0 requires Microsoft Windows NT® Server 4.0 running IIS 2.0 Implementation Questions
or Windows NT Workstation 4.0 running Peer Web Services.
On which platforms does Active Server Pages run?
The ASP feature does not require Service Pack 2 for Windows NT 4.0, although it is recommended that
all Windows NT systems receive the Service Pack 2 updates. The ASP feature contains a subset of the Active Server Pages will run on Microsoft Windows NT Server 4.0, Windows NT Workstation 4.0 with
updates found in Service Pack 2. Peer Web Services, and Microsoft Windows® 95 with Personal Web Server. Windows NT 3.51 is NOT
supported. Windows NT 4.0 on MIPS is also not supported by ASP.
Installation of ASP will upgrade IIS version 2.0 to version 3.0. The other IIS 3.0 features—Index Server
1.1, Microsoft NetShow™, FrontPage® 97 Server Extensions, and Crystal Reports—add significant Is Active Server Pages secure?
functionality to IIS, but are not required to take advantage of ASP.

1 2

Yes. Active Server Pages is a component of Internet Information Server, and thus uses Windows NT Can I use existing Automation servers?
Security. ASP files can be easily restricted to just certain users through secure Windows NT
authentication, basic Web authentication, or client-side certificates. For additional security, all client-to- There really are no minimum requirements for a component, beyond supporting Automation through
server communications can be secured with Secure Sockets Layer (SSL). IDispatch. You can optionally provide the following two methods on IDispatch:

What data sources can my Web application integrate with? 1. OnStartPage


2. OnEndPage
An Active Server Pages application can integrate with any ODBC-compliant databases including
Microsoft SQL Server™, Oracle, Sybase, Informix, and DB2 databases. Any OLE 2 application, such as Refer to "Creating ASP Components" in the Programmer's Reference for more details.
Lotus Notes or Microsoft Excel, can also be scripted to access or process information. You can also write
components to access online data feeds and legacy mainframes.
Competition
How does Active Server Pages compare to CGI?
What does Active Server Pages do better than other Web application tools?
Active Server Pages provides all of the functionality of CGI applications in an easier-to-use and more
Active Server Pages allows you to quickly bring your existing skills and knowledge, data sources,
robust environment.
components, and applications to the Web. Other tools create either static HTML or lock you into a non-
standard programming model or language. ASP is based upon the leading industry standards, making it
ASP is an easier way for your server to access information in a form not readable by the client (such as an
easy to build, maintain, and evolve powerful interactive Web applications.
SQL database) and then act as a gateway between the two to produce information that the client can view
and use.
How does Active Server Pages compare to Netscape LiveWire?
With CGI, the server creates as many processes as the number of client requests received. The more
Netscape LiveWire requires the use of JavaScript, while Active Server Pages supports the use of virtually
concurrent requests there are, the more concurrent processes created by the server. However, creating a
any scripting language, with native support for VBScript and JScript. ASP supports components written in
process for every request is time-consuming and requires large amounts of server RAM. In addition, this
any language, while LiveWire supports only Java components.
can restrict the resources available for sharing from the server application itself, slowing down
performance and increasing wait times on the Web.
LiveWire applications must be manually compiled after each change, and then the application stopped and
restarted. Active Server Pages recognizes when an ASP file changes and automatically recompiles the
Active Server Pages runs in the same process as the Web Server, handling client requests faster and more
application at the next request.
efficiently. It is much easier to develop dynamic content and Web applications with ASP.

How does Active Server Pages compare to ISAPI applications?

ISAPI applications require all of the programming and layout to be contained in a .dll file written in C++. What Is an ASP File?
ISAPI applications are thus more difficult to create and maintain. With ASP files, an HTML writer can
script an external component and format the output. ASP separates the layout and design from the Files created with Active Server Pages have the extension .ASP. This story is an example; take a look at
business logic. the address above. With ASP files, you can activate your Web site using any combination of HTML,
scripting—such as JavaScript or Visual Basic® Scripting Edition (VBScript)—and components written in
How does Active Server Pages compare to PERL? any language. This means your ASP file is simply a file that can contain any combination of HTML,
scripting, and calls to components. When you make a change on the ASP file on the server, you need only
PERL and other scripting languages are not robust development tools by themselves. Active Server Pages save the changes to the file—the next time the Web page is loaded, the script will automatically be
provides a familiar framework and objects for building complex applications that require data from compiled. How does this happen? It works because ASP technology is built directly into Microsoft Web
relational databases and legacy sources. servers, and is thus supported on all Microsoft Web servers: Windows NT Internet Information Server
(IIS) 3.0, Windows NT Workstation, and Windows 95 Personal Web Server.
ASP supports virtually any scripting language to build these applications. Third parties are currently
developing additional scripting engines, such as PERL, which we will announce when they are ready. A few examples of the use of Active Server Pages with IIS 3.0:

Can Active Server Pages use Java? • Put your employee handbook online, rather than printing copies that are soon obsolete. An added
benefit is the reduction of administrative costs when employees can access and update their own
Yes. Active Server Pages supports ActiveX server components written in any language, including Java. In records, such as address and health-plan benefits. I know of several administrative assistants who
addition, ASP includes the Microsoft Windows reference standard Java Virtual Machine. would love this one!
• Tie your online store to your existing inventory database and order-processing system.
3 4
• Give every visitor to your site a personalized view of just the information he or she seeks, and ASP uses the delimiters (better known to you and me as "thing-a-ma-bobs that specify the beginning and
automatically flag what is new since the last visit. end") "<%" and "%>" to enclose script commands. For example, the code below sets the value of the
• I know what you're thinking: "So what? I can write CGI scripts right now that will let me update variable "MyFavTVShow" in the user cookie to "I Dream of Jeannie."
information and have it reloaded next time the page is loaded." That's true, but ASP runs as a
service of the Web server and is optimized for multiple threads and multiple users. This means that Copy
it's fast, and it's easy to implement. If you use ASP, you can separate the design of your Web page <%Response.Cookies("MyFavTVShow")="I Dream of Jeannie"%>
from the nitty-gritty details of programming access to databases and applications. This frees up the
programmer to do what she does best—code like crazy—and, conversely, frees the designer to
worry about just the design rather than the database. The scripting languages supported by ASP in turn support use of the If-Then-Else construct (something
that will undoubtedly warm the hearts of all coders out there). Finally, you can embed some real logic into
It all works together via scripting. your HTML. For example, the following code from the IIS documentation shows how you can set the
greeting shown based upon the time of day.
An example is a form that is used to pass a ticker symbol request in the URL to the ASP files. The first
part of the ASP file calls a component that talks to a stock-price server. Properties of this object, such as Copy
<FONT COLOR="GREEN">
opening and closing price, can then be easily inserted in the HTML. The programmer can work in any <%If Time >= #12:00:00 AM# And Time < #12:00:00 PM# Then%>
language, and need worry only about how to talk to the stock-price server. The HTML author need know Good Morning!
only how to script the component, and does not care how the stock-price server works. <%Else%>
Hello!
<%End If%>
Is It Hard to Use? </FONT>

I don't know about you, but whenever people start talking about doing things on the server, I start to get
nervous. I think a lot about threading issues, synchronization, and generally stuff without a user interface. I'm sure that you can think of something more interesting for your Web site—I'd hate to have to come up
I assume it's going to be hard to do. Well, using ASP is about as easy as anything I've come across in with all of the clever ideas.
years.
Built-in Objects
If you're an experienced programmer, you don't even have to learn a new language to create ASP files—
you can use any language that supports ActiveX scripting. If you already develop with Visual Basic, using ASP includes five standard objects for global use:
VBScript is a snap!
• Request—to get information from the user
Or, if you know how to author pages in HTML, you're probably ready to advance your skills a notch—and • Response—to send information to the user
ASP is the perfect reason. Learning VBScript is not hard. Neither is JScript, Microsoft's implementation • Server—to control the Internet Information Server
of JavaScript. • Session—to store information about and change settings for the user's current Web-server session
• Application—to share application-level information and control settings for the lifetime of the
You don't even have to write your own controls to start using Active Server Pages. You can use any off- application
the-shelf-control that can be run on a server and has no user interface The reason it should not have a user
interface becomes obvious when you picture some hapless computer operator sitting in front of the server, The Request and Response objects contain collections (bits of information that are accessed in the same
dismissing dialog boxes meant for the user's machine. I mean, why should the operator care whether way). Objects use methods to do some type of procedure (if you know any object-oriented programming
you've logged on successfully? User interfaces are for client applications (applications that the user is language, you know already what a method is) and properties to store any of the object's attributes (such
running)--not for server-side scripting. as color, font, or size).

The Request object


Aw, Mom. Not Another Object Model!
The Request object is used to get information from the user that is passed along in an HTTP request. As I
I really hate doing this to you, but I'm going to have to use that overused and overcomplex term "object mentioned earlier, the Request and Response objects support collections:
model" again. Here's how it works. When a browser requests an ASP file from your Web server, your
Web server calls Active Server Pages to read through the ASP file, executing any of the commands • ClientCertificate—to get the certification fields from the request issued by the Web browser. The
contained within and sending the resulting HTML page to the browser. An ASP file can contain any fields that you can request are specified in the X.509 standard
combination of HTML, script, or commands. The script can assign values to variables, request • QueryString—to get text such as a name, such as my favorite TV sitcom above
information from the server, or combine any set of commands into procedures. • Form—to get data from an HTML form
• Cookies—to get the value of application-defined cookie
5 6

• ServerVariables—to get HTTP information such as the server name The Session object is used to store information about the current user's Web-server session. Variables
stored with this object exist as long as the user's session is active, even if more than one application is
The Response object used. This object supports one method, Abandon, which (believe it or not!) abandons the current Web-
server session, destroying any objects, and supports two properties, SessionID, containing the identifier
The Response object is used to send information to the user. The Response object supports only Cookies for the current session, and Timeout, specifying a time-out value for the session. One thing to bear in
as a collection (to set cookie values). The Response object also supports a number of properties and mind about the session identifier: It's not a GUID. It's only good as long as the current Web-server session
methods. Properties currently supported are: is running. If you shut down the Web-server service, the identifiers will start all over again. So don't use it
to create logon IDs, or you'll have a bunch of duplicates and one heck of a headache.
• Buffer—set to buffer page output at the server. When this is set to true, the server will not send a
response until all of the server scripts on the current page have been processed, or until the Flush The Application object
or End method has been called.
• ContentType—to set the type of content (i.e: text/HTML, Excel, etc.) The Application object can store information that persists for the entire lifetime of an application (a group
• Expires—sets the expiration (when the data in the user's cache for this Web page is considered of pages with a common root). Generally, this is the whole time that the IIS server is running. This makes
invalid) based on minutes (i.e.: expires in 10 minutes). it a great place to store information that has to exist for more than one user (such as a page counter). The
• ExpiresAbsolute—allows you to set the expiration date to an absolute date and time. downside of this is that since this object isn't created anew for each user, errors that may not show up
• Status—returns the status line (defined in the HTTP specification for the server). when the code is called once may show up when it is called 10,000 times in a row. In addition, because
the Application object is shared by all the users, threading can be a nightmare to implement.
The following methods are supported by the Response object:

• AddHeader—Adds an HTML header with a specified value


• AppendToLog—Appends a string to the end of the Web server log file ntroduction
• BinaryWrite—writes binary data (i.e, Excel spreadsheet data)
• Clear—clears any buffered HTML output.
Microsoft® Active Server Pages (ASP) is a server-side scripting technology that can be used to create
• End—stops processing of the script.
dynamic and interactive Web applications. An ASP page is an HTML page that contains server-side
• Flush--sends all of the information in the buffer.
scripts that are processed by the Web server before being sent to the user's browser. You can combine
• Redirect—to redirect the user to a different URL
ASP with Extensible Markup Language (XML), Component Object Model (COM), and Hypertext
• Write—to write into the HTML stream. This can be done by using the construct
Markup Language (HTML) to create powerful interactive Web sites.
Copy
Response.write("hello") Server-side scripts run when a browser requests an .asp file from the Web server. ASP is called by the
Web server, which processes the requested file from top to bottom and executes any script commands. It
then formats a standard Web page and sends it to the browser.
or the shortcut command
It is possible to extend your ASP scripts using COM components and XML. COM extends your scripting
Copy capabilities by providing a compact, reusable, and secure means of gaining access to information. You can
<%="hello"%> call components from any script or programming language that supports Automation. XML is a meta-
markup language that provides a format to describe structured data by using a set of tags.

The Server object As you work through the lessons in each module, save your work in the C:\Inetpub\Wwwroot\Tutorial
directory to view the content on your Web site. If you did not customize your installation of IIS,
The Server object supports one property, ScriptTimeout, which allows you to set the value for when the C:\Inetpub\Wwwroot was created as the default home directory. To load and run the tutorial samples, you
script processing will time out, and the following methods: must have administrator privileges on the computer running IIS. The default IIS security settings should
allow you to run the tutorial, but you may need to change your security settings on the directory if you
• CreateObject—to create an instance of a server component. This component can be any encounter access violations. See the product documentation for more information about IIS security
component that you have installed on your server (such as an ActiveX ). settings.
• HTMLEncode—to encode the specified string in HTML.
• MapPath—to map the current virtual path to a physical directory structure. You can then pass that
path to a component that creates the specified directory or file on the server. Module One
• URLEncode—applies URL encoding to a specified string.
This module explains how to create ASP pages (.asp files) that use the fundamental features of HTML,
The Session object ASP, and VBScript. This module includes the following lessons:

7 8
• Write and Run an ASP Page. Describes how to use Visual Basic® Scripting Edition (VBScript) Copy
and HTML tags. <%@ Language=VBScript %>
• Send Information by Using Forms. Shows how to display forms on an HTML page. <html>
<head>
• Create a Guest Book. Uses forms to gather information from visitors, store the information in a <title>Example 1</title>
database, and display the database contents in a Web page. </head>
• Display an Excel Spreadsheet in ASP. Explains how to display an Excel spreadsheet in a Web <body>
page. <%
FirstVar = "Hello world!"
%>
Write and Run an ASP Page <%=FirstVar%>
</body>
The best way to learn about ASP pages is to write your own. This lesson covers VBScript syntax and </html>
coding samples. To create an ASP page, use a text editor to insert script commands into an HTML page.
Saving the page with an .asp file name extension tells the Web server how to process the script
commands. To view the results of a script, request the page using a Web browser. VBScript is the default Example 2
scripting language for ASP, and most of the examples in the tutorial are scripted in VBScript.
This example incorporates a FOR loop in the ASP page. The FOR loop is a statement that prints "Hello
In HTML, you use brackets as delimiters around the tags: World" 10 times. To create Example 2, use the file from Example 1 and add the FOR loop code as shown
in the following code sample. Save the file as Example2.asp. View it in your browser.
Copy
<example> Copy
<%@ Language=VBScript %>
<html>
<head>
In VBScript, you use the percent sign with brackets as delimiters around the tags: <title>Example 2</title>
</head>
Copy <body>
<%example%> <%
FirstVar = "Hello world!"
%>
<%FOR i=1 TO 10%>
You can put many tags inside one pair of VBScript delimiters: <%=FirstVar%>
<%NEXT%>
Copy </body>
<%example, samples%> </html>

Example 1 Example 3

This example displays the words "Hello World". To run this example, cut and paste it into an empty file In this example, a time stamp is added to the ASP page. The word time is a function; it is a predefined
and save it in the C:\Inetpub\Wwwroot\Tutorial directory as Example1.asp. Make sure to save your file VBScript function variable containing the current time. There are more than 90 functions in VBScript.
with an .asp extension. Some text editors automatically change the file name extension to .txt when the Add the code for time shown in the following code sample to Example2.asp and save it as Example3.asp.
Text Document option is selected in the Save dialog box. To prevent this, select the All Files(*.*) option. View it in your browser.
Exit your text editor as the server may not be able to display an HTML page that is open in a text editor.
View your page with your browser by typing http://<Your Server Name>/Tutorial/Example1.asp in the Copy
address bar. <%@ Language=VBScript %>
<html>
<head>
When running Example 1, the page is processed by the Web server in the following sequence: <title>Example 3</title>
</head>
1. Assigns the text "Hello World" to the variable FirstVar. <body>
<%
2. Uses HTML to make an HTML page.
FirstVar = "Hello world!"
3. Uses <%FirstVar%> to print out the value of the variable FirstVar. %>
4. Ends the HTML page. The time is: <%=time%> <BR>
<%FOR i=1 TO 10%>
<%=FirstVar%>
9 10

<%NEXT%> <P>
</body> <INPUT TYPE="button" NAME="choice" VALUE="Less than 1">Less
</html> than 1 year.<BR>
<INPUT TYPE="button" NAME="choice" VALUE="1 to 5">1-5 years.<BR>
<INPUT TYPE="button" NAME="choice" VALUE="More than 5">More
than 5 years.
Example 4 </P>
<P><INPUT TYPE="reset" VALUE="Clear Form">
This example displays the message "Good Morning Everyone" if the hour is between 4:00 A.M. and 6:00 <INPUT TYPE="submit" VALUE="Submit">
P.M. It displays the message "Good Night Everyone" if the hour is between 6:00 P.M. and 4:00 A.M. Add </P>
the IF THEN statement in the code shown below to Example3.asp and save it as Example4.asp. </form>
</body>
</html>
Copy
<%@ Language=VBScript %>
<html>
<head> Text example
<title>Example 4</title>
</head> In this example, you create text fields in a form. Open a new file in your text editor, paste in the following
<body> code, and save the file as Text.htm:
<%IF Hour(time)>18 OR Hour(time)<4 THEN%>
Good Night Everyone.
<%ELSE%> Copy
Good Morning Everyone. <html>
<%END IF%> <head>
</body> <title>Text Form</title>
</html> </head>
<body>
<FORM NAME="Text Example" FORM METHOD="POST" ACTION="tutorial/text.htm">
<TABLE>
Send Information by Using Forms <TR>
<TD ALIGN="RIGHT" VALIGN="MIDDLE">Name?
A common use of intranet and Internet server applications is to process a form submitted by a browser. <TD ALIGN="LEFT">
With ASP, you can embed scripts written in VBScript directly into an HTML file to process the form. <INPUT TYPE="text" NAME="name" VALUE=""
SIZE="20" MAXLENGTH="150">
ASP processes the script commands and returns the results to the browser. In this lesson, you create an <TR>
HTML page that displays various elements of an HTML form. Later in this module, you use this <TD ALIGN="RIGHT" VALIGN="MIDDLE">Company?
knowledge of forms to build a guest book application on your Web site. <TD ALIGN="LEFT">
<INPUT TYPE="text" NAME="company" VALUE=""
This lesson contains the following examples: SIZE="25" MAXLENGTH="150">
<TR>
<TD ALIGN="RIGHT" VALIGN="MIDDLE">
• Button example. Displays selection buttons in the form. Email Address?
• Text example. Displays text boxes in the form. <TD ALIGN="LEFT">
<INPUT TYPE="text" NAME="email" VALUE=""
SIZE="25" MAXLENGHT="150">
Button example </TABLE>
<INPUT TYPE="reset">
In this example, there are three input lines that use "buttons," and two default buttons-RESET and <INPUT TYPE="Submit" NAME="Submit" VALUE="Submit">
SUBMIT. The Post method is used to send data from the client browser to the Web server. Open your text </form>
editor, create a new file, and paste in the following code. Save the file as Button.htm and view the page in </body>
</html>
your browser.

Copy Create a Guest Book


<html>
<head>
<title>Button Form</title> This lesson describes how to develop a guest book application. Guest books allow visitors to your site a
</head> chance to give you feedback. Information such as the visitor's name, e-mail address, and comments can be
<body> available to you.
<FORM NAME="Button Example" METHOD="POST" ACTION="tutorial/button.htm">
Computer Programming Experience:
Create the guest book database
11 12
You must first create an Access database called Guestbook.mdb and save it in the END IF
'Connects to the Access driver and Access database in the Inetpub
C:\Inetpub\Wwwroot\Tutorial directory. The database must have the fields with the properties described
'directory where the database is saved
in the following table. strProvider = "Driver={Microsoft Access Driver (*.mdb)};
DBQ=C:\Inetpub\Wwwroot\Tutorial\guestbook.mdb;"
Field Name Data Type and General Properties 'Creates an instance of an Active Server component
set objConn = server.createobject("ADODB.Connection")
ID AutoNumber, Field Size=Long Integer, New Values=Increment, 'Opens the connection to the data store
Indexed=Yes(No Duplicates) objConn.Open strProvider
'Instantiate Command object and use ActiveConnection property to
TB1 Text, Field Size=255, Required=No, Allow Zero Length=Yes, 'attach connection to Command object
Indexed=No set cm = Server.CreateObject("ADODB.Command")
TB2 Text, Field Size=255, Required=No, Allow Zero Length=Yes, cm.ActiveConnection = objConn
Indexed=No 'Define SQL query
cm.CommandText ="INSERT INTO Guestbook (TB1,TB2,TB3,TB4,MB1)
TB3 Text, Field Size=255, Required=No, Allow Zero Length=Yes, VALUES (?,?,?,?,?)"
Indexed=No 'Define query parameter configuration information for guestbook fields
set objparam=cm.createparameter(, 200, , 255, strTB1)
TB4 Text, Field Size=255, Required=No, Allow Zero Length=Yes, cm.parameters.append objparam
Indexed=No set objparam=cm.createparameter(, 200, , 255, strTB2)
MB1 Memo, Required=No, Allow Zero Length=Yes cm.parameters.append objparam
set objparam=cm.createparameter(, 200, , 255, strTB3)
cm.parameters.append objparam
After you create the database, you need to create a data source name (DSN) connection to the database so set objparam=cm.createparameter(, 200, , 255, strTB4)
your ASP application can interact with it. The DSN must be created on the Web server that is running the cm.parameters.append objparam
ASP application. If you move the ASP application to a different Web server, you have to re-create the set objparam=cm.createparameter(, 201, , iLenMB1, strMB1)
cm.parameters.append objparam
DSN on the new Web server. The following procedure describes how to create a DSN on Windows NT cm.execute
and Windows 2000. response.write("Thank you!")
ELSE%>
1. In the ODBC Data Source Administrator, select the ODBC icon. <h1>Guestbook</h1>
<!--Post information to Guestbook form -->
2. Select File DSN. <form name=guestbook.asp action="guestbook.asp" method="POST">
3. Select Add, select Microsoft Access Driver, and click Next. <p>To</p>
4. Type in a descriptive name for your file DSN (Guestbook) and click Next. <p><input type="Text" name="To"></p>
5. Click Finish, click Select, specify the location of the database file, and select OK. <p>Email Address</p>
6. Click OK twice. After you specify the location of the database file, the ODBC Data Source <p><input type="Text" name="EmailAdd"></p>
<p> CC</p>
Administrator creates a file DSN for it. <p><input type="Text" name="CC"></p>
<p>Subject</p>
Now that you have created the database and the DSN, paste the following code into a file named <p><input type="Text" name="Subject"></p>
Guestbook.asp and place it in the C:\Inetpub\Wwwroot\Tutorial directory. <p>Message</p>
<p><textarea name="Memo" rows=6 cols=70></textarea></p>
<input type="HIDDEN" name="Message" value="True">
Copy <input type="submit" value="Submit information">
<% @Language=VBScript %> </form>
<html dir=ltr> <%End if%>
<head> </body>
<TITLE>Guest Book</TITLE> </html>
</head>
<body bgcolor="#FFFFFF" text="#000000">
<%
IF request.form ("Message")="True" THEN View the database in a browser
strTB1=request.form("To")
strTB2=request.form("EMailAdd") Using a database to collect information left by visitors is a safe and simple way to make your Web site
strTB3=request.form("CC") more useful. Once information is entered in a database, you can either open the database in the application
strTB4=request.form("Subject")
strMB1=request.form("Memo") in which it was originally created, or you can use a Web page containing another script to view and edit
IF strMB1 = "" THEN the data. The following is a script that allows visitors to view and edit your database. To learn more about
iLenMB1=255 how to limit access to resources on your site, see "NTFS Security, Part 1: Implementing NTFS Standard
ELSE Permissions on Your Web Site," available at http://www.microsoft.com/technet/iis/ntfssec.asp.
iLenMB1 = Len(strMB1)

13 14

Copy &"</td>"
<% @Language=VBScript %> NEXT
<html dir=ltr> rst.MoveNext
<head> WEND
<title>View Guest Book</title> END IF
</head> %>
<body bgcolor="#FFFFFF" text="#000000"> </table>
<% </form>
'This section makes it possible for visitors to sort the data in the </body>
columns in ascending order. </html>
if request.form("sort")<> "" THEN
StrSort=request.form("sort")
ELSE Display an Excel Spreadsheet in ASP
StrSort="TB1 ASC"
END IF
strQuery="SELECT * FROM Guestbook ORDER BY " &StrSort This lesson demonstrates a technique that can be used to display a Microsoft Excel spreadsheet in a Web
'Database path statement describing the driver to use and the page. There are several standard server components supplied with IIS. One of these is the ActiveX® Data
path to the desired database. Objects (ADO) component, which is used as a connection mechanism to provide access to data. In the
strProvider = "Driver=Microsoft Access Driver (*.mdb); database lesson earlier, we used ADO. We use it again here to show you how to view and edit a
DBQ=C:\Inetpub\Wwwroot\Tutorial\guestbook.mdb;"
IF Request("ID") <> "" THEN
spreadsheet with a Web browser.
strIDNum=Request("ID")
'Creates an instance of an Active server component To prepare your Excel spreadsheet for display in an Active Server Page:
set objConn = server.createobject("ADODB.Connection")
'Opens the connection to the data store 1. Create a spreadsheet using either Excel 98 or Excel 2000 and save it as ASPTOC.xls in the
objConn.Open strProvider
'Instantiate Command object and use ActiveConnection property to C:\Inetpub\Wwwroot\ directory.
'attach connection to Command object Note: Do not include any special formatting or column labels when creating the spreadsheet.
set cm = Server.CreateObject("ADODB.Command") 2. Highlight the rows and columns on the spreadsheet that you want displayed in the Web page.
cm.ActiveConnection = objConn 3. On the Insert menu, choose Name, and select Define.
'Define SQL query
cm.CommandText = "DELETE FROM Guestbook WHERE ID = " &strIDNum
4. If there are any names listed, select them and select Delete.
cm.Execute 5. Type a name for the workbook, select Add, and select OK.
END IF
'Instantiate a Recordset object and open a recordset using To display the spreadsheet in a Web page, you must create a DSN for the spreadsheet. The process is the
'the Open method same as it was for the database lesson earlier in this module. The only difference is that you must select
Set rst = Server.CreateObject("ADODB.recordset")
rst.Open strQuery, strProvider the {Microsoft Excel Driver (*.xls)} option for the DSN.
%>
<h1>Guest Book</h1> Once you have created the spreadsheet and named the table in the spreadsheet, and also created a DSN for
<form name=viewdb.asp action=viewdb.asp method=post> the spreadsheet, you are ready to create the page that displays the contents. Paste the following code into a
<table border=1 cellspacing=3 cellpadding=3 rules=box>
<%
new file and name it ASPTOC.asp. Save it in the C:\Inetpub\Wwwroot\Tutorial directory and view the
ON ERROR RESUME NEXT page in your browser.
IF rst.EOF THEN
Response.Write "There are no entries in the database." Copy
ELSE%> <%@Language=VBScript %>
<tr> <html>
<% <head>
'Deletes rows from the database, this cannot be undone <title> Displaying An Excel Spreadsheet in an Web Page </title>
Response.Write "<td width=200><center>Delete Record</center></td>" </head>
FOR i = 1 to rst.Fields.Count -1 <body bgcolor="#FFFFFF" text="#000000" >
Response.Write "<td width=200><input name=sort value=" & rst(i).Name <h1>ASP Table of Contents</h1>
& " type=submit></td>" <%
NEXT 'Creates an instance of an Active Server Component
WHILE NOT rst.EOF %> Set oConn = Server.CreateObject("ADODB.Connection")
<tr> 'Connects to the Excel driver and the Excel spreadsheet
<% 'in the directory where the spreadsheet was saved
Response.Write "<td align=left valign=top bgcolor='#ffffff'> strConn = "Driver={Microsoft Excel Driver (*.xls)};
<a href=viewdb.asp?id=" & rst(0) & ">Delete</a></td>" DBQ=C:\Inetpub\Wwwroot\Tutorial\ASPTOC.xls;"
FOR i = 1 to rst.fields.count - 1 'Opens the connection to the data store
Response.Write "<td align=left valign=top bgcolor='#ffffff'>" & rst(i)
15 16
oConn.Open strConn pages. You can call this file from within any ASP page intended to display the rotated ads. When you test
'Selects the records from the Excel spreadsheet
calling the Include file from an ASP page (see Test the Ad Rotator), you will use some images from
strCmd = "SELECT * from `ASPTOC`"
Set oRS = Server.CreateObject("ADODB.Recordset") Microsoft.com for ad images.
'Opens the recordset
oRS.Open strCmd, oConn Open a new file in your text editor, paste in the following script, and save the file as Adrotatorlogic.inc:
'Prints the cells and rows in the table
Response.Write "<table border=1><tr><td>"
'Gets records in spreadsheet as a string and prints them in the table
Copy
<%
Response.Write oRS.GetString (, , "</tr><td>", "</td></tr><tr><td>",
NBSPACE) Function getAd()
%> Dim load
</body>
'Create an instance of the AdRotator component
</html>
Set load=Server.CreateObject("MSWC.AdRotator")

'Set the target frame, if any. This is the frame


Module Two 'where the URL will open up. If the HTML page does
'not find the target name, the URL will be opened
'in a new window.
This module explains how to develop an ASP page that delivers services useful in e-commerce. This
module includes the following lessons: load.TargetFrame = "Target = new"

'Get a random advertisement from the text file.


Rotate Ad Information. Randomly rotate ads on your Web page.
getAd = load.GetAdvertisement("adimagedata.txt")
Redirect Users from Ad Links. Redirect browsers to advertisers' sites when users click on an ad image. End Function
%>
Count Page Hits. Track the number of times users request a page.
Create an ad images data file
Rotate Ad Information
An ad images data file is created to provide information about the ads to be displayed. By placing the data
Advertising is big business on the Web. This lesson explains how to take advantage of the Ad Rotator
in one text file, when changes need to be made, you only need to change the data in one location. The ASP
component installed with ASP by describing how to use this component to rotate advertisements on your
page (with the logic in the Include file) sends data in the ad images data file to the Ad Rotator component.
Web pages. The Ad Rotator component selects an advertisement for your Web page each time the user
The component then selects an ad for display.
refreshes or loads the Web page. Two files are required to set up the Ad Rotator component: an Ad
Rotator Include file and an ad images data file. By setting up these two files, this component can be called
The data file is divided into two sections that are separated by an asterisk (*). The first section provides
by any ASP page on your site. Changes to the ad parameters are not done on all the sites containing the ad,
information common to all the ads to be displayed. The second section lists data relevant to each ad.
but to the ad images data file. This saves lots of time if the ad appears on numerous pages within your
Web site.
• The following outlines the structure of an ad images data file:
• REDIRECTION. URL, the path and name of the ASP file that redirects browsers that
This lesson explains how to:
select ad images.
• WIDTH. The width of ad images in pixels. Default is 440.
Write an Ad Rotator Include File. Creates the ad-image links on any page that calls this file.
• HEIGHT. The height of ad images in pixels. Default is 60.
• BORDER. The border thickness around ad images. Default is 1.
Create an Ad Image Data File. Specifies global ad-display data and information specific to each ad.
• *. Separates the first section from the second section.
• AdURL. Virtual path and filename of the image file containing the advertisement.
Test the Ad Rotator. Uses an ASP page that calls the Ad Rotator logic Include file and the image data file
• AdHomeURL. URL to jump to when this link is selected. To indicate there is no link, use
to display and rotate ads.
a hyphen.
• Text. Text to display if browser does not support graphics.
Write an Ad Rotator Include file • Impressions. An integer indicating the relative weight, or probability, that this ad will be
selected for display. For example, if two ads were displayed, one with an impression of 3
Include files are used to store information that will be used by more than one ASP or HTML file. By and the other with 7, then the one with 3 would have a 30 percent probability of being
creating an Ad Rotator Include file, when changes need to be made to specific information, you only need selected, while the other would have a 70 percent probability.
to change the information in one location. This lesson will guide you in creating an Ad Rotator Include
file containing a function named getAd(). This function randomly selects ads to display on your ASP
17 18

Open a new file in your text editor, paste in the following script, and save the file as Adimagedata.txt: <li type="disc">After you save Adrotatorredirect.asp, clicking on the
displayed image should cause a new window to open, displaying the
home page corresponding to the displayed logo.</li>
Copy <li type="disc">After you add the hit counter script to this page,
REDIRECT adrotatorredirect.asp under "Statistics" you should see the number of page hits since
WIDTH 250 the script was added.</li>
HEIGHT 60 </ul>
BORDER 0 <br><br><br><br><br>
* ' separates the general data from the image information <h3>Statistics</h3>
images/windows_logo.gif <% Set pageCount = Server.CreateObject("MSWC.PageCounter") %>
http://www.microsoft.com/windows <!--Increment the counter-->
Microsoft Windows <% pageCount.PageHit %>
2 <p>You are visitor number <% =pageCount.Hits %> to this Web page.</p>
images/office_logo.gif </body>
http://www.microsoft.com/office </html>
Office 2000
3
Redirect Users from Ad Links
Test the Ad Rotator
When a user clicks the ad, the browser appends a query string to the request to the server. Then, the server
To test the system, you will need an ASP page that calls the Ad Rotator Include file and the ad images directs the user's browser to the ad's URL.
data file, and then displays the ads. First, you will need test ad images stored on your site.
Open a new file in your text editor, paste in the following script, and save the file as Adrotatorredirect.asp:
Acquire and store the ad images as follows:
Copy
<%@Language=VBScript %>
1. Create a directory named Images in the tutorial folder: C:\Inetpub\Wwwroot\Tutorial\Images. <html>
2. Download the Office logo file, available at <head>
http://www.microsoft.com/office/images/office_logo.gif, from the Microsoft Office Web site, and <title>Redirection Page</title>
save it as Office_logo.gif in C:\Inetpub\Wwwroot\Tutorial\Images. </head>
<body>
3. Download the Windows logo file, available at <%
http://www.microsoft.com/windows/images/bnrwinfam.gif(, from the Microsoft Windows Web 'Set the response buffer on
site, and save it as Windows_logo.gif in C:\Inetpub\Wwwroot\Tutorial\Images. Response.Buffer = True
Dim lsURL
'Obtain the URL from the query string
Open a new file in your text editor, paste in the following script, and save the file as Displayad.asp: lsURL = Request.QueryString("URL")
'Clear the response and redirect to URL
Copy Response.Clear()
<%@ Language="VBScript" %> Response.Redirect(lsURL)
<!--Call the Include file, which in turn --> %>
<!--calls the ad images data text file--> </body>
<!--#include file="adrotatorlogic.inc"--> </html>
<html>
<head>
<title>Test Ad Display Page</title>
</head>
To check your work, use Displayad.asp. When you click on an ad, you should see a new window
<body> displaying an appropriate ad-related Web page.
<h1>Test Ad Display Page</h1>
<!--Display the ad banner--> Count Page Hits
<p><%=getAd()%></p>
<p>The space above should contain an image displaying either the
Microsoft Windows family logo or the Microsoft Office It is important to know how many hits your Web pages get. This data helps determine how changes to
family logo.</p> your Web site may affect your customers' viewing habits. More importantly, it provides useful insight as
<ul> to how customers are navigating through your site and where ads should be placed. Sites with high
<li type="disc">This indicates that Displayad.asp, Adrotatorlogic.inc, trafficking have higher advertisement prices associated with them. The data gathered from a page hit
and Adimagedata.txt are working together to correctly display the
images.</li> counter provides you with trafficking information to begin negotiating advertisement prices for your Web
<li type="disc">Repeatedly refreshing the page should result in the pages.
Windows and Office logos displaying in random order.</li>
19 20
The Page Counter component uses an internal object to record page hit-count totals for all pages on the
server. At regular intervals, this object saves all information to a text file so that no counts are lost due to
power loss or system failure. The Page Counter component uses the following three methods:

• Hits(). This displays the number of hits for a Web page. The default is the current page.
• PageHit(). This increments the hit count for the current page.
• Reset(). This resets the hit count for a page to zero. The default is the current page.

An in-use sample of this script can be seen at the bottom of the Displayad.asp script. To place a page hit
counter on a Web page, place the following script where you want the counter displayed on the page:

Copy
<% Set pageCount = Server.CreateObject("MSWC.PageCounter") %>
<% pageCount.PageHit %>
You are visitor number <% =pageCount.Hits %> to this Web site.

What is a Cookie?
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's
computer. Each time the same computer requests a page with a browser, it will send the cookie too. With
ASP, you can both create and retrieve cookie values.

21

Vous aimerez peut-être aussi