DevShed.com
★ wanayoo — archive 1999 http://devshed.com/Server_Side/ASP/Introduction/print.htmlNouvelle recherche | Portail wanayoo
DevShed.com 

Introduction to ASP
By Russell Mueller
April 21, 1999

Printed from DevShed.com
URL: http://www.devshed.com/Server_Side/ASP/Introduction/


Introduction
Server-side scripting is the hot topic du jour in web development. In a lot of ways, it's a logical evolution of the CGI idea. The *NIX world and Apache have PHP for their server-side, embedded scripting language, and Active Server Pages (ASP) is Microsoft's take on the subject. ASP is a small .dll that lives in the same memory space as your HTTP server (usually Internet Information Server). It represents a somewhat different approach to server/client interaction than traditional CGI model and, to give the folks in Redmond some credit, it's a robust and powerful solution.

ASP works as a filter and a redirector for IIS, intercepting incoming client requests with the .asp extension, caching information as needed (such as database queries), thereby taking some strain off of the HTTP server and, usually, speeding things up a bit as well.

What happens, generally, is this: before IIS gets a chance to deal with a client request with an .asp extension, ASP.dll sees the request, snatches it, processes it, and sends the resultant HTML page to the server. Neither the HTTP server nor the client is aware that it's getting the wool pulled over its eyes.

Active Server Pages have a couple of other things going for it. First of all, if you're working on an NT platform and using IIS, ASP and ASP's most useful components are free. ASP is also reasonably language-neutral. You can write your ASP code in the scripting language of your choice: the default is VBScript (although that can be changed via IIS), but if you prefer, you can use JScript or PerlScript by simply declaring it at the beginning of your code. That being said, we'll use VBSript in this tutorial.

One of the main reasons folks are so interested in ASP (or any server-side scripting language for that matter) is database manipulation and file access. ASP is particularly strong in these arenas, with ActiveX controls such as ADO providing some nice tools for manipulating outside data sources. We'll play a bit with the File Access component later in this article.

ASP is also extensible. Components are modules that add specific areas of functionality to ASP, and, although IIS comes with several useful prefabricated components, more can be obtained from third-party vendors or written yourself with anything from Visual Basic to C++ to Java, if you have the know-how. As of late ASP components have become a hot business on the web. If there's a something you want ASP to do, and you aren't able to make it happen with the standard components, it's a fair bet that you can find one on the web that will do the trick or write one yourself.

Finally, before we dive in, it needs to be said that, though ASP is primarily a Microsoft paradigm, it's not limited to Internet Information Server. Because of the popularity that ASP has been enjoying recently, third party vendors have begun to produce a number of ASP implementations for other platforms, most notable ChiliSoft! ASP for Apache Web Server. We'll focus on the IIS version, since that's what's most often found in the wild.


And Now for Some Code
Okay, now let's try a little code. The first thing you need to do when writing anything for ASP is let it know what language you're using. If you're using VBScript, technically you can skip this and ASP will use VBScript by default, but declaring your scripting language is a good habit to get into. So the first line of your ASP code will be:

<% @ Language = "VBScript" %>
Note the <% and %>. Anything between those marks, anywhere on an .asp page, ASP regards as gist for its mill.

For our first script, let's use ASP to tell the user what date it is on the server. It's pretty straightforward:

<%@ Language = "VBScript"%> <HTML> <HEAD><TITLE>First Script</TITLE></HEAD> <BODY> <% Response.Write "<P>Today is " & Date () & ".</P>" %> </BODY> </HTML>
This would appear on your browser as:
Today is 3/17/99.

Here's what you should latch onto in the above example: First, the use of Response.Write.
Response.Write tells ASP to insert whatever follows into the HTML stream that's being sent to the server. Quotes delimit what ASP will send to HTML straight out. The &'s mark off any variables, functions, or subroutines, inserting the values or results directly into the HTML stream. For example, if you were to view the source for the above page on your browser, you wouldn't see the ASP code, but the following ASP-rendered HTML:

<HTML> <HEAD>First Script</HEAD> <BODY> <P>Today is 4/17/99.</P> </BODY> </HTML>
There's also shortcut for Response.Write, the delimiters (<%= %>). The above code could be written as follows:

