ActivePerl Documentation
|
Active Server Pages (ASP)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.
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. Creating An ASP PageWhen 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.
2) Edit it and enter " <HTML> Hello World </HTML>"3) Save the file where you can access it by a URL such as http://localhost/. On IIS, the following path is often valid <device>:\inetpub\wwwroot\ where <device> is a hard-disk such as C:\ or D:\ 4) Run the file in your browser by entering the URL pointing to PerlScript.asp; for example, http://localhost/PerlScript.asp <%@Language=PerlScript%>
Write()"-method
sends the HTML and variable value of $i to the browser. However, $i 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:<HTML>
<TITLE> PerlScript Example </TITLE>
<script language=perlscript runat=server>
for($i=0; $i<=10; $i+=2) {
$Response->Write("<FONT SIZE=$i COLOR=#000000>");
$Response->Write("Hello World! </FONT> <BR>");
} </script> </HTML>A closure to this example, there is a shorthand for writing $Response->Write($variable),
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 <%=$variable%> where the
equal-sign automatically translates into $Response->Write(). For example:<HTML>
<TITLE> PerlScript Example </TITLE>
<% @Language=PerlScript %>
<% for($i=0; $i<=10; $i+=2) {
%>
<FONT SIZE=<%=$i%> COLOR=#000000>
Hello World!
</FONT>
<BR>
<% } >%
</HTML>
The ASP Programming InterfaceProviding 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. The ASP Intrinsic ObjectsIn 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:ApplicationThe 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.# Set an application variable
# Access an application variable
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. ASPErrorThe 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.
ObjectContextThe 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@TRANSACTION 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 <%@directiveA=something directiveB=somethingelse%>.
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.RequestFor 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 theTotalBytes-property and then read it with the BinaryRead($bytes_to_read)
method.
ClientCertificate for
digital certificated, Cookies for cookies sent with the HTTP request, Form
for data posted by a web form using the POST method, QueryString for data passed with
the QueryString or GET method from a web form, and ServerVariables for HTTP environment
variables such as the server software or the users browser.
# Let's see what's in the ALL_HTTP variable
ResponseThe 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.# Ask the client's browser if it wants a cookie
ServerThe Server object provides certain server-side functions. Its only property isTimeout
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.
# Open the file in the virtual path /scripts/forum.asp/
CreateObject('ProgID') to return a valid COM object to the Active Server
Page. For example, to instantiate an ADO object, you'd do the following:
# Create an ADO Connection object
HTMLEncode($string) 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 URLEncode($string)-method encodes a
string for valid represenation as a URL. New in IIS 5, you can Execute('/scripts/page.asp')
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.
# Transfer the user to a different page
SessionThe 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 theTimeout-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 Abandon-method and
then redirect to a new page. The redirection is very important! Other properties that you can use is
CodePage which is used for Symbol Mapping, LCID for the locale identifier,
and SessionID which uniquely identifies the client.For both the Session and Application object, the Contents collections contain a Remove()
and RemoveAll() method. Remove() takes either an index or a keyname for
the variable in the Collection to remove, and RemoveAll() 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:
$Session->Contents->Remove('myName');
Remove() and RemoveAll() are not available, so you
will have to use the Perl built-in function undef(),.
<%
# 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();
%>
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. 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. Variants and Binary DataAt 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 " 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));
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 "BinaryWrite()"-method.
The "BinaryWrite()"-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.
To Read And Display Binary Large Objects (ADO and ASP)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. <%@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) {
$buffer .= $rs->Fields('logo')->GetChunk($bytes_to_read);
$read_size += $bytes_to_read;
if($read_size+$bytes_to_read > $ blob_size) {
$bytes_to_read = $blob_size - $read_size; } }
# 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);
%>
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:
Why Not To Use A System DSNWith 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. How To Use The Native OLE DB ProviderThere 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:
2) Right-click on it 3) Choose Properties 4) Choose the OLE DB Provider to use 5) Define what source to connect to and possibly a username and password 6) Click "Test Connection" 7) Open the file in "Notepad" 8) Highlight the connectionstring and press CTRL+C to copy it into memory 9) Paste it into your ADO application by pressing CTRL+V Provider=Microsoft.Jet.OLEDB.4.0;
Provider=SQLOLEDB;
Online Resources
AUTHOR AND COPYRIGHTCopyright (c) 2000 Tobias Martinsson. All Rights Reserved. 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 outside of that package require that special arrangements be made with copyright holder. 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. Active Server Pages is copyright (c) Microsoft Corporation. All rights reserved.
|