ASP Tutorial Lesson 2: Response

So far we haven’t done anything useful in this tutorial. I expect now you know what ASP is you are itching to have a go at making it do something! Let’s start nice and easy by outputting some text to the users browser.

We can do this two ways, the long way and the shorthand way.

Long way

Outputting text requires the “Response” objects “Write” method, as in the following:

response.write “foo”

or

response.write(“foo”)

<%

response.write “Hello World”

%>

We will re-visit the the response object further on in this tutorial.

Shorthand

If you want to display an ASP value within a block of HTML you can also use the alternative approach of <%=value%>as in the following:

< % =”foo” % >

<%=”Hello World”%>

This internally still uses the response object but makes it easier to slip values into your layout. We used this method in the example in the previous installment that output a date/time.

http://www.aspalliance.com/chrisg/tools/helloworld.asp

This page simply displays takes todays date and time that is returned by calling “now” and sends it to the users browser
http://www.aspalliance.com/chrisg/tools/view-helloworld.asp.aspx

 

Line breaks

If your lines start getting too long you can break it over multiple lines using the following

response.write “This is a very long line so we must ” &_ “continue another line even though when output ” &_ “it will all appear together”

Whitespace is not necessary in your HTML but can help when debugging or when reading it so you might want to output a line break. You do this with the VBCRLF value (Carriage Return and Line Feed).

response.write VBCRLF

 

ASP Tutorial Lesson 1: “Hello World”

In this lesson we will look at the most basic example of an ASP script. Following programming tradition it is called “Hello World”.

Take a look at the following code and enter it into the text editor of your choice, saving the file as “helloworld.asp” into your web root (usually “C:\inetpub\wwwroot” by default, but check your IIS/PWS installation).

The observant among you will be saying “but that is just a HTML file!”, and you would be right. This demonstrates one of the basic principals of ASP – ASP is at its most basic just HTML with programming instruction (“code”) added. With the later versions of ASP (ASP 3 and ASP.NET) once the page has been visited this would even not execute much slower than had it been named .html

Let’s take a look at an example page
http://www.aspalliance.com/chrisg/tools/helloworld.asp

This page simply displays todays date and time and a little message. You can look at how we did this with the following link.
http://www.aspalliance.com/chrisg/tools/view-helloworld.asp.aspx

We will look at how exactly this works in the next installment, first let’s look at how code is inserted ..

Adding ASP CodeThere are two ways we can add code directly into our page.

<SCRIPT runat=”server”>

‘ comment

</SCRIPT>

and the shorthand

<%

‘ comment

%>

As you can see, we can add code comments by starting the line with an apostrophe.

We can also include code from another page using

<!– #include file|virtual=”filepath” –>

Virtual uses your web servers virtual paths, while File can locate a file from the current directory.

For the moment you are probably best off keeping all your code in the one page until you are confident, but seperating your code like this will pay dividends later on when your sites become more complex and you begin building up large collections of useful routines.

How does it work

The ASP interpretter reads in your ASP file and executes any instructions that it finds, sending the resulting output to the visitors browser. Included files will be processed before any other code, so be careful of this.

 

ASP Tutorial

Welcome!

My name is Chris Garrett and this is my ASP tutorial. I hope it is useful to you and you can help make it even more useful by contacting me with your comments, hopefully it will improve over time.

About this tutorial

This is not the first (or the best) tutorial out there, just my take on things. There will be many people out there who know more than me and I hope if you are one of those people you will give me some advice on how I can make this tutorial better.

I have tried to just give you enough information for what you need and no more. Once you have digested this you should be equipped to dig into the many reference materials out there with confidence.

About ASP

Active Server Pages (ASP) is a compile-free, text-based scripting environment for creating dynamic web sites. It allows a developer to quickly and easily create dynamic database-driven web sites, intranets and extranets.

To write an ASP script all you need is a text editor, Notepad will do. To run ASP you will need an installation of IIS or a version of personal web server. ASP can connect to all popular databases but most ASP programmers start out with Access or SQL Server. There are also ASP environments available for other operating systems such as Chilisoft ASP which will run on operating systems such as Unix.

The History of ASP

ASP first became available to developers in October 1996 with the release of the public beta for Internet Information Server 3 (IIS). Up until this point, ASP had been known by the project name “Denali”. Microsoft followed up with ASP 2 in August 1997 as part of IIS 4 and with IIS 5 and Windows 2000, ASP is now at version 3.

Microsoft has developed a new replacement for what many people call “Classic ASP” called ASP.NET as part of their huge .NET initiative, but many people and companies will need to keep their classic asp systems for a while even once ASP.NET is officially released.

Installing ASP