<P>Today is <%=Date ()%>.</P>
It works out exactly the same way. ASP code doesn't have to all be in one chunk on your page, either. It can be interpersed throughout your HTML if you wish. Suppose you wanted to display different images on a page depending on a user's color preference. (We'll go into how to grab values from forms in a little while.) You could write:

<% If varPreference = "yellow" Then %> <IMG SRC = "/old?u=http%3A%2F%2Fdevshed.com%2FServer_Side%2FASP%2FIntroduction%2Fyellowhat.gif&y=1999"> <%Elseif varPreference = "red" Then %> <IMG SRC = "/old?u=http%3A%2F%2Fdevshed.com%2FServer_Side%2FASP%2FIntroduction%2Fredhat.gif&y=1999"> <% End If %>
For the record, that could also be written:

<% Response.Write "<IMG SRC = " If varPreferences = "yellow" Then Response.Write "yellow.gif>" Elseif varPreferences = "red" Then Response.Write "red.gif>" End If.%>
You can also include subroutines on your ASP page, like the following example, which produces a list of files for a given directory on the server. We'll use this code more in the next section. For now, just note the way that subroutines can be called from within the ASP page.

<% Sub GetFolderFiles (folderspec) Set objFolder = FileObject.GetFolder(folderspec) Set objList = objFolder.Files For each File in objList Response.Write File.Name Next End Sub FolderName = "./text/" Set FileObject = Server.CreateObject("Scripting.FileSystemObject") Set Folder = FileObject.GetFolder(Server.MapPath(FolderName)) GetFolderFiles (Folder) %>
Or, if you have a subroutine that will be used on several pages (or just want to centralize your code) you can use the #includestatement, which lets you insert the contents of a file into your ASP page. The following syntax is used:

<! -- include virtual="/scripts/mycode.inc" -- !>
In the statement, virtual refers to the type of path (virtual for a virtual path, file for a local path), and "/scripts/mycode.inc" is the file to be included (included files can have any extension, but whatever you use, stay consistent to keep things straight).

On a final note, there's nothing to say that you have to use ASP to write HTML. It could just as easily be used to construct XML or JScript code as well. The potential for a completely customizeable web experience is pretty exciting.


Something With a Bit More Heft
Above, we used the example of a script that listed the contents of a directory (via the File Access Component). The script as it stands is fairly limited, but still very useful, since users are provided with a dynamic, up-to-date listing of available files, but don't actually have access to the directory itself. This can be nice for many reasons, the least of which is not security.

The basic code is below:

<% Sub GetFolderFiles (folderspec) Set objFolder = FileObject.GetFolder(folderspec) Set objList = objFolder.Files For each File in objList Response.Write File.Name Next End Sub FolderName = "./text/" Set FileObject = Server.CreateObject("Scripting.FileSystemObject") Set Folder = FileObject.GetFolder(Server.MapPath(FolderName)) GetFolderFiles (Folder) %>
Here's more about what's going on: ASP thinks of nearly everything as an object, and requires that objects you're going to use be explicitly created. (This includes database ODBC connections as well.) You create obects with the Set command. So we created the object FileObject on the server with Set FileObject = Server.CreateObject("Scripting.FileSystemObject"). That has to be done first. Next, we create another object: the folder we want to work in. A folder's path on the server has to be spelled out by Server.MapPath in order for ASP to be able to manipulate it. Note that the resultant path will be an actual path rather than virtual. On our server, Set Folder = FileObject.GetFolder(Server.MapPath(FolderName)) - where FolderName = "./text/" - returns D:\WEBSERVER\WWWROOT\TEXT. The reason a virtual path isn't returned even though we might expect it to be is simple: ASP.dll lives locally on the HTTP server and thinks in local terms.

Then we call GetFolderFiles with Folder as an argument. Two more objects are created in the subroutine. First, the objFolder object lets us grab onto the folder we want; and second, the objList object is actually a collection of the Files in obj.Folder. Finally, we just run a simple For-Next loop, writing to our HTML page the name of each File.

Of course, if we don't want users to see certain files we can test for and exclude the names of the files we want to keep private. Following the IIS convention, we'll add a leading underscore character( _ )to the names of those files, and toss a quick test into our code to bypass them:


If Left(File.Name,1) = "_" Then
Exit For
End If



Now let's throw in a new wrinkle. It'd be nice to let users pick which document they would like to read from a list box and then display the results in an HTML page. To do that, we'll need to populate the list box on a form with the results of our directory search, and then create a routine to stream the contents of a text file into HTML.

For the form itself, the code will go like this:

<HTML> <HEAD> <TITLE>Populating a List Box</TITLE> </HEAD> <BODY> <% Sub GetFolderFiles (folderspec) Set objFolder = FileObject.GetFolder(folderspec) Set objList = objFolder.Files For each File in objList If Left(File.Name,1) = "_" Then Exit For End If FileURL = File.Name Response.Write "<OPTION>" & FileURL & "</OPTION>" Next End Sub %> <FORM ACTION="/old?u=http%3A%2F%2Fdevshed.com%2FServer_Side%2FASP%2FIntroduction%2Ffilelist.asp&y=1999" METHOD="POST"> <SELECT NAME="Files" SIZE="1"> <% Folder = "./text/" Set FileObject = Server.CreateObject("Scripting.FileSystemObject") Set Folder = FileObject.GetFolder(Server.MapPath(Folder)) GetFolderFiles (Folder) %> </SELECT> <INPUT TYPE="submit" NAME="Submit"> </FORM> </BODY> </HTML>
Here's what's going on. We've kept our subroutine intact, but instead of simply writing the file name to the page, we've placed it in an <OPTION> tag. Create the form, run the subroutine, and we're done.

The code for the display page is only a little more complicated:

<HTML> <HEAD> <TITLE>Results Display</TITLE> </HEAD> <BODY> <% Folder = "./text/" Set FileObject = Server.CreateObject("Scripting.FileSystemObject") Set Folder = FileObject.GetFolder(Server.MapPath(Folder)) FileURL = Folder.Path + "\" + varFile varFile = Request.Form("Files") Response.Write "<P>You have requested <B>" & varFile & "</B>.</P>" Set fsObject = Server.CreateObject ("Scripting.FileSystemObject") Set txtObject = fsObject.OpenTextFile (FileURL) strFile = txtObject.ReadAll txtObject.Close Response.Write "<P>Contents of <B>" & varFile & "</B>:</P>" Response.Write "<P>" & strFile %> </BODY> </HTML>
First we re-create our File Access objects. (We could actually get around that by holding them in a Session variable, but that's a bit beyond the scope of this article.) Then we pull the name of the file we want from the form we just created with varFile = Request.Form("Files"). Next, we create a few new objects. (Remember, Server.CreateObject must be set.) We use the OpenTextFile method on the fsObject object to open the text file we want as txtObject. Finally, we use the ReadAll method on txtObject to read the contents of the file into a variable, which we can manipulate however we want. We could just have easily opened the file for append (if we had permissions on the server), deleted a file, or created a new file. Or the text file we read could have included HTML or JScript. There's a lot of potentiality for this type of script.


Where to Go Next
This article has barely scratched the surface of ASP. Up until recently, there was a great lack of decent ASP related web sites (Microsoft's being no exception). One of the best around right now is www.4guysfromrolla.com, which has a wealth of practical, well-written articles for ASP developers of any skill level. Another similar, equally good site is www.asp101.com. Both sites will be very helpful to anyone trying to pick up ASP or find task-specific, no-fluff how-to articles. Several ASP mailing lists can be found at www.activeserverlist.com.

Likewise, until very recently there were hardly any ASP books on the shelf. Wrox Press has a fairly good selection available if you're completely new to scripting, but if you're familiar with scripting at all, or come from a PHP background, the only text reference you will need is the recently published ASP in a Nutshell from O'Reilly Press. Like nearly every O'Reilly I've come across, this is the book that will stay next to your computer while you work.



Copyright © 1997-99 ngenuity. All rights reserved.