ASP: Definition and Function
Active Server Pages (ASP) is a proven, well-established technology for building dynamic Web applications that provide the power and flexibility you need to create anything from a personal Web based photo gallery, to a complete catalogue and shopping cart system. ASP enables HTML pages to be dynamic and interactive by embedding scripts, i.e. either VBScript, JScript, (Microsoft's JavaScript alternative) or JavaScript. Since the scripts in ASP pages (suffix .asp) are processed by the server, any browser can work with ASP pages regardless of the scripting language. This allows you to choose your favorite scripting language, i.e. JavaScript, JScript or VBScript (VBScript being the most popular). This article will provide you with the basic syntax of VBScript, including variables, operators, and control structures.
Related Links
- http://msdn.microsoft.com/default.asp
- http://www.4guysfromrolla.com/
- http://www.learnasp.com/
- http://www.15seconds.com/
Mail Server Settings
If you have written your own script to send an email or form from your website, you should use the following as your SMTP Server name:
auth.myhosting.com
Replace domain_name.com with your actual domain name.
Alternately, you can use your account's IP Address. Please do not use smtp.domain_name.com, as this is for use only for external SMTP such as sending email through your email software (Outlook, Eudora, etc.).
Using JMail
This code gives you the basics on how to send emails with ASP commands. You can send text or HTML, include CC and BCC recipients, and include any number of attachments. You can even send a text file or a complete HTML website as the content of your e-mail. Combined with its ability to receive and process e-mails, JMail is a component which gives your web site new dimensions of interactivity.
Send the Contents of a Form to Email
Below is a sample script describing how to send the content of a web form to an email address:
<%@LANGUAGE = VBSCRIPT%>
< html>
< body>
<%
'Collect form fields and their data
For Each x In Request.Form
message=message & x & ": " & Request.Form(x) & VBCrLf
Next
' Create the JMail message Object
set msg = Server.CreateObject( "JMail.Message" )
' Set logging to true to ease any potential debugging
' And set silent to true as we wish to handle our errors ourself
msg.Logging = true
msg.silent = true
' Most mailservers require a valid email address for the sender
msg.From = "THIS SHOULD BE YOUR E-MAIL ADDRESS"
msg.FromName = "THIS SHOULD BE YOUR NAME"
' Next we have to add some recipients.
msg.AddRecipient "YOUR FORM WILL BE SEND TO THE E-MAIL ADDRESS WRITTEN HERE"
' The subject of the message
msg.Subject = "CHANGE THE SUBJECT LINE OF THE MESSAGE"
' Note the use of VBCrLf to add linebreaks to our email
msg.Body = "Results of your web form:" & VBCrLf & VBCrLf & message & VBCrLf
' Replace YOUREMAILADDRESS with your email address that is hosted with myhosting.com
' and replace YOUREMAILPASSWORD with the password that is associated with
' that email address
msg.MailServerUserName = "YOUREMAILADDRESS"
msg.MailServerPassword = "YOUREMAILPASSWORD"
' To capture any errors which might occur, we wrap the call in an IF statement
if not msg.Send("auth.myhosting.com") then
'This message is displayed if an error occurs
Response.write "An error occured. Please contact the webmaster of this site."
else
'This message is displayed if the message has been sent successfully
Response.write "Thank you for your submission.... Your message has been delivered successfully."
end if
' And we're done! the message has been sent.
%>
< /body>
< /html>
Customizations
You can further customize the script to reflect the following issues:
Edit JMail Output
Question: I am having some trouble with the output from my forms processor. It does not seem to read the form objects from top to bottom, but instead returns them in a different order.
Answer: This is the order the server receives the data from the browser. You can customize how the data is interpreted by changing sendmail.asp as follows:
For Each x In Request.Form
message=message & x & ": " & Request.Form(x) & VBCrLf
Next
(do not delete <% on top),
then add
name = Request.Form ("name")
surname = Request.Form ("surname")
message = message & "Name: " & name & VBCrLf
message = message & "Surname: " & surname & VBCrLf
The above example assumes you have two form fields with names "name" and "surname". It gets their values from the form fields, and assigns them to variables and inserts the values into the message. Likewise, add all your form field names that you want to include in the e-mail. This way you have the full control to the order.
Edit Form to work with JMail
Question: Exactly where in the order form HTML code is the CGI statement inserted so that we can receive orders from internet customers in our e-mail?
Answer: At the start of the form, refer to sendmail.asp in your form as
<FORM NAME="yourformname" METHOD="post" ACTION="/cgi-bin/sendmail.asp"
Change Response to Redirect
Question: Can I customize my response after the form is submitted, instead of displaying simple text on the screen?
Answer: Yes you can. Instead of writing a simple text on screen, it can be redirected to another page. This can be done thru modifying the following code:
else
'This message is displayed if the message has been sent successfully
Response.write "Thank you for your submission.... Your message has been delivered successfully."
should be changed to
else
'This message is displayed if the message has been sent successfully
Response.Redirect ("../thankyou.html")
This change will display thankyou.html in your root directory after the message has been sent successfully.
ASP Database Connection using DSN
Connecting to an Access database using a DSN is fairly simple. To connect to the database using a DSN, all you need to do is setup and open the connection and select the records.
Listed below are some lines of code you will need to connect to the database using the DSN:
Set con = Server.CreateObject('ADODB.Connection')'Creates an ADO connection object.
con.Open 'DSN=;UID=;PWD;'
'Opens the connection to the DSN. If the database is located in a password-protected area you will need to enter the username and password for the connection to work correctly.
strconnect = 'Select * from '
'Selects the criteria from the query that you have entered from the table that you have specified.
Set objRS = con.Execute(strconnect)
'Executes the variable's select statement.
Example: Listed below is a sample script that will connect to an Access database via the DSN. It will return the first name, last name, and department of each record in the table.
<%
Option Explicit
Response.Expires = 0
Response.Write ("")
Dim con, objRS, strconnect
Set con = Server.CreateObject ("ADODB.Connection")
con.Open "DSN=testing;UID=;PWD=;"
strconnect = "Select * From personnel"
Set objRS = con.Execute(strconnect)
Response.Write ("List of people stored in the Personnel table are listed below:") Response.Write (" ")
While Not objRS.EOF Response.Write objRS("First_Name") &
objRS("Last_Name") & objRS("Department")
Response.Write (" ") objRS.MoveNext
Wend objRS.close
con.Close
Set objRS = Nothing Set
con = Nothing
%>
Using FileSystemObject
Here is the information on how to use the FileSystemObject.
Working with Files:
There are two major categories of file manipulation:
- Creating, adding, or removing data, reading files
- Moving, copying, and deleting files
Creating Files
There are three ways to create an empty text file (sometimes referred to as a "text stream").
The first way is to use the CreateTextFile method. The following example demonstrates how to create a text file using this method in VBScript:
Dim fso, f1
Set fso = CreateObject("Scripting.FileSystemObject")
Set f1 = fso.CreateTextFile("c:\testfile.txt", True)
To use this method in JScript, use this code:
var fso, f1;
fso = new ActiveXObject("Scripting.FileSystemObject");
f1 = fso.CreateTextFile("c:\\testfile.txt", true);
The second way to create a text file is to use the OpenTextFile method of the FileSystemObject object with the ForWriting flag set. In VBScript, the code looks like this example:
Dim fso, ts
Const ForWriting = 2
Set fso = CreateObject("Scripting. FileSystemObject")
Set ts = fso.OpenTextFile("c:\test.txt", ForWriting, True)
To create a text file using this method in JScript, use this code:
var fso, ts;
var ForWriting= 2;
fso = new ActiveXObject("Scripting.FileSystemObject");
ts = fso.OpenTextFile("c:\\test.txt", ForWriting, true);
A third way to create a text file is to use the OpenAsTextStream method with the ForWriting flag set. For this method, use the following code in VBScript:
Dim fso, f1, ts
Const ForWriting = 2
Set fso = CreateObject("Scripting.FileSystemObject")
fso.CreateTextFile ("c:\test1.txt")
Set f1 = fso.GetFile("c:\test1.txt")
Set ts = f1.OpenAsTextStream(ForWriting, True)
In JScript, use the code in the following example:
var fso, f1, ts;
var ForWriting = 2;
fso = new ActiveXObject("Scripting.FileSystemObject");
fso.CreateTextFile ("c:\\test1.txt");
f1 = fso.GetFile("c:\\test1.txt");
ts = f1.OpenAsTextStream(ForWriting, true);
Adding Data to the file
Once the text file is created, add data to the file using the following three steps:
- Open the text file.
- Write the data.
- Close the file.
To open an existing file, use either the OpenTextFile method of the FileSystemObject object or the OpenAsTextStream method of the File object.
To write data to the open text file, use the Write, WriteLine, or WriteBlankLines methods of the TextStream object, according to the tasks outlined in the following table.
Task |
Method |
Write data to an open text file without a trailing newline character. |
Write |
Write data to an open text file with a trailing newline character. |
WriteLine |
Write one or more blank lines to an open text file. |
WriteBlankLines |
To close an open file, use the Close method of the TextStream object.
NOTE: The newline character contains a character or characters (depending on the operating system) to advance the cursor to the beginning of the next line (carriage return/line feed). Be aware that the end of some strings may already have non-printing characters.
The following VBScript example demonstrates how to open a file, use all three write methods to add data to the file, and then close the file:
Sub CreateFile()
Dim fso, tf
Set fso = CreateObject("Scripting.FileSystemObject")
Set tf = fso.CreateTextFile("c:\testfile.txt", True)
' Write a line with a newline character.
tf.WriteLine("Testing 1, 2, 3.")
' Write three newline characters to the file.
tf.WriteBlankLines(3)
' Write a line.
tf.Write ("This is a test.")
tf.Close
End Sub
This example demonstrates how to use the three methods in JScript:
function CreateFile()
{
var fso, tf;
fso = new ActiveXObject("Scripting.FileSystemObject");
tf = fso.CreateTextFile("c:\\testfile.txt", true);
// Write a line with a newline character.
tf.WriteLine("Testing 1, 2, 3.") ;
// Write three newline characters to the file.
tf.WriteBlankLines(3) ;
// Write a line.
tf.Write ("This is a test.");
tf.Close();
}
Reading Files
To read data from a text file, use the Read, ReadLine, or ReadAll method of the TextStream object. The following table describes which method to use for various tasks.
Task |
Method |
Read a specified number of characters from a file. |
Read |
Read an entire line (up to, but not including, the newline character). |
ReadLine |
Read the entire contents of a text file. |
ReadAll |
If you use the Read or ReadLine method and want to skip to a particular portion of data, use the Skip or SkipLine method. The resulting text of the read methods is stored in a string which can be displayed in a control, parsed by string functions (such as Left, Right, and Mid), concatenated, and so forth.
The following VBScript example demonstrates how to open a file, write to it, and then read from it:
Sub ReadFiles
Dim fso, f1, ts, s
Const ForReading = 1
Set fso = CreateObject("Scripting.FileSystemObject")
Set f1 = fso.CreateTextFile("c:\testfile.txt", True)
' Write a line.
Response.Write "Writing file <br>"
f1.WriteLine "Hello World"
f1.WriteBlankLines(1)
f1.Close
' Read the contents of the file.
Response.Write "Reading file <br>"
Set ts = fso.OpenTextFile("c:\testfile.txt", ForReading)
s = ts.ReadLine
Response.Write "File contents = '" & s & "'"
ts.Close
End Sub
This code demonstrates the same in JScript:
function ReadFiles()
{
var fso, f1, ts, s;
var ForReading = 1;
fso = new ActiveXObject("Scripting.FileSystemObject");
f1 = fso.CreateTextFile("c:\\testfile.txt", true);
// Write a line.
Response.Write("Writing file <br>");
f1.WriteLine("Hello World");
f1.WriteBlankLines(1);
f1.Close();
// Read the contents of the file.
Response.Write("Reading file <br>");
ts = fso.OpenTextFile("c:\\testfile.txt", ForReading);
s = ts.ReadLine();
Response.Write("File contents = '" + s + "'");
ts.Close();
}
Moving, Copying, and Deleting Files
The FSO object model has two methods each for moving, copying, and deleting files, as described in the following table.
Task |
Method |
Move a file |
File.Move or FileSystemObject.MoveFile |
Copy a file |
File.Copy or FileSystemObject.CopyFile |
Delete a file |
File.Delete or FileSystemObject.DeleteFile |
The following VBScript example creates a text file in the root directory of drive C, writes some information to it, moves it to a directory called \tmp, makes a copy of it in a directory called \temp, then deletes the copies from both directories.
To run the following example, create directories named \tmp and \temp in the root directory of drive C:
Sub ManipFiles
Dim fso, f1, f2, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set f1 = fso.CreateTextFile("c:\testfile.txt", True)
Response.Write "Writing file <br>"
' Write a line.
f1.Write ("This is a test.")
' Close the file to writing.
f1.Close
Response.Write "Moving file to c:\tmp <br>"
' Get a handle to the file in root of C:\.
Set f2 = fso.GetFile("c:\testfile.txt")
' Move the file to \tmp directory.
f2.Move ("c:\tmp\testfile.txt")
Response.Write "Copying file to c:\temp <br>"
' Copy the file to \temp.
f2.Copy ("c:\temp\testfile.txt")
Response.Write "Deleting files <br>"
' Get handles to files' current location.
Set f2 = fso.GetFile("c:\tmp\testfile.txt")
Set f3 = fso.GetFile("c:\temp\testfile.txt")
' Delete the files.
f2.Delete
f3.Delete
Response.Write "All done!"
End Sub
This code shows the same in JScript:
function ManipFiles()
{
var fso, f1, f2, s;
fso = new ActiveXObject("Scripting.FileSystemObject");
f1 = fso.CreateTextFile("c:\\testfile.txt", true);
Response.Write("Writing file <br>");
// Write a line.
f1.Write("This is a test.");
// Close the file to writing.
f1.Close();
Response.Write("Moving file to c:\\tmp <br>");
// Get a handle to the file in root of C:\.
f2 = fso.GetFile("c:\\testfile.txt");
// Move the file to \tmp directory.
f2.Move ("c:\\tmp\\testfile.txt");
Response.Write("Copying file to c:\\temp <br>");
// Copy the file to \temp.
f2.Copy ("c:\\temp\\testfile.txt");
Response.Write("Deleting files <br>");
// Get handles to files' current location.
f2 = fso.GetFile("c:\\tmp\\testfile.txt");
f3 = fso.GetFile("c:\\temp\\testfile.txt");
// Delete the files.
f2.Delete();
f3.Delete();
Response.Write("All done!");
}
"Error - Cannot update. Database or object is read-only."
While using ASP pages, you may encounter one of the follow errors messages:
Microsoft OLE DB Provider for ODBC Drivers error '80004005'
[Microsoft][ODBC Microsoft Access Driver] Can't update. Database or object is read-only.
Microsoft OLE DB Provider for ODBC Drivers error '80004005'
[Microsoft][ODBC Microsoft Access Driver] Operation must use an updateable query.
These errors appear when an ASP script tries to access a database that doesn't have read/write/modify permissions set for it.
When a hosting account is first created, only /cgi-bin and /fpdb directories are given read/write/modify permissions. We suggest that you place your database in either of these two directories so that ASP scripts and write to the database. These folders also have the added security of not having "web read" access, meaning that a visitor is restricted from being able to download the entire database as they could a webpage.
If you need read/write/modify permissions applied to another directory, please send an e-mail to support@myhosting.com and specify the path of the directory you wish to change.
Displaying the Date using VBScript
Including the date and/or time on a web page can be a subtle yet valuable addition to your web site. The addition of the date to the home page can create the impression that a site is constantly being updated with new content as the current date will be displayed each time a user visits the page.
The following tutorial will teach you how to easily add the "date" and "time" feature to you ASP pages utilizing the VBScript "FormatDateTime()" function. We will explain how the function works, teach you how to integrate it into your ASP pages and illustrate the output you can expect depending on the arguments you pass through. Further, we will cover a few limitations that this function has.
NOTE: The following article assumes that you know basic HTML and how to add ASP scripts to your web pages.
The FormatDateTime() Function
Microsoft provides many predefined VBScript functions designed to reduce coding time. The FormatDateTime() function is one of those powerful functions and is really easy to use. This function uses the following format:
FormatDateTime(date, format)
There are two arguments the function accepts: "date" and "format". The table below describes these arguments in greater detail:
The FormatDateTime() function and its arguments
Argument |
Argument Description |
||
Date |
This argument is required and can be any valid date expression such as Date or Now |
||
Format |
This format constant or format value specifies how the date and/or time will be displayed on your ASP page. |
||
|
Constant |
Format Value |
Format Description |
|
vbGeneralDate |
0 |
This is the default. Not specifying a value or specifying 0 will produce a date in the format of mm/dd/yy. If the date expression is Now, it will also return the time, after the date, in hh:mm:ss PM/AM format. |
|
vbLongDate |
1 |
Passing this value will produce a date in the format of
|
|
vbShortDate |
2 |
Passing this value returns a date formatted just like the default of 0 (mm/dd/yy). |
|
vbLongTime |
3 |
Passing this value returns the time in hh:mm:ss PM/AM format. |
|
vbShortTime |
4 |
Passing this value returns military time in this format hh:mm |