Mirror

Delphi and ASP (Views: 589)

Problem/Question/Abstract:

Getting Started with Active Server Pages

Answer:

In brief, Active Server Pages (ASP) are text files that contain standard HTML commands that are processed by a Web browser, and scripting commands that are executed on a Web server. These scripting commands can be written in VBScript, JScript (the Internet Explorer equivalent of Netscape's JavaScript), or any other language for which a valid scripting engine is installed, e.g. Perl and Python. Using these scripting commands, you can introduce basic programming operations into your HTML, such as performing conditional execution and expression evaluation, as well as invoking the features of COM servers installed on the server. In this article, we'll take a look at using these scripting commands to achieve the results you want.

When an HTTP request for an ASP document is received by an ASP-enabled Web server, such as Microsoft's Internet Information Server (IIS), the server processes the scripting commands within that file. The output generated by the scripting language is combined with the standard HTML in the ASP to produce the HTTP response returned to the Web browser. In other words, the server doesn't return the ASP document to the browser. Instead, it returns static HTML, plus the output from the processing of the scripting commands. In most cases, the returned data is pure HTML, although it can potentially contain any valid MIME (Multi-Purpose Internet Mail Extensions) content type.

There are numerous benefits to using ASP:

The user can't readily access your code. Unlike with browser-side JavaScript or VBScript, in which the scripting instructions are delivered intact to the browser, ASP commands aren't sent to the Web browser.
ActiveX objects accessed using ASP - when Microsoft Transaction Server (MTS) isn't being used - are loaded into the process space of the server, which reduces overhead when compared with CGI (common gateway interface) server extensions. An ASP object can also be processed in a separate process space, reducing the likelihood that a crashing ASP object will bring down your Web server.
ActiveX objects used by IIS can be installed into MTS, providing activation on demand, transactions, resource sharing, crash protection, and additional security.
ASP code is often easier to write than other CGI programs, in that they don't require compilation or the installation of a secondary processor (although when you create a COM server designed to be accessed by an ASP, the COM server requires compilation).

As noted already, ASP can only be used with an ASP-enabled Web server. Initially, ASP support was introduced in Microsoft's Internet Information Server (IIS). However, any Windows-based server can potentially support ASP. This is crucial in that ASP servers use COM technology, which is supported almost exclusively by the Windows operating system. (Although some non-Windows implementations of COM exist, these are quite rare.)

Before continuing, it's worth mentioning that JSP (Java Server Pages) is a technology similar to ASP. The primary difference is that JSP-enabled servers aren't limited to Windows-based servers. Any Web server that runs on a Java 2-supporting operating system (JDK 1.2) can be a potential JSP-enabled server.

Using ASP Commands

In addition to basic HTML, ASP contains four types of commands: primary scripting commands, output directives, processing directives, and include statements.

With the exception of include statements, commands contained within an ASP document are enclosed within <% %> delimiters. As mentioned earlier, these commands can consist of VBScript, JScript, or any other scripting language for which a valid scripting engine has been installed on the Web server. The language used for most of the remainder of this article is VBScript.

Primary scripting commands contain the basic syntactic elements of the scripting language being used. For example, primary scripting commands may include control structures, expression evaluation, function invocation, variable declarations, and so on. HTML commands can be interspersed between primary scripting commands to control the HTML content that is returned to the Web browser. For example, consider the following segment:

<%
If Time >= #12:00:00 AM# And Time < #12:00:00 PM# Then
%>
Good Morning!
<% Else %>
Hello!
<% End If %>

Here, the plain HTML text Good Morning! appears between the <%If%> and the <%Else%> commands. Alternatively, the Write method of the built-in Response object can be used to write HTML from within a primary scripting command. The Response object is one of six available built-in objects you can use in your ASP. Built-in objects are discussed in greater detail later in this section. The following is an example of ASP commands that make use of the Response.Write method:

<%
If Time >= #12:00:00 AM# And Time < #12:00:00 PM# Then
Response.Write "Good Morning!"
Else
Response.Write "Hello!"
End If
%>

In this example, the entire code segment is a primary scripting command. The result is that one of two strings is written to the HTML file being created by the Web server based on the evaluation of the <%If%> statement. In other words, the result of this segment will either be Good Morning! or Hello!. None of the other actual text of the primary scripting command is delivered to the browser.

Output directives. Output directives are a special case of primary scripting commands. As with the Response.Write technique, an output directive inserts text into the HTML stream that will be returned to the Web browser. Output directives use the following syntax:

<%= expression %>

The value of expression can be a variable, constant, formula, property, method, or function. For example, the following line inserts a string indicating the current time, based on the internal clock on the Web server (because the Web server can be at any location in the world, this isn't necessarily the same time as in the time zone of the Web browser!):

The current time on this server is: <%=Now%>

Processing directives. Processing directives provide instructions to the ASP processing engine and typically appear at the beginning of an ASP page. Processing directives use the following syntax:

<% @ keyword=value%>

The keyword must be a reserved word recognized by the ASP engine and must be separated from the @ sign by at least one space. The keyword is followed by an equals sign (=) and a value. Furthermore, multiple keywords can appear in a single processing directive, and no spaces can appear on either side of the equals sign. The following is an example of a processing directive that tells the Web server that the VBScript language is being used (the default):

<% @ LANGUAGE=VBScript %>

When using VBScript or JScript, the ASP processing engine removes white space. When you need to include a blank space in HTML, use the HTML non-breaking white space character,   see an HTML reference for additional special character.

VBScript Comments and Variables

In VBScript, comments can appear within primary scripting commands, with the exception of output commands. Comments are defined by anything to the right of an apostrophe (with the exception of the end delimiter):

<%
If Time >= #12:00:00 AM# And Time < #12:00:00 PM# Then
Response.Write "Good Morning!"   ' Write morning greeting.
Else
Response.Write "Hello!"   ' It must be later in the day.
End If
%>

As you can imagine, comment notation depends on the scripting language. For example, while VBScript uses the apostrophe, JScript makes use of the // characters to denote a comment, similar to Java, Delphi, and C++.

Although variables don't need to be declared in VBScript, they should be declared for good programming practice. Once declared, or assigned in those cases in which they aren't declared, variables are accessible to the remaining commands in that ASP page. For example, the following statement declares a variable named UserName, and sets its value to that of a value passed in the HTTP query string. The following variable can be used in any expression that appears in any commands later in this page:

<%
Dim UserName
Set UserName = Response.QueryString("Name")
%>

There are two special classes of variables that are visible to more than one ASP page. These are Session and Application variables. Session variables are available to all pages accessed by a particular user within a session. By comparison, Application variables are shared by all ASP pages in an ASP application. These variables are stored using the Session and Application built-in objects, respectfully. These objects are described in greater detail later in this article.

You access Session and Application variables by passing the name of the variable to the Session or Application object. For example, the following code stores the session start time in a Session variable:

<% Session("SessionStart") = Now %>

All pages on the site accessed by a specific user can then read this value using the following statement:

You began your session at <% = Session("SessionStart") %>

VBScript doesn't permit the declaration of constants. Constants are defined using type libraries.

Include Files

Include files are similar to Delphi's Web Broker TPageProducer in that they permit you to insert segments of HTML into your page at specific points. For example, if you have a segment of HTML that should appear at the top of every page, you can create it once and embed it within each ASP page by using the include directive before any other simple HTML text or commands on the page.

The include statement has the following syntax:



If the keyword VIRTUAL is used, the dirname part is a virtual directory (defined through server configuration). If FILE is used, the directory can either be an absolute or a relative directory. For example, if you have created a virtual directory under IIS named Chunks, you can use the following include statement to include the header.htm HTML in your ASP page:



In addition to including static HTML, include files can also reference ASP pages or ASP segments. However, note that ASP segments referenced by include directives are processed on the server before the referencing ASP page is processed. This processing is unconditional. That is, all included ASP pages are processed - even those where the include statement is referenced within an <%IF%> statement - before the first primary command of the referencing ASP page is processed.

Using Objects

ASP objects are Automation servers, and therefore can be either in-process servers or out-of-process servers. There are two general classes of objects that you can use from an ASP: built-in objects and custom objects.

The Server and Application objects referenced previously are examples of built-in objects. These objects are available to all ASP pages. These built-in objects are automatically created for you by the server, and can be referenced within any primary commands. By comparison, you must explicitly create custom objects before you can access them. You create custom objects by calling the CreateObject method of the Server built-in object, passing to it the PROGID of the registered object. For example, if you have registered an Automation server with the PROGID of Project1.Text, you can create an instance of it, and assign this instance to the variable DelphiASPObj using the following command:

<%
Set DelphiASPObj = Server.CreateObject("Project1.Test")
%>

You can also use the HTML tag to create an instance of an object. When doing so, however, you must include the RUNAT directive with the Server option to ensure that this object runs on the server, and not on the browser's machine:

PROGID="Project1.Test">

Java objects. Rather than using COM objects, you can use Java objects in your ASP commands, as long as your Web server supports Java. The following example demonstrates how to create an instance of the java.lang.Integer class:

<%
Dim date Set intobj = GetObject("java:java.lang.Integer ")
%>

Once you have a reference to the Java object, you can call its methods. For example, the following example calls the parseInt method of the Integer class:

<% = intobj.parseInt(somestring) %>

Although the availability of Java objects within ASP pages provides you with some flexibility, Java objects typically can't access the built-in objects, nor can they be part of an MTS transaction. Consequently, their use is usually reserved for special operations not normally available through the scripting language of COM objects.

Using methods. You call an object's methods using dot notation to invoke the qualified method name. If the method requires one or more parameters, then follow the method name using the syntax of your scripting language. For example, to invoke the built-in Response object's Write method, you use a statement similar to the following example:

<% Response.Write "Text to return to the browser" %>

Using properties. You reference an object's property by using dot notation to reference the qualified property. You write to the property by placing the property reference on the left side of an assignment statement. You read the property by including the qualified property name in an expression. Because properties in COM make use of accessor methods, reading and writing properties of ASP objects results in the execution of the defined read and write methods, respectively. From these methods, you can invoke custom code, or even reference both built-in and custom ASP objects.

Built-in objects. ASP pages have access to a number of objects created automatically by the ASP-enabled server. These objects can be referenced by your server-side VBScript, permitting you to get information about the environment, as well as to control the behavior of your ASP. The following built-in objects are available to all ASP pages: Application, ObjectContext, Request, Response, Server, and Session.

The Application object permits you to store application-wide data. An ASP application is a set of related ASP pages under a common directory structure. The application starts the first time a page of the application is loaded, and shuts down when the server is shut down.
The ObjectContext object is used to start, commit, abort, and complete transactions.
The Request and Response objects permit you to get information about the HTTP request and to control the HTML response. For example, the Request object permits you to read query strings, cookies, binary data, client certificates, and server variables. The Response object, by comparison, can be used to write cookies, control page caching (affecting caching servers), and write the response, among other operations.

The Server object is used primarily to create new ActiveX or Java objects. It can also be used to control URL mapping and encoding and HTML encoding.

The Session object represents one or more hits on pages in a given ASP application by the same user. To use a session object, the user's browser must be set to accept cookies to be sent back to the same domain. One of the most powerful aspects of the Session object is that it permits you to track information as a user navigates from one page to another within your ASP application.

If you must track sessions without using cookies, you can use Cookie Munger. Cookie Munger is an IIS filter that executes for every page request, producing an overall performance penalty as an unwanted side effect. Cookie Munger will detect whether the browser will accept cookies. If the browser doesn't accept cookies, the munger will generate a session ID for that browser. Furthermore, when a page is being sent back to a browser that doesn't accept cookies, Cookie Munger adds query string information to every URL that references back to the ASP application. The Microsoft Cookie Munger can be found in the IIS Resource Kit.

Custom ASP objects. Even without custom ASP objects, it's clear that ASPs can provide you with the power and flexibility to create more intelligent Web content. However, one of the more powerful aspects of ASPs is that you can create custom ActiveX servers for use with them. Specifically, you can create ActiveX servers that are invoked by a Web server at run time. Those ActiveX servers can read information about the HTTP request, as well as execute custom code to provide the necessary response. ActiveX servers used in this context are referred to as ASP objects for short.

Since the release of Delphi 3, Delphi has made the creation of COM servers almost effortless. With Delphi 5, this convenience has been extended to ASP objects. The Active Server Object Wizard, shown in Figure 1, appears on the ActiveX page of the New Items dialog box. Using this Wizard, you can create an ASP object that can be registered on your Web server (in that machine's Windows registry), as well as a sample HTML page that can be used to invoke your custom ASP page.


Figure 1: The Active Server Object Wizard is accessible from the New Items dialog box.

As mentioned earlier in this section, custom ASP objects can be in-process servers or out-of-process servers. The following example makes use of in-process ASP objects. These objects can be loaded in the process space of the Web server, or installed and invoked from MTS.

Creating a Custom ASP Example

Use the following steps to create a custom ASP object for use with IIS:

Select File | Close All.

Select File | New to display the Object Repository. Select the ActiveX tab, then double-click the ActiveX Library Wizard. This wizard creates a new DLL-based project that exports the essential four functions for in-process COM server activation.

Select File | New again. Then, select the ActiveX tab and double-click the Active Server Object Wizard. Delphi responds by displaying the New Active Server Object dialog box (see Figure 2).

At CoClass Name, enter DelphiASP. If you're using IIS version 3.0 or 4.0, you must set the Active Server Type to Page-level event methods. If you're using IIS version 5.0, select Object Context. Leave Generate a template test script for this object enabled. Click OK when you're done.



Figure 2: The New Active Server Object dialog box.

At this point, creating your ActiveX server object is like creating any other type of COM server. You use the Type Library editor to declare methods and properties. From within the implementation of your methods, you write your code logic. What is somewhat different from other types of COM servers is that the interfaces that enable ActiveX server objects expose a number of interface references that provide you with access to the built-in server objects. For example, your server inherits a Request property, which gives you access to the built-in Request object. Similarly, you have access to the Response property, which you use to invoke methods of the built-in Response object.

The following steps demonstrate how to implement a method on the server. This particular example is being kept fairly simple.

Using the Type Library editor, add a new method named SayHello. Don't define any parameters for this method (see Figure 3).

Click the Refresh Implementation button to generate the SayHello method stub in the DelphiASP CoClass.

Implement the DelphiASP.SayHello method. The example in Figure 4 demonstrates the use of several Response.Write methods, using the ServerVariables interface, as well as accessing the Request object.

Save the project as DelphiASP.DPR. (Save the CoClass unit using any name you want. In the ASPDemo project, it's named coclassu.pas.)

Compile the project, and then select Run | Register ActiveX to register this ASP object with the Windows registry. (All files and projects are available for download; see end of article for details.)



Figure 3: Adding the SayHello method in the Type Library editor.

procedure TDelphiASP.SayHello;
var
i: Integer;
begin
with Self.Response do
begin
Write('This is the response ' +
'from the Delphi ASP object.

Here is a big ' +
'

Hello !!

' +
'This request has come from a ');
Write(Request.ServerVariables.Get_Item(
'HTTP_USER_AGENT'));
Write(' agent at address ');
Write(Request.ServerVariables.Get_Item('REMOTE_HOST'));
Write('.
Furthermore, the last page you ' +
'visited was (none if blank): ');
Write(Request.ServerVariables.Get_Item(
'HTTP_REFERER'));
Write('

The request method was ');
Write(Request.ServerVariables.Get_Item(
'REQUEST_METHOD'));
Write('

There were ');
Write(IntToStr(Request.QueryString.Count));
Write(' items in the query string.');
if Request.QueryString.Count <> 0 then
begin
Write('

The query string is :');
Write(Request.QueryString);
end;
if Request.Form.Count <> 0 then
begin
Write('

There were ');
Write(IntToStr(Request.Form.Count));
Write(' items sent by an HTML FORM.');
Write('

These are ');
for i := 1 to Request.Form.Count do
begin
Write('
');
Write(Request.Form.Key[i]);
Write(' : ');
Write(Request.Form.Item[i]);
end;
end;
if (Request.QueryString.Count = 0) and
(Request.Form.Count = 0) then
Write('

There was no data sent with this request.');
end;
end;
Figure 4: Demonstrating the use of several Response.Write methods.

Calling the Custom ASP Object

You now must update the text of the ASP page generated by Delphi. Originally this page looked like the code shown in Figure 5.



Testing Delphi ASP


You should see the results of your Delphi Active
Server method below





<%
Set DelphiASPObj=Server.CreateObject("Project1.DelphiASP")
DelphiASPObj.{ Insert Method name here. }
%>




Figure 5: Original ASP page.

Change the generated code to look like that shown in Figure 6.



Testing Delphi ASP

You should see the results of your Delphi Active
Server method below





<% Set DelphiASPObj = Server.CreateObject(
"DelphiASP.DelphiASP") DelphiASPObj.SayHello %>




Figure 6: Modified ASP page.

In this modified ASP page text, the CreateObject call has been updated to refer to the ProgID of the newly created ASP object. Also, the call to invoke the SayHello method of this object has been added.

Now save the .asp file to the root directory of your Web server. Make sure you keep the file extension as .asp. Next, using the [Ctrl][O] (File | Open) selection from your Web browser, type http://localhost/delphiasp.asp. (This assumes you're testing this application using a local Web server. If you're using a Web server on another machine, replace localhost with either the domain name, the machine name, or the IP address of your Web server.) After a moment, the page should load. Figure 7 shows what this page looks like in Netscape Communicator.


Figure 7: The updated ASP page as seen in Netscape Communicator.

Because this page was displayed using the Open Page feature, there was no HTTP referrer. However, if you loaded this page by clicking an anchor tag link (), or submitting an HTML form with either a GET or POST action, the URL of that linking page would be displayed following the "last page you visited" text.

If you now select View | Page Source, you will see the HTML generated by the ASP (see Figure 8). Notice that what you see here is plain HTML. None of the ASP commands are visible, because the server replaced them with the HTML text generated by the ASP object.


Figure 8: The HTML generated by ASP.

Calling Your ASP from an HTML Form

As mentioned earlier, if you had displayed your ASP-generated HTML by clicking on a link, the HTTP_REFERER server variable would contain the URL of the linking page. Likewise, if this link was generated by either a GET or POST action from an HTML form, the ASP would display the data sent by the form.

This effect is demonstrated using the HTML page defined by the text in Figure 9, which is found in the TESTASP.HTM file located along with the sample code for this article.


Demonstrating an HTML form calling an ASP

Enter some data into this HTML form




First Name :

Last Name :

Age :





Figure 9: An HTML form calling an ASP page.

If you save this page to the same directory in which you have placed the ASP page, then load it into your browser and enter data into the text input fields, your browser will look something like that shown in Figure 10.


Figure 10: The HTML text from Figure 9 displayed in a browser.

If you click the Enter button on the HTML form to invoke your ASP object, the resulting HTML downloaded to your browser may look similar to that shown in Figure 11.


Figure 11: The resulting HTML after invoking your ASP object.

Alternatively, if your HTML form used the GET action (the default) instead of POST, the resulting page may look something like that shown in Figure 12.


Figure 12: HTML opting for the GET action rather than the POST action.

Conclusion

In this article, we've seen a number of different ways you can benefit from the use of ASP in Web development. And when you add ASP's ability to utilize Delphi's COM capabilities, Web development becomes all that much more robust.

Component Download: http://www.baltsoft.com/files/dkb/attachment/Delphi_and_ASP.ziphttp://www.baltsoft.com/files/dkb/attachment/Delphi_and_ASP.zip

<< Back to main page