To run your ASP scripts you either need Internet Information Server (IIS) on Windows NT/2000 or Personal Web Server (PWS) for Win9x. IIS is an optional part of the Windows 2000 installation, just add it with “add/remove”. Windows NT 4 requires the NT4OptionPack from Microsoft.

 

Combined plain and HTML email

This article explains how you can combine both a plain text and a HTML message in one EMail by defining its content type.

Setting the “Content-Type:” of an email message as “Multipart/Alternative” tells the mail system you are creating the email message in parts, one text/plain and the other text/html. Which part is displayed is left up to the client email program.

View the email
http://www.aspalliance.com/chrisg/tools/view-multipart.txt.asp

There are a couple of problems with this method, first of which is the filesize can more than double and every recipient has to download the whole thing. The second issue is that the majority of mail readers that understand multipart also understand HTML!

Having said that it is still a useful technique in some circumstances. Check out the below example script which demonstrates loading a template email and replaces keywords. I use a text file creation technique to show how you can implement this with a wide variety of smtp servers regardless of wether they support the multipart functionality directly or not.

Automation 1: Execute DTS from ASP/SProc

DTS is a wonderful tool in SQL Server. It allows you to automate importing, exporting, merging and transforming of data. This is great if you have access to the management console, what if you want to give the client a button to push?

Enter the following code into a new stored procedure.

CREATE PROCEDURE doPublish AS
exec master..xp_cmdshell 'dtsrun /Ssql1 /NPublish /E'

This will execute the DTSRun command line utility with the parameters

  • /S = SQL Server Host Name
  • /N = DTS Package Name
  • You can either use /E for “trusted connection” or /U/P to supply username and passwords

Once you have your new stored procedure, simply create an asp page that calls the stored procedure name as an SQL query, such as

cn.Execute("doPublish", , 1)

(Where cn is your database connection).

There you have it, DTS at the click of a button!

 

Downloading files to the browser with ADODB.Stream

This script demonstrates getting properties of a file, such as name and size, and using a response stream to send the file to the users browser.

VIEW SOURCE
http://www.aspalliance.com/chrisg/tools/view-downloadfile.asp

The script begins by calling the function “downloadFile” with the file we wish to download as a parameter, in this case getting it from the “file” request variable.

DownloadFile() first gets full path of specified file and checks to see if the file exists using the FileExists(strFilename) method of the filesystem object. It then gets the length of the file (the size) using the .size property of the file object.

Lines 19 and 20 show how we create the stream object and in line 23 we set the stream to binary. Line 42 uses the loadfromfile method to begin the process to read in the file, and after the headers have been set between lines 49 and 52, the file is output using Response.Binarywrite and the contents of the streams “read”.

Future improvements

I have fudged this script a bit by using a default content type of “octet”, you could improve this scripts functionality by specifying the corrent mime type.

Automation

One should always try to be more productive, even if it is only to speed up the dull bits so you have more time to do the fun stuff ;O)

The following three articles show how you can automate routine tasks with ASP, Windows Scripting Host (WSH) and SQL Server Data Transformation Services (DTS).

Each article stands on its own, but there is no reason why you could not mix and match as they are all complementary and execute in their own environments.

We start with DTS as this is the tool I have found most useful in automating workflow or moving/importing/exporting data at the push of a button ..

  1. Execute DTS from ASP/SProc
  2. Run command lines from ASP
  3. Call a web page from command line

 

Review: Professional ASP.NET

You can always rely on Wrox to come up with great ASP books, and this is no exception.

Now, if asked I would more than likely say I was an O’Reilly fan. Most of my technical books seem to have an animal on the front, but take a quick glance at my bookshelves and you will be able to see a close second would be big red books with unattractive faces all over them.

This seems to be the trademark of Wrox for now, I guess they are saying “these people are so ugly they don’t get out much, so they must know what they are talking about”.

Minging they may be, but they do know their stuff.

The book is well written, both from a technical and readability standpoint, and this is where they have a slight edge over O’Reilly. Some O’Reilly authors have brilliantly readable writing styles, but many “Over tech” and the books become dry tomes that are about as fun to read as a telephone directory printed in 5pt type.

They have coped well with the fact ASP.NET is such a new and constantly updating subject, and the examples lead you gently through the subject matter. Thankfully, they have also recognised that the main subject is cool enough without stuffing the remainder of the book with acronym-tastic examples to make it fully “buzzword compliant” as in some of this books stable mates (professional JSP an example).


Professional ASP.NET

professional asp.net

As a taster, you can preview the first chapter on the Wrox site as a PDF.

 

Rating: :OD

I give it one big nosed grinning smiley

 

Review: Commerce Server 2000 Programming

My initial reaction when the book landed on my desk was “Oh .. my .. God, Look at the size of this book – look how many authors there are! This must be a big subject” and believe me, I was right.

book cover

