home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Chip 2000 May
/
Chip_2000-05_cd1.bin
/
zkuste
/
Perl
/
ActivePerl-5.6.0.613.msi
/
䆊䌷䈹䈙䏵-䞅䞆䞀㡆䞃䄦䠥
/
_c9838c4019125cd3c1b525163dd61501
< prev
next >
Wrap
Text File
|
2000-03-22
|
42KB
|
839 lines
<HTML>
<HEAD>
<TITLE>Active Server Pages</TITLE>
<META name="GENERATOR" charset="iso-8859-1" content="Microsoft FrontPage 4.0">
<META name="ProgId" content="FrontPage.Editor.Document">
<LINK rel="STYLESHEET" href="../Active.css" type="text/css">
</HEAD>
<BODY bgcolor="#ffffff">
<TABLE border="0" cellpadding="0" cellspacing="0" width="100%">
<TR>
<TD class="block" valign="MIDDLE" width="100%" bgcolor="#cccccc"><STRONG>
<P class="block"> Active Server Pages</P>
</STRONG></TD>
</TR>
</TABLE>
<UL>
<LI><A href="#introduction">Active Server Pages</A>
<UL>
<LI><A href="#thescriptdelimiters">The Script Delimiters</A></LI>
<LI><A href="#thescriptinghost">The Scripting Host</A></LI>
<LI><A href="#aquickexample">Creating An ASP Page</A></LI>
</UL>
<LI><A href="#asp_api">The ASP Interface</A>
<UL>
<LI><A href="#theaspobjects">The ASP Intrinsic Objects</A></LI>
<UL>
<LI><A href="#application">The Application Object</A></LI>
<LI><A href="#asperror">The ASPError Object</A></LI>
<LI><A href="#objectcontext">The ObjectContext Object</A></LI>
<LI><A href="#request">The Request Object</A></LI>
<LI><A href="#response">The Response Object</A></LI>
<LI><A href="#server">The Server Object</A></LI>
<LI><A href="#session">The Session Object</A></LI>
</UL>
</UL>
<LI><A href="#aspsamples">Active Server Pages Samples</A>
<UL>
<LI><A href="#hw">Say "Hello World!"</A></LI>
<LI><A href="#sv">Accessing HTTP Server Variables</A></LI>
<LI><A href="#qs">Reading the QueryString</A></LI>
<LI><A href="#wf">Interactive Web Forms</A></LI>
<LI><A href="#dc">Database Connections (ADO and ASP)</A></LI>
</UL>
<LI><A href="#bindata">Variants and Binary Data</A>
<UL>
<LI><A href="#readblob">To Read And Display Binary Large Objects (ADO and ASP)</A></LI>
</UL>
<LI><A href="#appa">Appendix A</A>
<UL>
<LI><A href="#appasysdsn">How To Set Up A System DSN</A>
<LI><A href="#appanosysdsn">Why Not To Use A System DSN</A>
<LI><A href="#appaoledb">How To Use The Native OLE DB Provider</A>
</UL>
<LI><A href="#appb">Appendix B</A>
<UL>
<LI><A href="#appbbook">Book Resources</A>
<LI><A href="#appbonline">Online Resources</A>
</UL>
<LI><A href="#author and copyright">AUTHOR AND COPYRIGHT</A></LI>
</UL>
<A name="introduction"></A>
<HR>
<H1>Active Server Pages (ASP)</H1>
<P>Introduced in 1996, Active Server Pages (ASP) is an easy to learn server-side technology from
Microsoft that has taken the web by storm. ASP is implemented as a set of objects with built-in
features for fast and simple access to common services provided by the web-server for the Internet.
As we will see, there are versatile reasons for using ASP as a server-side technology with
ActivePerl.<BR>
<BR>
To begin, if you in general are unfamiliar with server-side technologies, let's start at the core by
describing the need-to-know about ASP. ASP is a feature that installs with Microsoft's Internet
Information Services (IIS) web-server. No special interaction or configuration is needed afterwards,
and it should run out of the box just as easily as IIS. Fundamentally, a server-side technology such
as ASP puts no requirements on the client or browser, and, as a result, no browser-compatibility
issues will ever occur, no browser plug-ins have to be installed, and the client does not need a
local installation of ActivePerl.<BR>
<BR>
Since there are no client requirements for ASP, it needs something on the server-side that tells it
what to do with its features. A special implementation of a scripting language is therefore
installed on the server and used in order to control and program ASP; PerlScript, which installs
with ActivePerl, is suitable for the role as scripting language because it brings the power of Perl
into the environment of ASP and there merges it with the services provided by ASP. There are only
two things that you either may already know or will need to learn while using PerlScript:</P>
<UL>
<LI>The Active Server Pages Object Model
<LI>How Perl Works with Objects
</UL>
<P>On the Internet, ASP serves documents of its own filetype as opposed to familiar document types
like HTML documents. This is so that the ASP document can be processed on the server side before
returned to the client's browser. An ASP document has the file extension .asp, and it provides both
existing features derived from ASP and the ability to execute script commands within the document.
The file extension is by the webserver recognized in a special way which results in the underlying
technology executing script commands that are within the file and treat other markup such as HTML in
a standard fashion. The source code of your saved file's PerlScript script commands will by default
never be available to the user when choosing to view the document source in the browser, so any
script that you write can not be copied. The reason for this is because everything is processed on
the server side and what is returned to the browser is a standard format such as HTML.<BR>
<BR>
For a closure, it deserves to be repeated that if you are unfamiliar with object-oriented
programming in Perl, it is strongly recommended that you sometime browse the Perl documentation on
object-oriented programming to get a basic understanding of the aspects of an object and its origin.
Next up, let's look at how to embed PerlScript commands within an ASP document.<BR>
<BR>
<A name="thescriptdelimiters">
<H2>The Script Delimiters</H2>
To successfully execute the script commands within an ASP file, you must specify what scripting
language ASP should use to interpret the script commands. You can do this within the .asp document
by either setting a default scripting language in which all script commands within the
script-delimiters <% and %> will be executed by the specified scripting language. Either you
can apply that setting that within the Microsoft Management Console's IIS snap-in or you can use
what ASP recognizes as a page command, which is indicated by the special directive @. The following
example is for illustrational purposes only and it shows you how to set the default scripting
language for the ASP file to PerlScript; as a result, all commands will be treated by the PerlScript
engine; however, please note that no actual output or result is being displayed by the script, so if
you run the code shown in the example below, you won't see an output although the code is being
executed and interpreted.<BR>
<PRE>
<%@ Language=PerlScript %>
<%
for($i=0; $i<=10; $i++) {
#
# Your Perl code here
#
}
%></PRE>
<BR>
In addition to page-commands, you can set the scripting language for a defined scope by using the <CODE><SCRIPT
Language=PerlScript RUNAT=Server></CODE> and <CODE></SCRIPT></CODE> delimiters. This
results in the scripting language only executing the code within the <script> elements
regardless of what the default scripting language is set to for a language by the webserver or by an
ASP page command for the current document.<BR>
<BR>
<PRE><SCRIPT Language=PerlScript RUNAT=Server>
for($i=0; $i<=10; $i++) {
#
# Your Perl code here
#
}
</SCRIPT></PRE>
</A><A name="thescriptinghost">
<H2>The Scripting Host</H2>
When Active Server Pages acts as the scripting host for PerlScript, it is initalized as a host first
when an ASP file on the web-server is requested by the way of a URL (such as http://www.domain.com/home.asp).
The web-server locates the file, and the scripting host locates the script commands that are within
the script delimiters. The chunks of code found within the delimiters are passed on to PerlScript,
which creates a Perl interpreter that treats the code. Afterwards, it returns to the scripting host,
which waits for the next incoming call. Certain rules apply to when you write code to interact with
scripting hosts such as ASP, and let's look at one of those necessary things to know by illustrating
it as a parallel to writing a command-line Perl script. When you began programming Perl, among the
first things you probably learned was how to print text to the screen, and it is not unusual that
such a script looks as follows.<BR>
<BR>
<UL>
<CODE>print "Hello World";</CODE>
</UL>
As seen, the <CODE>"print()"</CODE>-function of Perl outputs the string "Hello
World" to what is known as the Standard Output. PerlScript, too, will send any output to what
it knows as Standard Output, and when executed within the ASP scripting host, the PerlScript engine
will use the features of the host's object-model in order to reach the standard output. Essentially,
the host provides a set of features, and you pick the scripting language in which you wish to write
your application to interact with the host. In ASP, you need to know the host because it decides
what method and what object you need to deploy of the host's in order to output a string. A
scripting language would become extremely bloated if it had to keep track of all those things In
contrast, the scripter needs to keep track of such features. :-) To send "Hello World" to
the client's browser by using ASP, you call the "<CODE>Write()</CODE>"-method of the
Response object as in the next example.<BR>
<BR>
<UL>
<CODE>$Response->Write("Hello World");</CODE>
</UL>
In essence, it is of most importance that you know the object-model of the ASP scripting host within
which you use PerlScript so that you know what object to call and how to get the best performance
out of your application.</A><A name="aquickexample"></A>
<H2>Creating An ASP Page</H2>
When looking back, the little we've seen about ASP so far is that it contains a set of objects that
you can use for your programming. It also requires a scripting language that is used to access these
objects, and for that purpose, PerlScript can be used to execute Perl commands that are mixed and
embedded within the HTML of your Active Server Pages document. Lastly, the ASP document has its own
file extension .asp which is recognized by the web server as a document parsed for first script
commands and then HTML tags.<BR>
<BR>
<UL>
1) Create a file named PerlScript.asp<BR>
2) Edit it and enter "<CODE><HTML> Hello World </HTML></CODE>"<BR>
3) Save the file where you can access it by a URL such as <I>http://localhost/</I>. On IIS, the
following path is often valid <I><device>:\inetpub\wwwroot\</I> where <device> is a
hard-disk such as C:\ or D:\<BR>
4) Run the file in your browser by entering the URL pointing to PerlScript.asp; for example, <I>http://localhost/PerlScript.asp</I>
</UL>
If it instead of finding the file reports an error such as "File Not Found," you need to
open Windows Explorer and reassure yourself of that the file is saved with the .asp file-extension
and in the correct physical location for being accessible by the browser. If the browser finds the
file and "Hello World" is outputted, you can place a few script commands in the file and
rest assured that ASP will execute everything as for which it was built. Edit the file so that is
looks as follows.
<UL>
<CODE><%@Language=PerlScript%><BR>
<HTML><BR>
<TITLE> PerlScript Test </TITLE><BR>
<%<BR>
for($i=0; $i<=10; $i+=2) {
<UL>
$Response->Write("<FONT SIZE=$i COLOR=#000000>");<BR>
$Response->Write("Hello World! </FONT> <BR>");
</UL>
}<BR>
%><BR>
</HTML><BR>
</CODE>
</UL>
The script shown is used only to output HTML and text. Essentially, the Response object's "<CODE>Write()</CODE>"-method
sends the HTML and variable value of <CODE>$i</CODE> to the browser. However, <CODE>$i</CODE> is a
part of the HTML Font element, so the result is that the font size is increased by 2 for each time
"Hello World" is sent to the client's browser. You could also write the script this way:<BR>
<BR>
<PRE><HTML>
<TITLE> PerlScript Example </TITLE>
<script language=perlscript runat=server>
for($i=0; $i<=10; $i+=2) {</PRE>
<UL>
<PRE>$Response->Write("<FONT SIZE=$i COLOR=#000000>");
$Response->Write("Hello World! </FONT> <BR>");</PRE>
</UL>
<PRE>}
</script>
</HTML>
</PRE>
A closure to this example, there is a shorthand for writing <CODE>$Response->Write($variable)</CODE>,
and it is not available when already within script delimiters; however, to easily mix variables with
HTML you can automatically call the mentioned method by <CODE><%=$variable%></CODE> where the
equal-sign automatically translates into <CODE>$Response->Write()</CODE>. For example:<BR>
<BR>
<PRE><HTML>
<TITLE> PerlScript Example </TITLE>
<% @Language=PerlScript %>
<% for($i=0; $i<=10; $i+=2) {
%>
<FONT SIZE=<%=$i%> COLOR=#000000>
Hello World!
</FONT>
<BR>
<% } >%
</HTML>
</PRE>
<P><A name="asp_api"></A>
<HR>
<H1>The ASP Programming Interface</H1>
<P>Providing an interface to common tasks for a web programmer, ASP simplifies web-programming by
making the simple tasks even easier. The features of ASP are implemented and exposed as objects,
and, in addition, a scripting language is enabled to not only use those features of the ASP host,
the language can certainly use its own features, too.<BR>
<BR>
<A name="theaspobjects"></A>
<H2>The ASP Intrinsic Objects</H2>
In object-oriented programming as we know it, the programmer is required to create an instance of
the object she wishes to use. The ASP objects, on the other hand, are "intrinsic", which
means that they are already instantiated and available to your scripting language engine. No
pre-work at all is associated with these objects and you can access them at any time. Now, each
object encapsulate a set of very specific services and provides shorthand access to common tasks for
the web developer such as reading the data submitted from a web-form, reading and writing cookies,
redirecting the client's browser, and also extended functionality such as the ability to identify
each user as a unique client and associate private server-side variables with her. Before diving
into the syntax, these are the objects as of ASP 3.0:<BR>
<BR>
<A name="#application"></A>
<H3>Application</H3>
The Application Object an object that is a place-holder for global variables stored on the server
side. A global variable in this sense is a variable that is global to what is known as the IIS
application. The IIS application defines the physical space of a webserver such as the range on the
hard disk for the URL http://members.someperlsite.com/. A webserver can have more than one IIS
application, but there is only one ASP application object per IIS application. Confused? Hang on a
minute. The Application object, like the Session object, has what is called a collection. The
collection contains variables created by you. Whenever you want to create a variable, the variable
must be put on the contents collection, and the following is one way of doing it.
<UL>
<CODE># Set an application variable<BR>
#<BR>
$Application->Contents->SetProperty('Item', 'myName', 'Tobias');</CODE>
</UL>
The contents collection can store scalar variables, arrays, or objects that somehow are associated
with all users; for example, a visitor counter or a connection-string used to connect to a database
through the Microsoft universal ADO application-programming interface. The variable can be accessed
easily, too.
<UL>
<CODE># Access an application variable<BR>
#<BR>
$Application->Contents->Item('myName');</CODE>
</UL>
<BR>
<BR>
However, when you're comfortable within the Microsoft Management Console and can set and define your
own IIS applications, you will notice that there is only one ASP Application object per IIS
Applcation and the variables placed in the Contents colleciton are only available within that IIS
application and no other. If it's a bit confusing, it's guaranteed to have cleared out after playing
around with this for a while. It's the most abstract part about ASP if you are not used to defining
IIS applications. On the downside, Personal Web Server does not enable you to define more than one
IIS application.<A name="#asperror"></A>
<H3>ASPError</H3>
The ASPError object is the only new object that shipped with ASP 3.0. It contains detailed
information about an error which occured during the processing of an ASP page. Unless told otherwise
by the administrator, ASP 3.0 redirects the client to a page named 500-100.asp when an error occurs,
and in that page, the ASPError object is deployed to show detailed descriptions about the error. You
can with PerlScript easily also extend the use the 500-100.asp page to perform custom tasks such as
emailing you a formatted page of the contents of the ASPError object on an arror or writing it to a
special log. Some of its useful properties include: SourceCode for returning the source code of the
part of a script that generated the error, Category for tracking down the categoru of the error to
ASP, scripting language, or an object, File for the name of the file processed when error was
generated, and Description to return a description of the error; however, please note that ASPError
objects are only returned by the Server object's GetLastError method.
<UL>
<CODE><BR>
# Return the ASPError object<BR>
#<BR>
$ASPError = $Server->GetLastError();<BR>
<BR>
# Output the error's description<BR>
#<BR>
$Response->Write( $ASPError->{Description} );</CODE>
</UL>
<BR>
<BR>
<A name="#objectcontext">
<H3>ObjectContext</H3>
The ObjectContext object is used for a page that is run as a transaction. This object enables you to
commit or abort a transaction, which is an important functionality for deployed business
applications. Its only methods are SetAbort() and SetComplete(). They are used to commit or abort
the transaction. Before this can be used, your page must include a <CODE>@TRANSACTION</CODE> page
command in the page, whereas you are enabled only to define @ once per file; however, you can use
multiple directives within the @ such as <CODE><%@directiveA=something directiveB=somethingelse%></CODE>.
If you use PerlScript a lot, you are better off setting it as the default language in the Microsoft
Management Console. Setting the default language in the MMC is unfortunately not an option for
Personal Web Server. PWS is good for practicing a scripting language and ASP, but it is not good for
tailormaking your webservice in terms of IIS applications and other tasks that are administrative.
For example, it does not have the Microsoft Management Console. What PWS mainly does is to allow you
to publish and develop Active Server Pages within reson while it hides the administrative tasks.<BR>
<BR>
</A><A name="#request">
<H3>Request</H3>
For good reason, the Request object is a widely used object. It contains a collection of information
such as form-data or cookies gathered from the client. With this object you can gather the contents
submitted from any type of web-form, read server variables or the contents of a digital client
certificate. You can also read binary data such as an uploaded file by first determining the number
of bytes sent with the <CODE>TotalBytes</CODE>-property and then read it with the <CODE>BinaryRead($bytes_to_read)</CODE>
method.
<UL>
<CODE><BR>
# Get the number of total bytes in the request<BR>
#<BR>
$bytes_to_read = $Request->{TotalBytes};<BR>
<BR>
# Read and return a variant array of type VT_U1<BR>
#<BR>
$read_bytes=$Request->BinaryRead( $bytes_to_read );</CODE>
</UL>
In the Request object, collections that you can read includes <CODE>ClientCertificate</CODE> for
digital certificated, <CODE>Cookies</CODE> for cookies sent with the HTTP request, <CODE>Form</CODE>
for data posted by a web form using the POST method, <CODE>QueryString</CODE> for data passed with
the QueryString or GET method from a web form, and <CODE>ServerVariables</CODE> for HTTP environment
variables such as the server software or the users browser.
<UL>
<CODE># Let's see what's in the ALL_HTTP variable<BR>
#<BR>
$Response->Write( $Request->ServerVariables('ALL_HTTP')->Item() );</CODE>
</UL>
</A><A name="#response">
<H3>Response</H3>
The Response Object is responsible for sending data from the client to the server. For example, you
can print strings such as HTML or scalar variables, and you can also print binary data such as
images, set cookies, control cache, character sets, and content-types, plus send the client status
headers, append datato the log, set PICS labels, and see if the client is still connected. A cookie
can contain the attributed Domain, Expires, HasKeys, Path, and Secure, and you first declare a
cookie before setting these attributes.
<UL>
<CODE># Ask the client's browser if it wants a cookie<BR>
#<BR>
$Response->Cookies->SetProperty(
<UL>
<UL>
<UL>
<UL>
<UL>
<UL>
'Item',<BR>
'someCookie',<BR>
'Hi! This is a cookie!'<BR>
);
</UL>
</UL>
</UL>
</UL>
</UL>
</UL>
<BR>
<BR>
# ==================================================<BR>
# Let's set some attributes of the cookie!<BR>
# ==================================================<BR>
<BR>
# This is the domain that can read the cookie; to specify it further,<BR>
# use the Path-attribute to define a more complete URL<BR>
#<BR>
$Response->Cookies('someCookie')->{Domain} = 'somesite.com';<BR>
<BR>
# The expiration date for the cookie<BR>
#<BR>
$Response->Cookies('someCookie')->{Expires} = 'January 1, 1999';<BR>
<BR>
# Not a secure cookie; 1 defines it as secure<BR>
#<BR>
$Response->Cookies('someCookie')->{Secure} = 0;</CODE>
</UL>
<BR>
<BR>
</A><A name="#server">
<H3>Server</H3>
The Server object provides certain server-side functions. Its only property is <CODE>Timeout</CODE>
which defines for how many seconds a script should try executing before returning an error. This
setting can also be set in the Microsoft Management Console. In terms of methods, you can create
instances of COM objects in your page, encoding HTML and URL's, mapping the physical path to a file
by providing its URL, execute other .asp files, and seamlessly transfer the client to a new page
while maintaining the state of the current ASP objects, which means that any form data that was
gathered can be transferred between pages.
<UL>
<CODE># Open the file in the virtual path /scripts/forum.asp/<BR>
#<BR>
open( FILE, $Server->MapPath('/scripts/forum.asp') );</CODE>
</UL>
You can use <CODE>CreateObject('ProgID')</CODE> to return a valid COM object to the Active Server
Page. For example, to instantiate an ADO object, you'd do the following:
<UL>
<CODE># Create an ADO Connection object<BR>
#<BR>
$ADOConnObj = $Server->CreateObject('ADODB.Connection');</CODE>
</UL>
When using strings, <CODE>HTMLEncode($string)</CODE> encodes charaters such as greater than and less
than into its valid character represenation within an HTML page. This prevents, for example, users
to post HTML to a chatroom or messageboard. The <CODE>URLEncode($string)</CODE>-method encodes a
string for valid represenation as a URL. New in IIS 5, you can <CODE>Execute('/scripts/page.asp')</CODE>
ASP scripts in other files, and to transfer the user without losing the state of the Request
object's existing variables such as the contents of the Form-collection you can use the
Transfer-method.
<UL>
<CODE># Transfer the user to a different page<BR>
#<BR>
$Server->Transfer('/step2.asp');</CODE>
</UL>
Worth noting about the transfer method is that it takes place on the server side. There is never a
request sent to the users browser telling the browser to redirect, thus a roundtrip is spared.<BR>
<BR>
</A><A name="#session"></A>
<H3>Session</H3>
The Session object enables you to associate variables with each unique client and keep the variables
stored until she leaves the domain. It has the same abilities as the Application object, but with
the important difference that these variables will only be available to the single user and the
script engine. Ideal for applications such as shopping carts. The syntax is the same as the
Application object in terms of adding entities to the Contents collection. In addition, you can set
the <CODE>Timeout</CODE>-property to the number of minutes that you wish the Session to last before
it is ended or you can deliberately end the Session by calling the <CODE>Abandon</CODE>-method and
then redirect to a new page. The redirection is very important! Other properties that you can use is
<CODE>CodePage</CODE> which is used for Symbol Mapping, <CODE>LCID</CODE> for the locale identifier,
and <CODE>SessionID</CODE> which uniquely identifies the client.<BR>
<BR>
For both the Session and Application object, the Contents collections contain a <CODE>Remove()</CODE>
and <CODE>RemoveAll()</CODE> method. <CODE>Remove()</CODE> takes either an index or a keyname for
the variable in the Collection to remove, and <CODE>RemoveAll()</CODE> removes all variables stored
in the collection. In example, consider that you have stores a property called "myName" in
the Session s Contents collection, you would remove it as follows:
<UL>
<CODE>$Session->Contents->Remove('myName');</CODE>
</UL>
Earlier than IIS 5, <CODE>Remove()</CODE> and <CODE>RemoveAll()</CODE> are not available, so you
will have to use the Perl built-in function <CODE>undef()</CODE>,.
<P><A name="aspsamples">
<HR>
<H1>The Active Server Pages Samples</H1>
The following examples are taken from the \eg\aspsamples\ directory, which will be installed on your
machine if you installed the example files with ActivePerl. In addition to these examples, there are
useful and advanced examples in the \eg\aspsamples\ directory.<BR>
</A><A name="hw">
<H2>Say "Hello World!"</H2>
<B>File Location: [\eg\aspsamples\hello.asp]</B><BR>
<BR>
In this example, a for-loop is used to print a series of "Hello World!" strings of
increasing font-size. Notice the <CODE><%=$i%></CODE> call, which is shorthand for writing
$Response->write($i).<BR>
<UL>
<CODE><BR>
<%<BR>
for ($i = 3; $i < 8; $i++) {<BR>
%><BR>
<font size=<%= $i %>><BR>
"Hello World!"<BR>
</font><BR>
<BR><BR>
<%<BR>
}<BR>
%></CODE>
</UL>
<BR>
<BR>
</A><A name="sv">
<H2>Accessing HTTP Server Variables</H2>
<B>File Location: [\eg\aspsamples\srvvar.asp]</B><BR>
<BR>
The HyperText Transfer Protocol (HTTP) variables that are sent with each request can be retrieved
from the Request object. You need to specify that you want the server variables, and then call a
method named "Item" in order to return the value.
<UL>
<CODE><%= $Request->ServerVariables('SERVER_SOFTWARE')->Item() %></CODE>
</UL>
<BR>
</A><A name="qs">
<H2>Reading the QueryString</H2>
<B>File Location: [\eg\aspsamples\qstring.asp]</B><BR>
<BR>
The QueryString can be either manufactured by handcoding it, or it is automatically generated for
form-fields if you use a HTML form that uses the GET method for submitting its data. The following
is one way you can use it.
<UL>
<CODE><BR>
<A HREF="<%=$Request->ServerVariables('PATH_INFO')->item()%>?Size=Medium&Color=Yellow"><BR>
This link will demonstrate the Request object's QueryString collection.<BR>
</A><BR>
<BR>
The current value of Size is<BR>
<%= $Request->QueryString('Size')->item() %><BR>
<BR>
<BR><BR>
<BR>
The current value of Color is<BR>
<%= $Request->QueryString('Color')->item() %></CODE>
</UL>
<BR>
</A><A name="wf">
<H2>Interactive Web Forms</H2>
<B>[\eg\aspsamples\wform.asp]</B><BR>
<BR>
In this example, the POST method is used to submit a form. The Request object gathers data by
calling the Form-element by its name in <CODE>$Request->Form('name')->Item()</CODE> instead of
in <CODE>$Request->QueryString('name')->Item()</CODE> as it is passed when the method is GET.<BR>
<BR>
Once fetched, the "<CODE>$Server->HTMLEncode()</CODE>"-method is called to correctly
translate HTML tags into proper encoding so that no HTML tags can be submitted.<BR>
<PRE>
<%
my($name) = $Request->Form('Yourname')->Item();
$name = $Server->HTMLEncode($name);
%>
<%
if($name eq 'Enter Your name here') {
$Response->Write("Please type your name in the box below and then press the button");
}
else {
$Response->Write("Hello $name");
}
%>
<CENTER>
<FORM ACTION="wform.asp" METHOD="POST">
<INPUT TYPE="Textfield" NAME="Yourname" MAXLENGTH="30" VALUE="Enter Your Name Here">
<INPUT TYPE="SUBMIT" VALUE="Click Me">
</FORM>
</CENTER></PRE>
<BR>
<BR>
</A><A name="dc">
<H2>Database Connections (ADO and ASP)</H2>
<B>[\eg\aspsamples\ado1.asp]</B><BR>
<BR>
This database example requires the ActiveX Data Objects from the Microsoft Data Access Components,
available at </A><A href="http://www.microsoft.com/data/">http://www.microsoft.com/data/</A>.<BR>
<BR>
<PRE>
<%
# Create an instance of the ADO Connection object
#
$Conn = $Server->CreateObject("ADODB.Connection");
# Open a system DSN
#
$Conn->Open( "ADOSamples" );
# Execute an SQL Query
#
$RS = $Conn->Execute( "SELECT * FROM Orders" );
# Read a property to get the number of columns
# present in the Recordset returned from the
# query.
#
$count = $RS->Fields->{Count};
# Print out the names of each column
#
for ( $i = 0; $i < $count; $i++ ) {
$Response->Write( $RS->Fields($i)->Name );
$Response->Write("<BR>");
};
# Loop the Recordset until there are no more records
#
while ( ! $RS->{EOF} ) {
for ( $i = 0; $i < $count; $i++ ) {
$Response->Write(" ");
$Response->Write($RS->Fields($i)->{Value});
$Response->Write("<BR>");
};
# Move to the next record
#
$RS->MoveNext();
};
# Close the Recordset
#
$RS->Close();
$Conn->Close();
%></PRE>
<BR>
As an important note, the ActiveX Data Objects is an easy-to-use and easy-to-learn set of objects
that provides universal data access. Regardless of what language you use ADO from within, the
application-level programming interface of ADO remains the same.<BR>
<BR>
Moreover, not only can you access relational databases such as MS Access, SQL Server, or Oracle with
these components, you can access non-relational data such as video, filesystems, and email systems
-- all from one single interface. It is the post-ODBC industry standard for accessing data stores,
and a fast and powerful way to get your databases out on the Internet.
<P><A name="bindata"></A>
<HR>
<H1>Variants and Binary Data</H1>
<P>At times, you will be working with binary data that is passed to PerlScript from a COM object or
passed from PerlScript to a COM object. In Windows Script, the data comes in a data type called a
Variant. The Variant resembles of Perl's scalar variables because it was designed for holding most
types of data. And most of the time, Perl is able to determine what type of Variant that is being
returned to it from a COM object; however, with binary data, it sometimes becomes necessary to
define what the variant is exactly for a type, so the "<CODE>Win32::OLE::Variant</CODE>"-module
provides functionality for this conversion and much more. For example, if you have a GIF image
stored in the variable <CODE>$image</CODE>, and you want to output it to the screen by using the
Response object's "<CODE>BinaryWrite()</CODE>"-method, you must convert it to a VT_UI1
variant before it is passed to the "<CODE>BinaryWrite()</CODE>"-method simply because a
VT_UI1 variant is expected by the method.<BR>
<PRE>use Win32::OLE::Variant;
# Tell the browser a GIF image is on its way
#
$Response->{ContentType} = "image/GIF";
# Send the GIF as a VT_UI1 Variant
#
$Response->BinaryWrite(Win32::OLE->Variant(VT_UI1, $image));
</PRE>
An issue of needing to convert to the accurate type of Variant occurs most of the time when working
with binary data; two concrete examples are binary large objects (BLOBs) returned from SQL Server
and binary data being output through the ASP Response object's "<CODE>BinaryWrite()</CODE>"-method.
The "<CODE>BinaryWrite()</CODE>"-method expects a Variant of the type VT_UI1, and that is
the same type which is returned when reading a BLOB from SQL Server. However, as the variant is
returned to PerlScript, it converts it into the type of scalar that most resembles the variant, and
although that is an accurate conversion for use in Perl, you will need to convert data if it's used
in a VT_UI1 context.
<P><A name="readblob"></A>
<HR>
<H1>To Read And Display Binary Large Objects (ADO and ASP)</H1>
<P>The following example will demonstrate how ADO can be used to read a Binary Large Object from SQL
Server, and how ASP is used to output the BLOB as an image.
<PRE><%@Language=PerlScript%> <%
use Win32::OLE::Variant;
# One note, 40 as bytes to read per GetChunk()-call is not
# a good number to choose for a real application. I emphasize
# _not_. Instead, whatever you choose depends much on your
# system and the power of it; however, 4000 is a much more
# realistic real-world number compared to 32.
#
my($blob_size, $read_size, $bytes_to_read) = (0, 0, 32);
# Let's create the Connection object used to establish the connection
#
$conn = $Server->CreateObject('ADODB.Connection');
# Open a connection using the SQL Server OLE DB Provider
#
$conn->Open(<<EOF);
Provider=SQLOLEDB;
Persist Security Info=False;
User ID=sa;Initial Catalog=pubs
EOF
# Execute the query which returns the BLOB from our database
#
$rs = $conn->Execute("SELECT logo FROM pub_info WHERE pub_id='0736'");
# Get the size of the BLOB
#
$blob_size = $rs->FieldS('logo')->{ActualSize};
# And here's the routine for reading in the blob. Alternatively you can
# make a control statement that says if the $blob_size is less than
# 4096, it should just swallow it in one chunk, but the routine below
# is good to have handy
#
while($read_size < $blob_size) {</PRE>
<UL>
<PRE>$buffer .= $rs->Fields('logo')->GetChunk($bytes_to_read);
$read_size += $bytes_to_read;
if($read_size+$bytes_to_read > $ blob_size) {</PRE>
<UL>
<PRE>$bytes_to_read = $blob_size - $read_size;</PRE>
</UL>
<PRE>}</PRE>
</UL>
<PRE>}
# Make a VT_UI1 variant of the retrieved Chunks
#
$image = new Win32::OLE::Variant(VT_UI1, $buffer);
# Tell the browser that the content coming is an image of the type GIF
#
$Response->{ContentType}="image/gif";
# Do a binarywrite of the VT_UI1 variant image
#
$Response->BinaryWrite($image);
%></PRE>
<P><A name="appa">
<HR>
<H1>Appendix A</H1>
</A><A name="appasysdsn">
<H2>How To Set Up A System DSN</H2>
<P>The System Data Source Name is information stored in the Windows-registry. The information is
used by your application to connect to a database. To create a SystemDSN you must have a database
ready to be used by your application and know the path to the database.When the information above is
gathered you open "32 Bit ODBC" from the control-panel andclick on the "SystemDSN"-tab.
Choose to "Add" a new SystemDSN and select the driver foryour database. Enter the
"Data Source Name" that you will call on the database by fromyour application, then click
on the "Select"-button and browse to your database-file.Okay everything, then close the
program. You'll now be able to call on your databaseby the Data Source Name you entered for it as
follows:
<UL>
<CODE>$Conn = $Server->CreateObject("ADODB.Connection");<BR>
$Conn->Open("Name");</CODE>
</UL>
</A><A name="appanosysdsn"></A>
<H2>Why Not To Use A System DSN</H2>
<P>With the ActiveX Data Objects (ADO), the layer that connectes to a database is called the OLE DB
layer. It is the very closest to the physical database, and directly connecting to OLE DB is ADO.
Most databases will have what is called an OLE DB Provider, and if you have worked with ODBC, the
OLE DB provider is OLE DB's equivalent of the ODBC driver. In ADO, ideally you should connect via
ADO directly to OLE DB and from OLE DB directly to the physical database or other data store. A
System DSN is for ODBC data sources and it causes OLE DB to wrap an ODBC driver within itself, which
adds an overhead and reduces performance.<A name="appaoledb"></A>
<H2>How To Use The Native OLE DB Provider</H2>
<P>There are a number of things you can do to get the native provider set up. When you have it set
up, you simply replace the name of the system DSN with the string that has been produced in order to
connect to the data store using the native OLE DB provider. First, try to create an Universal Data
Link file by doing the following:
<UL>
1) Create a file named connectionstring.udl<BR>
2) Right-click on it<BR>
3) Choose Properties<BR>
4) Choose the OLE DB Provider to use<BR>
5) Define what source to connect to and possibly a username and password<BR>
6) Click "Test Connection"<BR>
7) Open the file in "Notepad"<BR>
8) Highlight the connectionstring and press CTRL+C to copy it into memory<BR>
9) Paste it into your ADO application by pressing CTRL+V
</UL>
If you are not lucky enough to have .udl, locate a friend who has it or dig around for the
connectionstrings. It is more than feasible that there are texts on it available on the Internet,
too. To give an example, this is what a typical connectionstring looks like for an Access database:
<UL>
<CODE>Provider=Microsoft.Jet.OLEDB.4.0;<BR>
User ID=Somebody;<BR>
Data Source=c:\\access.mdb;<BR>
Persist Security Info=False</CODE>
</UL>
And here's one for SQL Server:
<UL>
<CODE>Provider=SQLOLEDB;<BR>
Persist Security Info=False;<BR>
User ID=sa;<BR>
Initial Catalog=Northwind</CODE>
</UL>
<P><A name="appb">
<HR>
<H1>Appendix B</H1>
</A><A name="appbbook">
<H2>Books Resources</H2>
<P>
<UL>
<CODE>ActivePerl with ASP and ADO:<BR>
by Tobias Martinsson<BR>
ISBN 0471383147<BR>
URL: http://www.wiley.com/compbooks/</CODE>
</UL>
</A><A name="appbonline"></A>
<H2>Online Resources</H2>
<P>
<UL>
<LI><A href="http://www.microsoft.com/data/">Microsoft Data Access Components</A>; MDAC includes
ADO, OLE DB, and every component needed for getting your databases out on the Internet.
<LI>Windows 95 users will have to download the NT Option Pack from <A href="http://www.microsoft.com/">Microsoft</A>
and install Personal Web Server which ships with it. Win 98 already has it on its CD.
<LI>The <A href="http://www.asplists.com/asplists/aspperlscript.asp">ASP PerlScript</A>
mailinglist is pretty much where the most questions and answers on PerlScript and ASP circulate.
<LI><A href="http://www.deja.com/~perlscript/">PerlScript Community</A> is a Deja community for
users who want to find users that PerlScript.
<LI><A href="http://www.fastnetltd.ndirect.co.uk/Perl/perl-win32-asp.html">The Perl-Win32-ASP FAQ.</A>
Maintained by Matthew Sergeant.</LI>
</UL>
<P>
<HR>
<H1><A name="author and copyright">AUTHOR AND COPYRIGHT</A></H1>
<P>Copyright (c) 2000 Tobias Martinsson. All Rights Reserved.</P>
<P>When included as part of the Standard Version of Perl, or as part of its complete documentation
whether printed or otherwise, this work may be distributed only under the terms of Perl's Artistic
License. Any distribution of this file or derivatives thereof <EM>outside</EM> of that package
require that special arrangements be made with copyright holder.</P>
<P>Irrespective of its distribution, all code examples in this file are hereby placed into the
public domain. You are permitted and encouraged to use this code in your own programs for fun or for
profit as you see fit. A simple comment in the code giving credit would be courteous but is not
required.</P>
<P>Active Server Pages is copyright (c) Microsoft Corporation. All rights reserved.</P>
<TABLE border="0" cellpadding="0" cellspacing="0" width="100%">
<TR>
<TD class="block" valign="MIDDLE" width="100%" bgcolor="#cccccc"><STRONG>
<P class="block"> Active Server Pages</P>
</STRONG></TD>
</TR>
</TABLE>
</BODY>
</HTML>