Now, I doubt very much you will be able to learn everything you need to know just by reading this one book, and there doesn’t seem to be that many out there to choose from, but the book does cover the subject comprehensively. Perhaps too comprehensively. As I was reading it I had the nagging feeling perhaps it should have been split into a smaller, idiots style quick start book and another fatter reference book.

Ordinarily I breeze through technical books, enjoying reading them from cover to cover. Due to my train commute I get through a couple of books of this type a month without any bother. This particular book I had to make a real effort, I found it very hard work. Was it because the subject matter was difficult? No, is it badly written? Not at all. So why did I have to force myself to continue with it?

I have thought a lot about why and all I can think the reason could be is because it doesn’t flow. Often books have a noticeable beginning, middle and end, where as this book seems to just cover the subjects it needs to. Also it is quite dry, others in the Wrox family inject humor and colorful examples to liven things up. The examples don’t follow on as you would expect and are not inspiring either, so in the end I found it lifeless and inconsistent.

Does it fulfil its purpose?

Yes and no.

It does cover the subject very well, and it does show you how to get up and running. Even I, under motivated as I was, managed to get the software installed and something going. I doubt I really needed the book and could probably have done so (perhaps in a longer time frame) with the Microsoft documentation. Because I found the book dull I gave up on following the examples. Probably a good job judging from mailing lists and news groups as most people have had problems getting them to work.

Summary

I would recommend it as a reference book. There is not a lot of selection out there, and the format does allow you to dip into the subjects you need. This is definitely NOT a book to take on holiday or to read in quiet moments, unless you have real problems sleeping.

Score

(:O’ – half a smile

 

ASP.NET HTML Editor Review: RichTextBox

Most large web sites now include some method for site copy to be created dynamically, with all but the larger (ie. higher budget) installations using a custom content management system.

There are many good reasons for this, one near the top of the list is usually cost savings (not having a web agency update copy while charging by the hour), another is ease of maintenance for the client (not having multiple-hour turnaround).

When developing these content editing interfaces, some way must be given for the editor to enter textual copy. Traditionally this takes the form of some kind of text box. While the text box solution is great for the developer and fine to produce plain unformatted text, not so good for a client that is expecting to be able to add bold, italics, indents, bullets and images.

RichTextBox to the rescue

ASP.NET developers can now add rich HTML formatted text entry as easy as adding a simple text box, using the RichTextBox ASP.NET server control. The RichTextBox control allows the user to insert links, images, bullets, change fonts, etc, all in a familiar word-like manner.

While this sort of functionality has been becoming more and more common a sight, especially since Microsoft included much of the underlying technology in later versions of IE, this product wraps the functionality up in an extremely easy to implement package. It really is almost a case of dragging the control onto your ASP.NET page to get up and running.

Choices

You have a choice of three options when looking to use the RichTexBox.

First is a free download for evaluation purposes. This version is fully featured and the license is limited to 30 days. A message appears in the users work space to identify the control as the trial version.

Next up is the version most developers would look to use initially which is the version intended for a single  web site (“standard” version). At $89.95 the control can be yours for less than an hour of a heavy weight contractor would cost!

For those who have really fallen for the contol in a big way there is the “Professional” license. This allows use across multiple web sites and is also the choice for deployment in web farm installations.

Alternatives

As noted earlier, the actual technology is not uncommon, so what of the alternatives.

First alternative is obviously to code your own. Well, as the cost is only just short of 90 bucks (US) which is just short of 60 uk pounds I don’t think there are a heck of a lot of people who would see that as economic, especially when you add in the time for testing and documenting the thing.

You could buy one of the Java or Director developed browser components. This is really the only option if your users might need to use Netscape as RichTextBox is IE only. This cross-browser arena is one that developers are giving a lot of attention.

What about competitors to RichTextBox? Well, checking out ASP.NET control gallery there are a few. I can only talk from initial impressions, mainly going by their web sites, number of downloads and client lists, but none seem to be as “mature” as RichTextBox. Only time will tell if any become a serious competitor.

Check out the RichTextBox site and you will see there are some pretty serious names using the control (including Microsoft, Intel and Sony – nice!), along with the fact it has been tested by hundreds of beta testers then downloaded and used thousands of times, this gives me a fair amount of confidence it will work as advertised.

Implementation and development

After all this, the real proof is how good it is in action. Patience is not my strong suit but thankfully I didn’t need any – using the example code supplied I had it up and working both on my development box and live well within 5 minutes. This included wiring it in to an example data entry form.

Once you have a simple page up and working you need to know how to tweak the defaults to your liking. Well, tweakers are well served. There are enough options and variations of features in the design time environment to keep anyone happy.

Technical support is through email and online, with sample code, a peer-to-peer discussion group and a constantly updated knowledgebase.

Conclusion

If your clients need to update site content and you can live with only supporting IE then this is definitely the product for you.