Está en la página 1de 36

ASP Introduction

Active Server Pages (ASP) is a server side scripting language that lets a webmaster transform the plain, static web site into a dazzling, dynamic solution. With Microsoft's server side scripting language you can gather data from your site's visitors, use sessions, cookies, application variables, and more. Don't worry if you don't know what all of those terms mean because you will soon be learning all about them.

Is ASP a Complete Solution?


While ASP is quite useful, it is not a stand alone solution. Rather, ASP is a supplement to HTML (and CSS and even Javascript) and your final ASP code will often contain bits of pieces of code that are not ASP. If you had ever wanted to take orders, gather emails, or make a decent guestbook, ASP will provide you the necessary tools to complete these tasks.

What You Need to Know


Before you start in on Tizag's ASP Tutorial, it is recommended that you have a strong grasp of HTML, as this tutorial will not explain the HTML code in any great depth. If your HTML knowledge could use a touchup, check out our HTML Tutorial or for the complete HTML Beginner: First Web Site Walkthrough. This ASP Tutorial is quite long, so do not try to take it on all at once. We find that reading a couple lessons at one sitting and then giving yourself time to reflect on what you learned really helps to understand the subject better. Good luck!

Installing ASP
ASP (Active Server Pages) is part of the Internet Information Server (IIS) package that comes with certain Microsoft operating systems. Currently there is no native support for ASP on the other operating systems, such as: Mac OS, Linux, and Unix. The operating systems that do have the ability to support ASP are: Windows 95, 98, NT, 2000, 2003, XP Pro. You will notice that XP Home Edition was not on the list of operating systems, and this was done intentionally by Microsoft to encourage people to purchase the more expensive XP Professional Edition. This lesson will provide an installation walkthrough for Windows 98 and Windows XP Pro. Note: Chilisoft does have a solution for some Linux and Solaris users and can be purchased at Sun's web site: Sun Java System Active Server Pages 4.0.

Installing ASP and IIS on Windows XP Professional


First locate your XP Professional CD and put it into your CD-ROM then follow these steps: 1. 2. 3. 4. 5. 6. 7. Open your control panel. Click Start -> then Settings -> then Control Panel Select and Open "Add or Remove Programs" On the left column of the popup window select "Add or Remove Windows Components" Scroll down until you see Internet Information Services (IIS) If IIS is not checked then check it, otherwise you already have IIS installed on your computer Click Next and follow the on screen instructions from the installer When it has completed, open up Internet Explorer and type in http://localhost

8. If IIS was install appropriately you should be taken to the welcome screen http://localhost/localstart.asp

Tizag's Setup
This tutorial was written on XP Professional, but any of you using Windows 98 or other Windows derivatives should have no problem following along. If you do encounter a specific problem, please feel free to Contact Us.

Running an ASP Web Page


If you do not know where to save and run your ASP web pages from, this lesson will guide you through the process. In the previous lesson we installed Microsoft's Server software (IIS or PWS) to enable your computer to run .asp files. However, having IIS or PWS installed is not enough to run ASP files. The next step you must complete is to save and run your ASP files from a special location on your hard drive: the Inetpub directory to be specific. Follow these steps to navigate to this directory: 1. Open up "My Computer" or "Windows Explorer" so that you can view your system's files and directories. 2. Select and Open the C drive (C:) 3. Double click the Inetpub folder 4. Double click the wwwroot folder - The full path to this location is "C:\Inetpub\wwwroot" for you advanced users 5. Within the wwwroot directory locate the "localstart.asp" file. This is the same file you saw after completing the installation in the previous lesson. Your ASP files will have to go into this wwwroot directory or a contained sub-directory to run properly.

Creating ASP Testing Grounds


Throughout this tutorial we will be referring to the folder "tizagASP" that you should create if you want to follow along with these ASP Tutorials.

Inside the wwwroot folder create a New Folder and rename it "tizagASP" To access this directory you would type the following into Internet Explorer: o http://localhost/tizagASP/FILENAME.asp Where FILENAME is name of your ASP file

All of the files you create while reading the ASP Tutorial should go into this directory.

Tips
1. Be sure to save your ASP files in a folder that exists inside C:\Inetpub\wwwroot 2. Tizag ASP Tutorial saves file to C:\Inetpub\wwwroot\tizagASP 3. Run your ASP files by using Internet Explorer and typing "http://localhost/tizagASP/FILENAME.asp" without quotes and replace FILENAME with the name of your specific ASP file

Your First ASP Script

Before we get into the meat and potatoes of ASP programming let's just run a very simple ASP script to check that your IIS installation and ASP are working properly. Open up a text editor and type the following ASP Code and save the file as "firstscript.asp".

firstscript.asp ASP Code:


<% Response.Write("Hello Me") %>

Be sure to save this file to the directory "tizagASP" as was mentioned in the previous lesson, Running ASP. Launch Internet Explorer and type the following into the address bar:

http://localhost/tizagASP/firstscript.asp

If you see the following...

Internet Explorer Display:


Hello Me ...then you've got all the file saving and running mumbo jumbo figured out and you can start focusing on learning ASP! Now let's continue!

ASP Syntax
If you have any experience with PHP, Javascript, or general programming then ASP's syntax will make some sense to you. However, if you only have experience with web technologies like HTML and CSS, then ASP will be more of a challenge.

ASP Syntax: Wrappers


Just how HTML uses tags to create web pages, ASP needs tags to create dynamic web sites. These tags do not resemble the typical tags used in HTML, so be sure you notice the difference between tags used for ASP and tags used for HTML. Below is the ASP script we used in the previous lesson.

ASP Code:
<html> <body> <% Response.Write("Hello Me") %> </body> </html>

ASP - Tags

These special tags <% and %> will always encapsulate your ASP code. Some things about the ASP tag that sets it apart from normal HTML tags: 1. An opening ASP tag is <% while an HTML tag normally looks like <tagname> 2. A closing ASP tag looks like %> while an HTML tag normally looks like </tagname> 3. ASP code can occurr anywhere, even within an HTML tag opening tag like this:

ASP Code:
<a href="<% Response.Write("index.asp") %>">Home</a>

Display:
Home

ASP Syntax - Script Dependent


Besides the ASP Tag wrapper, the rest of ASP's syntax is dependent on which scripting language you are using in your ASP code. The default setting for ASP is VBScript, a scripting language based off of Visual Basic. However, you can also use non-Microsoft scripting languages, the most popular option being Javascript. The following two lessons will be talking about coding ASP with the aide of both these scripting languages.

ASP Programming - VBScript


As was mentioned in the last lesson, ASP uses VBScript as its default scripting language. VBScript is similar to Javascript, a client side programming language used to add functionality through the <script> tag. Read the following paragraph carefully! VBScript, when used to program ASP converts it to server side scripting. Any given web page could be created from a combination of server side and client side scripting. The confusing part is this: You must use these client side scripting languages (Javascript, VBScript, etc) to program in ASP! Below we have a simple ASP script programmed in VBScript and includes the necessary HTML as well. This is only server-side scripting.

Server Side ASP Code using VBScript:


<html> <body> <% Dim myString myString = Date() Response.Write("The date is: " & myString) %> </body> </html>

Display:
The date is: 9/28/2011 If you already know VBScript or Visual Basic programming then you'll recognize Dim as Dimension, which is used to "dimension" variables. It is a good programming practice to "dimension" all your variables before you use them, as we did with myString in the above example. Now that we have our ASP Code working, say that we wanted to use our ASP code along with some client side Javascript code. To keep it simple we are just going to use the Javascript write function and have our ASP

Code fill in the Date. All the Javascript client code is in the default color, but ASP Server Side Code is in Red.

ASP Code with VBScript and Client Side Javascript Code:


<script> document.write("The date is:<% Dim myString myString = Date() Response.Write(myString) %>") </script>

Display:
The date is: 9/28/2011 If you just want to program in ASP you can disregard the above example if you find it confusing. Just remember that you can have client-side Javascript code and server-side ASP/VBScript code included in an ASP generated web page!

Programming ASP with VBScript


You should be able to follow along with our ASP tutorial with little or no VBScript knowledge, but just in case you want to know more or find some of the VBScript syntax or code confusing then you can check out our VBScript Tutorial.

Programming ASP in Javascript


VBScript is the default scripting language that ASP is coded in, so if you want to specify a different scripting language you have to state which scripting language you will be using at the very beginning of your code. Below is the line of code that must be your first line of ASP code or else your page will break and you'll get a boring error message.

ASP Code:
<%@ Language="javascript" 'The rest of your ASP Code....%>

Remember, if this isn't your first line of ASP code then everything will break.

Learning Javascript
If you don't already know javascript very well, then it is probably a good idea if you just learn VBScript instead of trying to get ASP to work with javascript. I have heard of many fellows having trouble getting ASP to cooperate properly with Javascript and there just isn't that many informative examples of programming ASP with Javascript available. Your ASP career will be much more pleasant if you simply stick with VBScript from the get go.

ASP Operators
ASP is programmed in VBScript by default, thus ASP's operators are VBScript operators by default. Operators in ASP fall into four categories Math, Comparisons, the somewhat more advanced Logic operators, and Leftovers(those that don't fit well into any category).

ASP Arithmetic Operators


The mathematical operators in ASP are similar to many other programming languages. However, ASP does not support shortcut operators like ++, --, +=, etc. Operator + * / ^ Mod \ English Addition Subtraction Multiplication Division Exponential Modulus Negation Integer Division Example myNum = 3 + 4 myNum = 4 - 1 myNum = 3 * 2 myNum = 9 / 3 myNum = 2 ^ 4 myNum = 23 Mod 10 myNum = -10 myNum = 9 \ 3 Result myNum = 7 myNum = 3 myNum = 6 myNum = 3 myNum = 16 myNum = 3 myNum = -10 myNum = 3

Comparison Operators
Comparison operators are used when you want to compare two values to make a decision. Comparison operators are most commonly used in conjunction with "If...Then" and "While something is true do this..." statements, otherwise known as conditional statements. The items that are most often compared are numbers. The result of a comparison operator is either TRUE or FALSE. Operator = < > <= >= <> Example Result Equal To 4=3 False Less Than 4<3 False Greater Than 4>3 True Less Than Or Equal To 4 <= 3 False Greater Than Or Equal To 4 >= 3 True Not Equal To 4 <>3 True English

Logical Operators
The above comparison operators result in a truth value of TRUE or FALSE. A logical operator is used for complex statements that must make decisions based on one or more of these truth values. Operator English Example Result And Both Must be TRUE True and False False

Or Not

One Must be TRUE True or False Flips Truth Value Not True

True False

String Operators
The only string operator is the string concatenation operator "&" that takes two strings and slams them together to form a new string. An example would be string1 = "Tim" and string2 = " is a Hero". The following code would combine these two strings into one: string3 = string1 & string2 Operator English Example Result & String Concatenation string4 = "Bob" & " runs" string4 = "Bob runs" We will be using these operators throughout the tutorial, so chances are you will get understand them more and more as this tutorial goes on.

ASP - If Statement
An If Statement is used to make a decision in your ASP program to execute certain code if some condition is True. Because ASP is programmed in VBScript by default, when you program an ASP If Statement it is actually the same as programming a VBScript If Statement.

If Statement Syntax
ASP's If Statement is slightly different than the If Statement implementation in most other languages. There are no brackets, or curly braces, nor are there any parenthesis. Rather the beginning of the code to be executed in the If Statement when its true is marked with Then and the end of the If Statement is plainly marked with End If. Below is a very basic If Statement that will always be True.

ASP Code:
<% Dim myNum myNum = 6 If myNum = 6 Then Response.Write("Variable myNum = 6") End If %>

Display:
Variable myNum = 6 You might notice that the "=" operator is used to both set the value of myNum to 6 at first, then it is used to compare myNum to 6 in our If Statement. This dual use of the equals operator is confusing to many, but it might help you to remember that in ASP you cannot set the value of variables within If Statements, which means that the "=" can only compare!

ASP - If Else Conditional Statement

Sometimes you might want to execute some code both when the If Statement is True and some different code when it is False. Just like other programming languages, you can do this in ASP with the use of the Else keyword. Below is an example that will always be false, so that the Else portion of the If Statement is always executed.

ASP Code:
<% Dim myNum myNum = 23 If myNum = 6 Then Response.Write("Variable myNum = 6") Else Response.Write("**Variable myNum = " & myNum) End If %>

Display:
**Variable myNum = 23

ASP - ElseIf Conditional Statement


With a normal If Statement you can only check one condition, but at times you will want to check for multiple conditions. In ASP you can do this with ElseIf, which is the name given to an If Statement that depends on another If Statement. Think about it in plain english: If something is true Then do this ElseIf second something is true Then do this, etc. You may have used the ElseIf condition statement in other programming languages, but if not just know that you cannot have an ElseIf statement without first having an if statement. Below is an example whose second if statement (elseif) is always true.

ASP Code:
<% Dim myFastfood myFastfood = "JBox" If myFastfood = "McD's" Then Response.Write("Happy Meal Por Favor!") ElseIf myFastfood = "JBox" Then Response.Write("Two tacos please!") Else Response.Write("Foot-long turkey sub.") End If %>

Display:
Two tacos please!

ASP Select Case


In the previous lesson you learned how to setup a block of If Statements using the ElseIf keyword, but this is not the most efficient method for checking multiple conditions. ASP uses the Select Case statement to check for multiple Is Equal To "=" conditions of a single variable. If you are an experienced programmer you realize the Select statement resembles a Switch statement that other programming languages use for an efficient way to check a large number of conditions at one time.

ASP Select Case Example


The variable that appears immediately after Select Case is what will be checked against the list of case statements. These case statements are contained within the Select Case block of code. Below is an ASP Select Case example that only checks for integer values. Later we will show how to check for strings.

ASP Code:
<% Dim myNum myNum = 5 Select Case myNum Case 2 Response.Write("myNum Case 3 Response.Write("myNum Case 5 Response.Write("myNum Case Else Response.Write("myNum End Select %>

is Two") is Three") is Five") is " & myNum)

Display:
myNum is Five

ASP Select Case - Case Else


In the last example you might have noticed something strange, there was a case that was referred to as "Case Else". This case is actually a catch all option for every case that does not fit into the defined cases. In english it might be thought of as: If all these cases don't match then I'll use the "Case Else"! It is a good programming practice to always include the catch all Else case. Below we have an example that always executes the Else case.

ASP Code:
<% Dim myNum myNum = 454 Select Case myNum Case 2 Response.Write("myNum Case 3 Response.Write("myNum Case 5 Response.Write("myNum Case Else Response.Write("myNum End Select %>

is Two") is Three") is Five") is " & myNum)

Display:
myNum is 454

Select Case with String Variables

So far we have only used integers in our Select Case statements, but you can also use a string as the variable to be used in the statement. Below we Select against a string.

ASP Code:
<% Dim myPet myPet = "cat" Select Case myPet Case "dog" Response.Write("I own a dog") Case "cat" Response.Write("I do not own a cat") Case Else Response.Write("I once had a cute goldfish") End Select %>

Display:
I do not own a cat

ASP Variables - VBScript


ASP is not a language in itself. To program ASP you actually need to know the VBScript scripting language. This means that all VBScript variable rules can be applied to your ASP code. This lesson will teach you the basics of Variables in ASP and some good programming conventions. If you would like to know more about VBScript check out our VBScript Tutorial.

Declaring a Variable in ASP


It is a good programming practice to declare all your variables before you use them, even though it is not required. Nearly all programming languages require you to declare variables and doing so also increases your program's readability. In ASP you declare a variable with the use of the Dim keyword, which is short for Dimension. Dimension in english refers to the amount of space something takes up in the real world, but in computer terms it refers to space in computer memory. Variables can be declared one at a time or all at once. Below is an example of both methods.

ASP Code:
<% 'Single Variable Declarations Dim myVar1 Dim myVar2 'Multiple Variable Declarations Dim myVar6, myVar7, myVar8 %>

ASP Variable Naming Conventions


Once again, ASP uses VBScript by default and so it also uses VBScripts variable naming conventions. These rules are:

1. 2. 3. 4.

Variable name must start with an alphabetic character (A through Z or a through z) Variables cannot contain a period Variables cannot be longer than 255 characters (don't think that'll be a problem!) Variables must be unique in the scope in which it is declared (Basically, don't declare the same variable name in one script and you will be OK).

ASP - Assigning Values to ASP Variables


Assigning values in ASP is straightforward enough, just use the equals "=" operator. Below we have set a variable equal to a number and a separate variable equal to a string.

ASP Code:
<% 'Single Variable Declarations Dim myString, myNum, myGarbage myNum = 25 myString = "Hello" myGarbage = 99 myGarbage = "I changed my variable" Response.Write("myNum = " & myNum & "<br />") Response.Write("myString = " & myString & "<br />") Response.Write("myGarbage = " & myGarbage & "<br />") %>

Display:
myNum = 25 myString = Hello myGarbage = I changed my variable

ASP Arrays
Arrays in ASP follow the exact same form and rules as those arrays in VBScript. You can create an array of specific size or you can create a dynamic sized array. Below we have examples of both types of arrays.

ASP Code:
<% Dim myFixedArray(3) 'Fixed size array Dim myDynArray() 'Dynamic size array %> We are going to focus on fixed size arrays first and cover dynamic arrays later on in this lesson.

Assigning Values to an Array


Let's fill up our fixed size array with values. Our fixed array is going to store the names of famous people. To assign a value to an array you need to know three things:

The name of the array The value you want to store The position in the array where you want to store the value.

An array is a group of variables that you can access by specifying the position inside the array. Our array myFixedArray has four positions: 0, 1, 2 and 3. Let's assign some values to our array.

ASP Code:
<% Dim myFixedArray(3) 'Fixed size array myFixedArray(0) = "Albert Einstein" myFixedArray(1) = "Mother Teresa" myFixedArray(2) = "Bill Gates" myFixedArray(3) = "Martin Luther King Jr." %>

ASP Arrays are Zero Based!


If you're a programmer you might look at that above example and thing "Hey, you only allocated three elements for that array, but you assigned four values! Well, this can be done because arrays in ASP are zero based. This means when you declare fixed array of size X then you can assign values for each value from 0 through X. Below is perfectly functional ASP code that will go through our array and print out the contents of each element. Don't worry if you are confused by this new for loop code it will be taught later.

ASP Code:
<% Dim myFixedArray(3) 'Fixed size array myFixedArray(0) = "Albert Einstein" myFixedArray(1) = "Mother Teresa" myFixedArray(2) = "Bill Gates" myFixedArray(3) = "Martin Luther King Jr." For Each item In myFixedArray Response.Write(item & "<br />") Next %>

Display:
Albert Einstein Mother Teresa Bill Gates Martin Luther King Jr.

ASP Dynamic Sized Arrays


To create an array whose size can be changed at any time simply do not put a number within the parenthesis when you declare the array. When you know what size you want the array to be use the ReDim keyword. You may ReDim as many times as you wish. If you want to keep your data that already exists in the array then use the Preserve keyword. Below is an example of all these things we have just talked about.

ASP Code:
<% Dim myDynArray() 'Dynamic size array ReDim myDynArray(1) myDynArray(0) = "Albert Einstein" myDynArray(1) = "Mother Teresa" ReDim Preserve myDynArray(3) myDynArray(2) = "Bill Gates" myDynArray(3) = "Martin Luther King Jr." For Each item In myDynArray Response.Write(item & "<br />") Next %>

Display:
Albert Einstein Mother Teresa Bill Gates Martin Luther King Jr.

ASP Session
The Session Object in ASP is a great tool for the modern web site. It allows you to keep information specific to each of your site's visitors. Information like username, shopping cart, and location can be stored for the life of the session so you don't have to worry about passing information page to page. In old web page designs you might have to try to pass information this information through HTML Forms or other methods.

ASP Session Object


Contained within the Session Object are several important features that we will talk about in this lesson. The most important thing to know about ASP's Session Object is that it is only created when you store information into the Session Contents collection. We will now look into creating and storing information in an ASP Session.

ASP Session Variables


To store a Session Variable you must put it into the Contents collection, which is very easy to do. If you have already read the ASP Arrays Lesson then this bit of code will be a cinch! Here we are saving the Time when someone visited this page into the Session Contents collection and then displaying it .

ASP Code:
<% 'Start the session and store information Session("TimeVisited") = Time() Response.Write("You visited this site at: " & Session("TimeVisited")) %>

Display:
You visited this site at: 10:47:14 PM Here we are creating two things actually: a key and a value. Above we created the key "TimeVisited" which we assigned the value returned by the Time() function. Whenever you create a Session Variable to be stored in the Session Contents collection you will need to make this Key / Value pair.

ASP Session ID
The ASP Session ID is the unique identifier that is automatically created when a Session starts for a given visitor. The Session ID is a property of the Session Object and is rightly called the SessionID property. Below we store the user's SessionID into a variable.

ASP Code:
<% Dim mySessionID

mySessionID = Session.SessionID %>

ASP Session Timeout


A Session will not last forever, so eventually the data stored within the Session will be lost. There are many reasons for a Session being destroyed. The user could close their browser or they could leave their computer for an extended amount of time and the Session would time out. You can set how long it takes, in minutes, for a session to time out with the Timeout property. Below we set our session to timeout after 240 minutes, which should be more than enough time for most web sites.

ASP Code:
<% Session.Timeout = 240 Response.Write("The timeout is: " & Session.Timeout) %>

Display:
The timeout is: 240 Note: Timeout is defined in terms of minutes.

ASP Cookies
Like ASP Sessions, ASP Cookies are used to store information specific to a visitor of your website. This cookie is stored to the user's computer for an extended amount of time. If you set the expiration date of the cookie for some day in the future it will remain their until that day unless manually deleted by the user. If you have read through the Sessions lesson you will notice that ASP Cookies code has several similarities with ASP Sessions.

ASP Create Cookies


Creating an ASP cookie is exactly the same process as creating an ASP Session. Once again, you must create a key/value pair where the key will be the name of our "created cookie". The created cookie will store the value which contains the actual data.In this example we will create a cookie named brownies that stores how many brownies we ate during the day.

ASP Code:
<% 'create the cookie Response.Cookies("brownies") = 13 %>

Now that we've created this cookie, how do we get that information back from the user's computer?

ASP Retrieving Cookies


To get the information we have stored in the cookie we must use the ASP Request Object that provides a nice method for retrieving cookies we have stored on the user's computer. Below we retrieve our cookie and print out its value.

ASP Code:
<% Dim myBrownie 'get the cookie myBrownie = Request.Cookies("brownies") Response.Write("You ate " & myBrownie & " brownies") %>

Display:
You ate 13 brownies Note: Be sure you see that when you create a cookie you use Response.Cookies, but when you retrieve a cookie you use Request.Cookies.

ASP Cookie Expiration Date


Unlike real life cookies, in ASP you can set how long you want your cookies to stay fresh and reside on the user's computer. A cookie's expiration can hold a date; this date will specify when the cookie will be destroyed. In our example below we create a cookie that will be good for 10 days by first taking the current date then adding 10 to it.

ASP Code:
<% 'create a 10-day cookie Response.Cookies("brownies") = 13 Response.Cookies("brownies").Expires = Date() + 10 'create a static date cookie Response.Cookies("name") = "Suzy Q." Response.Cookies("name").Expires = #January 1,2009# %>

ASP Cookie Arrays or Collections


Up until now we have only been able to store one variable into a cookie, which is quite limiting if you wanted to store a bunch of information. However, if we make this one variable into a collection it can store a great deal more. Below we make a brownies collection that stores all sorts of information.

ASP Code:
<% 'create a big cookie Response.Cookies("brownies")("numberEaten") = 13 Response.Cookies("brownies")("eater") = "George" Response.Cookies("brownies")("weight") = 400 %>

ASP Retrieving Cookie Values From a Collection


Now to iterate through the brownies collection we will use a for each loop. See our for loop tutorial for more information.

ASP Code:
<% For Each key In Request.Cookies("Brownies") Response.Write("<br />" & key & " = " & _ Request.Cookies("Brownies")(key)) Next Response.Cookies("brownies")("numberEaten") = 13 Response.Cookies("brownies")("eater") = "George" Response.Cookies("brownies")("weight") = 400 %>

Display:
numberEaten = 13 eater = George weight = 400

ASP Strings
This lesson will tell you how to use strings in ASP. VBScript is the default scripting language for ASP, so if you know VBScript strings inside and out you will already know everything you're about to read!

ASP Creating a String


To create an ASP String you first declare a variable that you wish to store the string into. Next, set that variable equal to some characters that are encapsulated within quotations, this collection of characters is called a String. Below we set our variable myString equal to string of characters "Hello There!".

ASP Code:
<% Dim myString myString = "Hello There!" %>

ASP Concatenating Strings


Throughout your ASP programming career you will undoubtedly want to combine multiple strings into one. For example: you have someone's first and last name stored in separate variables and want to print them out as one string. In ASP you concatenate strings with the use of the ampersand (&) placed between the strings which you want to connect. Below we have set up this situation and added a twist. After we combine the names into one string we will be adding this string variable to the temporary string "Hello my name is ".

ASP Code:
<%

Dim fname, lname, name fname = "Teddy" lname = " Lee" name = fname & lname Response.Write("Hello my name is " & name) %>

Display:
Hello my name is Teddy Lee

ASP Concatenating Numbers


Besides just concatenating strings onto other strings you can just as easily add on numbers to strings, or numbers to numbers to make strings. Below are a couple of integer to string examples.

ASP Code:
<% Dim fname, myAge, myHeightM, allOfIt myAge = 7 myAge = myAge & 5 myHeightM = 2 fname = "Teddy" allOfIt = fname & " is " & myAge & " years old and " allOfIt = allOfIt & myHeightM & " meters tall" Response.Write(allOfIt) %>

Display:
Teddy is 75 years old and 2 meters tall

ASP Convert String to Date


To perform an ASP String to Date conversion you need to utilize the CDate function (stands for Convert Date). This will take a String that contains a date and change it into a properly formatted ASP Date. In our example below we create a string, check to see if it can be converted into a date with isDate and then perform the conversion.

ASP Code:
<% Dim myStringDate, myTrueDate myStringDate = "August 18, 1920" If IsDate(myStringDate) Then myTrueDate = CDate(myStringDate) Response.Write(myTrueDate) Else Response.Write("Bad date formatting!") End If %>

Display:
8/18/1920 Our string myStringDate was a properly formatted date and was successfully converted and written to the browser.

ASP Forms
With ASP you can process information gathered by an HTML form and use ASP code to make decisions based off this information to create dynamic web pages. An ecommerce site could take the user's information and store it into a database named Customers. This information could then be used to prepopulate the shipping information when the customer is ordering another product. A forum might save the user's post to a forum by taking the title and body and saving it to a file so that it can then be called later when someone wants to view it.

Create an HTML Form


Before you can process the information, you need to create an HTML form that will send information to your ASP page. There are two methods for sending data to an ASP form: POST and GET. These two types of sending information are defined in your HTML Form element's Method attribute. Also, you must specify the location of the ASP web page that will process the information. If you would like to revisit HTML Forms check out our HTML Forms Lesson. Below is a simple form that will send the data using the GET method. Copy and paste this code and save it as as "tizagForm.html".

tizagForm.html Code:
<form method="GET" action="tizagGet.asp"> Name <input type="text" name="Name"/> Age <input type="text" name="Age"/> <input type="submit" /> </form>

tizagForm.html Display (not functional):


Name Age

Two Form Examples


The next two lessons will cover how to retrieve this HTML Form information using ASP. The first lesson will be for processing data sent with the GET and the second lesson will cover the details for processing POST data. Please continue on!

ASP Forms Get


When you pass information from an HTML form, using the Get method, to an ASP page from processing, you can retrieve the information using ASP's QueryString Collection. In the previous lesson we created "tizagForm.html" that sent information to "tizagGet.asp" for processing. Below is that HTML code.

tizagForm.html Code:
<form method="GET" action="tizagGet.asp"> Name <input type="text" name="Name"/> Age <input type="text" name="Age"/> <input type="submit" /> </form>

Now we need to create our ASP web page "tizagGet.asp" that will process this data.

ASP QueryString Variables


The form data we want resides within the Request Object's QueryString collection. In this collection there is an entry for each individual Form Input from our HTML Form. The input tag's name attribute is the key needed to access data for that Input element. Here we create a simple ASP processor that will store the contents of each the two items in our QueryString into variables and then print their values to the web page. Save your ASP file as "tizagGet.asp" and save it in the same directory as "tizagForm.html".

tizagGet.asp Code:
<% Dim name, age name = Request.QueryString("Name") age = Request.QueryString("Age") Response.Write("Name: " & name & "<br />") Response.Write("Age: " & age & "<br />") %>

ASP Get Simulation


After you have saved both files into a working ASP directory then if you were to enter the following information into "tizagForm.html" and submit you would get the following:

tizagForm.html Filled Out:


Name Age

tizagGet.asp Result:
Name: Fred Age: 52

ASP Form Post


The previous lesson ASP Form Get created an ASP page to process information sent through an HTML form with the GET method. In this lesson we will be examining how to process data sent via the POST method and see how it is different from the last lesson.

Altering Our HTML Form


Before we begin creating a new ASP file, we are going to have to change our "tizagForm.html" file to use the POST method and send the form data to a different ASP page. The example below provides the up-to-date code for "tizagForm.html".

Modified tizagForm.html Code:


<form method="POST" action="tizagPost.asp"> Name <input type="text" name="Name"/> Age <input type="text" name="Age"/> <input type="submit" /> </form>

Creating an ASP POST Processor


Our new ASP file will be called "tizagPost.asp" and will be saved in the same directory as "tizagForm.html". When the POST method is used to send data you retrieve the information with the Request Object's Form collection. So the only difference between a GET and POST processor is replacing all instances of QueryString with Form. In the example below we have made the correct changes and highlighted them in red.

tizagPost.asp Code:
<% Dim name, age name = Request.Form("Name") age = Request.Form("Age") Response.Write("Name: " & name & "<br />") Response.Write("Age: " & age & "<br />") %>

ASP POST Processing Simulation


Let's run through a quick simulation of our ASP processor. Try this on your computer and make sure it all works.

tizagForm.html Filled Out (not functional):


Name Age

tizagPost.asp Result:
Name: Jack Age: 15

ASP Email Form


You can easily add limited email functionality to your ASP programs using the Message object. The Message object is not very feature intensive, but this lesson will show you how to implement a basic email form on your ASP site. Experienced web masters might have noticed that whenever you put your email address onto the internet, so that your visitors can email you, you instantly get hit with tons of spam. This is most likely because a spammer's email finder application saw your email address and added it to their nasty hit list. You can receive emails from your visitors, without letting the general public know your email address, using what is taught in this lesson.

Quicky HTML Form


Before we start worrying about how to send the email, let's make a basic HTML form that will gather the following information from the user:

From To Subject Body

Our HTML file will be called "tizagEmailForm.html" and should be saved in a directory that can Run ASP.

tizagEmailForm.html Code:
<form method="POST" action="tizagEmail.asp"> To <input type="text" name="To"/> <br /> From <input type="text" name="From"/> <br /> Subject <input type="text" name="Subject"/> <br /> Body <textarea name="Body" rows="5" cols="20" wrap="physical" > </textarea> <input type="submit" /> </form>

If you would like a refresher on HTML Forms check out our HTML Forms Lesson.

ASP NewMail Object Death


Microsoft has made it rather confusing by changing their implementations of sending mail with ASP. In older ASP versions you would send mail with the NewMail Object. However, new versions of Microsoft's Internet Information Services (IIS) software has changed again to instead use the Message object.

ASP Mail Processor


Now that we have our handy dandy HTML Form we need to create the ASP file that will retrieve this data and shoot off an email. All the properties that are set in the following code are self-explanatory and write only. Also, because Message is an object, it must be Set equal to nothing after we have finished with it to release the memory allocated to it. The name of the ASP file is "tizagEmail.asp" and should be saved to the same directory as "tizagEmailForm.html".

tizagEmail.asp:
<% 'Sends an email Dim mail Set mail = Server.CreateObject("CDO.Message") mail.To = Request.Form("To") mail.From = Request.Form("From") mail.Subject = Request.Form("Subject") mail.TextBody = Request.Form("Body") mail.Send() Response.Write("Mail Sent!") 'Destroy the mail object! Set mail = nothing %>

Please note that this is a very basic ASP Email Form and is only for education purposes. If you were to put an email form on your web site you would want to do some checking to make sure the email addresses are valid, allow for attachments, etc.

ASP Object
Objects are a way of encapsulating multiple methods (they're like functions) and variables in one easy to manage Uber-Variable (an Object). Objects in ASP resemble other Object Oriented Programming languages. In this lesson we will be using the ASP CDO.Message object as our example object to be dissected.

ASP Object Overview


Objects were created to combat the increasing complexity of programming. The rationale for understanding and using Objects in your programming is to make programming easier and your code more human readable.

ASP Create an Object - Server.CreateObject


An object in ASP is created by passing a name string to the Server.CreateObject function(actually referred to as a method). The string to create a Message object is "CDO.Message". We will be creating a CDO.Message object in this example. Note: Because objects are special there is a special way that you create and destroy them using the Set keyword. These areas are marked in red in the example below.

ASP Code:
<% Dim myObject Set myObject = Server.CreateObject("CDO.Message") 'You must Set your objects to "nothing" to free up the 'the computer memory that was allocated to it Set myObject = nothing %>

That wasn't too painful, was it? Let's cover some more bases on the object model. Objects are a collection of related things that are combined into this blob of programming goo that can be created and destroyed whenever we may need it. For example say that you wanted to make an object that allowed you to send an email... Well there are certain things all emails have: To, From, CC, Subject, etc. This list of variables that are common to every email would be quite tiresome to have to create for every email we sent. Wouldn't it be nice if we could create some sort of Uber-Variable(Object) that would group all these smaller variables into one thing?

ASP Object Properties


These smaller variables are commonly referred to as an object's properties and the format for setting these properties is nearly identical to setting a variable equal to a value.

The correct syntax for setting an object's properties is:

objectName.propertyName = someValue

In this tiny example below we are creating a new mail object and setting its To and From properties.

ASP Code:
<% Dim myObject Set myObject = Server.CreateObject("CDO.Message") 'Then we set the To and From properties myObject.To = "little.timmy@example.com" myObject.From = "huge.jill@example.com" 'You must Set your objects to "nothing" to free up the 'the computer memory that was allocated to it Set myObject = nothing %>

Now I know we didn't DO anything in the above example, but we still need to learn a bit more about objects before we can get anything done! Objects, besides having a clump of associated common variables, may also have a collection of functions(which become referred to as methods) associated with them. These methods are processes that you would want to commonly do to either manipulate the variables of the object or to use the variables to do something. In our Message object we have a collection of information that, when put together into the proper email form and sent to an email service will become an email. All this complex code has been programmed by Microsoft employees and stored into the Message objects Send method.

ASP Object Methods


We cannot see the code that was used to program the Send method, but that's one of the great things about using object programming. You know what you need to know and nothing more. In our example below we create a Message object and set the necessary properties and send it off with the Send method.

ASP Code:
<% Dim myObject Set myObject = Server.CreateObject("CDO.Message") 'Then we set the To and From properties myObject.To = "little.timmy@example.com" myObject.From = "huge.jill@example.com" myObject.Subject = "Can you see me?" myObject.TextBody = "I'm really really big!" myObject.Send() 'You must Set your objects to "nothing" to free up the 'the computer memory that was allocated to it Set myObject = nothing %>

Note:If you are running this on your home computer there are a slough of issues that may arise with sending an email. Microsoft has a large FAQ about using the CDO.Message object that may help you. Knowing Microsoft, that link may go dead soon, so Contact Us if it expires!

ASP Object Summary


In this lesson you learned how to create and destroy an object in ASP. You also learned how to access the properties and utilize the methods of an object. If you still have no idea what this lesson was about, hopefully there's enough information for you to hack out what you need to do in your ASP project. However, there are many good references to object oriented programming and here are a few to help out those that would like a crash course: Sun's Take on Objects, Crazy Germans Know Their Stuff!, and Wikipedia.

ASP Components
An ASP Server Component is a collection of code that has been made by Microsoft (advanced users can also create their own components), and included in IIS. With the use of ASP you can unlock the power of this premade code. These objects can be used to do a ton of things, such as: an easy-to-use ad rotation service, an interface to a database, a means of manipulating files and much more.

Using ASP Components


Making use of Microsoft's ASP Components in your ASP programming will allow you to do so much with ASP that you'll be kicking yourself for not using components earlier. You can access these built in components by creating objects of them. See our previous lesson if you need a refresher on what ASP Objects are. In this lesson we will be utilizing Microsoft's FileSystem Component to display all the files in our current directory. The first thing we need to do is to create a FileSystem object so we can use all the properties and methods that are in this component. Note: FSO stands for File System Object in this example.

tizagComponent.asp ASP Code:


<% Dim myFSO Set myFSO = _ Server.CreateObject("Scripting.FileSystemObject") Set myFSO = nothing %>

Accessing an ASP Component's Features


Once you have created an object of your desired component you can access all the methods and variables of that component. We have created an instance of the File System Component and stored it into myFSO. We need the folder that we're going to list all the files of and the GetFolder method of our FSO will do the job. Using the same directory we decided to use back in the Running ASP lesson we are going to set the path of this FSO to "C:\Inetpub\wwwroot\tizagASP\", the same directory that "tizagComponent.asp" was saved in.

Updated tizagComponent.asp ASP Code:


<% Dim myFSO, myFolder Set myFSO = _ Server.CreateObject("Scripting.FileSystemObject") Set myFolder = _myFSO.GetFolder("C:\Inetpub\wwwroot\tizagASP") Response.Write("Current folder is: " & myFolder.Name) Set myFolder = nothing

Set myFSO = nothing %>

Display:
Current folder is: tizagASP

Finishing Up
The last thing on our to-do list is to get access to the names of the files in our working directory. The Folder object contains a method that returns a collection of all the files in the current directory. The code for accessing this collection and displaying the filenames is in the example below.

Updated tizagComponent.asp ASP Code:


<% Dim myFSO, myFolder Set myFSO = _ Server.CreateObject("Scripting.FileSystemObject") Set myFolder = _myFSO.GetFolder("C:\Inetpub\wwwroot\tizagASP") Response.Write("Current folder is: " & myFolder.Name) For Each fileItem In myFolder.Files Response.Write("<br />" & fileItem.Name) Next Set myFolder = nothing Set myFSO = nothing %>

If you have done every example in this ASP Tutorial your web page produced would look like this. Notice that the files are automatically sorted alphabetically!

Display:
firtscript.asp tizagComponent.asp tizagEmail.asp tizagForm.html tizagGet.asp tizagPost.asp

ASP Comments
As we have stated way too many times now, ASP uses VBScript as its default programming language. This means VBScript comments are ASP comments. It's a darn shame too because that means there isn't any support for multiple line comments that you see in HTML and various other programming languages.

ASP Comment Syntax: Single Line Comment


To create a comment in ASP you simply place an apostrophe in front of what you want commented out. The most common practice is to place the apostrophe at the beginning of the line of text like we have in the following example.

ASP Code:
<% 'Hello I am a comment

Dim newVar1, newVar2 'Dim oldVar1, oldVar2 %>

In the above example we had two comments. The first comment was a note style comment. Programmers often use these kinds of comments to leave information to people who are going to read their code or to themselves. The second comment we created commented out "Dim oldVar1, oldVar2" preventing the ASP interpreter from reading this line of code. This kind of comment is a block-out comment that is often used to temporarily remove code from a file that may be causing errors or is just unnecessary at the time.

How Comments Fail in ASP


Besides not having any support for multi-line comments, your ASP comments will not work if you place them within a string. This is because the interpreter will think that your apostrophe is a part of the string and not a comment. Below is an example of this happening.

ASP Code:
<% Dim newVar1, newVar2 newVar = "Hello. 'I am not commented out" %>

ASP Special Characters


All the special characters that you see when programming ASP can be a little overwhelming at first. This lesson is aimed at providing a succinct look at the most common special characters that occur within ASP. This lesson will cover the following character/symbol combinations:

& ' _ : . <%...%> <%=...%>

That's pretty ugly and confusing to look at, so let's get right in to the details of each of the symbols and see what they mean.

String Concatenation: The Ampersand &


You can combine strings with the ampersand character. It acts as a glue between one or more strings to create one large string. See our Strings Lesson for a more detailed look at strings and string concatenation. Below is an example of the ampersand concatenating two strings.

ASP Code:
<% Dim myString myString = "One String" myString = myString & " another string" Response.Write(myString) %>

Display:
One String another string

ASP Comments: The Apostrophe '


The apostrophe is used to prevent the ASP interpreter from executing the text that follows. In ASP there is only the single line comment. Check out our ASP Comments Lesson for more information on comments. Below is an example of the apostrophe.

ASP Code:
<% 'This is a comment. %>

Spanning Multiple Lines: The Underscore _


Sometimes you can't fit all your ASP code on one line because your string is too long, you are tabbed over too far or you just want to break up the statement. With the use of the underscore you can tell the ASP interpreter that you line of code continues to the next line. This allows you to have a single ASP statement span multiple lines. In the following example we have such a huge piece of code we need to span over three lines.

ASP Code:
<% Response.Write("This is probably the longest "&_ "string to be typed out on this page and maybe "&_ "even this whole tutorial on ASP!!!") %>

Display:
This is probably the longest string to be typed out on this page and maybe even this whole tutorial on ASP!!!

Squishing Onto a Line: The Colon :


Sometimes you want to reduce the human readability of your code because you're either mentally disturbed or insane. The colon will help you satiate your crazy desires by letting you put multiple lines of ASP code onto a single line. Below is an example of how to make your code very hard to read!

ASP Code:
<% Dim Dim Dim x=3 %> x y z : y=25 : z=x-y : y=x*z : z=x*x-z+y : y=5*3*z*2/x

Calling Methods: The Period .

ASP allows for Object Oriented Programming and these objects have methods that can only be called by first stating the object, then placing a period and finally calling the method by its name. The form for using the period is:

myObject.MethodName()

If you would like to learn more about ASP objects see our ASP Object Lesson.

Declaring ASP Code: The Percentage %


ASP files are often made up of a combination of HTML, some other stuff and ASP. The tag that you use to stake out an area for your ASP code does not resemble normal HTML tags. Instead it is almost like just an opening tag that can be stretched very, very, very long. You must use this character sequence to insert ASP code into your ASP files.

ASP Code:
<html> <body> <% 'My ASP code goes here. %> </body> </html>

Write Shortcut: The Percentage Equal %=


The percentage equal special character sequence is a modified version of the standard ASP code marker. This modification allows for quick access to the Response.Write() method that is used to write information to the web browser. This shortcut can be used to quickly print numbers, strings, variables and anything else you might throw at it. Below is a few examples of using this shortcut.

ASP Code:
<%=2%> <br /> <%="Hello"%> <br /> <%=Date()%>

Display:
2 Hello 9/28/2011

ASP DLL Information


When creating or using complex ASP web applications you will surely run into one that requires the use of a DLL. The DLL usually includes code that was compiled in VB, C++, or other Windows programming languages to be used in the ASP application.

Registering a DLL

Before you can start using the code that resides in the DLL file, you must first register the DLL with the windows runtime library. There are two ways to let windows know about this new DLL.

Save the DLL to C:\Windows\system32\

or

Manually register it with the regsvr32 application

The first option is self-explanatory, but the second option takes a bit more work. Here is a quick How-To on registering DLLs: 1. Find out the location of your DLL. We will be using C:\Inetpub\wwwroot\tizagASP\myDLL.dll in this example. 2. Click on the Start menu and choose Run 3. Type in regsvr32.exe "C:\Inetpub\wwwroot\tizagASP\myDLL.dll" (With the quotes) 4. You should get a confirmation message if it succeeded, such as: "DllRegisterServer in C:\Inetpub\wwwroot\tizagASP\myDLL.dll succeeded"

Using Your DLL in ASP


Now that you have registered your DLL you need to learn how to access the functions that are contained within it. Let us assume for the sake of this example that the DLL file is called "myDLL.dll" and the name of the class is "myClass". To create an instance of this class you would use the Server.CreateObject method like so:

ASP Code:
<% 'Note this is example code, it will not work ' unless you create a myDLL, myClass, and a myMethod Dim myObject myObject = Server.CreateObject("myDLL.myClass") myObject.myMethod("something") myObject = nothing %>

ASP ADO
This lesson will provide a brief overview of what ADO is and why it is necessary to have in your ASP programming repertoire. ADO stands for ActiveX Data Objects. ActiveX Data Objects are a collection of components that can be used in your ASP programs.

Accessing the Database


ADO is specifically used as means to communicate and manipulate a database. The types of databases ADO will allow your ASP program to interact include Access, MySQL, and MSSQL to name a few. In this lesson we will be connecting to an Access database, so you will need to have access to Access(hehe) to complete this lesson.

Create Your Access Database

Before you can connect to the Access database you have to first create the Access database file. Fire up your copy of MS Access and create the following database: 1. Create a New blank database called "tizag.mdb" (without the quotes) and save it to "C:\Inetpub\wwwroot\tizagASP\" (without the quotes) 2. Use the wizard to create the database. 3. Add two fields to your table: FirstName and LastName 4. Click Next 5. Name the table "TizagTable" (without the quotes) 6. Select "Yes, set a primary key for me" 7. Click Next 8. Click Finish Now that we have our database all that remains to connect to it.

Using ADO to Connect to an Access Database


Create an ASP file called "tizagADO.asp" and save it in the same directory as your Access database file. In the following ASP code we first create an ADO database connection and then we set up the ConnectionString and finally we call the Open method with our Access database filename to finish the opening process.

ASP Code:
<% Dim myConn Set myConn = Server.CreateObject("ADODB.Connection") myConn.Open = ("DRIVER={Microsoft Access" &_ " Driver (*.mdb)};DBQ=" &_ "C:\Inetpub\wwwroot\tizagASP\tizag.mdb;") myConn.Close() Set myConn = nothing %>

ASP vs PHP
Here at Tizag.com we teach two ways to program dynamic web pages: ASP and PHP. Which one is right for you? Which one should you spend your precious time and resources learning? This lesson will talk about the benefits and drawbacks of both of these technologies and try to give you the direction you need for choosing one technology over the other.

PHP: PHP Hypertext Protocol


PHP has become a somewhat mature dynamic server side programming language over the past few years. As of writing this article PHP 5.x is the current release and millions of web pages are using PHP (we are at Tizag). PHP is a free technology you can download for many different Operating Systems (see our PHP Install Lesson for information on how to install PHP).

Compared to ASP, PHP is very easy to pick up and learn a little at a time. PHP is an ideal language for the weekend or hobbyist programmer. Seems like all green pastures in the land of PHP. However, businesses do not readily embrace PHP for many reasons. A great deal of companies are running operating systems such as Windows Server 2003 or one of the Window NTs, which have been optimized to run Microsoft's proprietary language ASP. Companies usually are reluctant to switch technologies when they already have a history with one type of technology. Such a transition requires retraining or even retraining much of their staff.

ASP: Active Server Pages


ASP is a technology that is included with Internet Information Services (IIS) which is included in Windows 2003, NTs and XP Professional. If you own XP Home Edition then you will need to pay a couple hundred dollars to upgrade to XP Professional before you can begin your ASP programming career. As far as programming languages go, ASP is definitely not as straightforward as PHP. The language has a plethora of confusing programming patterns that will take a while to learn. Besides that difficulty, there is also much less free information on the internet, preventing you weekend programmers from getting a quality education for no money down. On the other hand, ASP and ASP.NET are widely used in the business world. If you are looking to get a high paying job, ASP or ASP.NET would be a darn good start to improving your desirability to employers. This isn't to say that you couldn't get a job with PHP, because you can, but rather you would just have an easier time if you took the ASP path. A search on Monster.com of ASP vs PHP near a major city resulted with 47 jobs for PHP and 321 jobs for ASP.

ASP vs PHP: Conclusion


Are you looking for a job and have time and resources to learn a rather difficult technology? Learn ASP. Want to program in your spare time, as more of a hobby than a career? PHP will treat you just fine. There are plenty of exceptions to these conclusions, as they are more a suggestion then anything else. Hopefully, this will make your decision a little easier.

ASP Files
All file interactions in ASP are done through the File System Component that is included with IIS. It includes many objects that give you a window into your system's file system. Some of the more important objects include: 1. File System Object 2. File Object 3. Folder Object Before you can gain access the second and third objects we listed above you must create the grand daddy master File System Object (FSO). Through this overarching object, everything in the File System Component can be accessed.

ASP Creating the FileSystem Object


To create the FSO you simply create an object reference to it like any other object in ASP. For a quick review on ASP Objects check out our ASP Object Lesson. In the example below we create a filesystem object and destroy it.

ASP Code:
<% Dim myFSO Set myFSO = Server.CreateObject _ ("Scripting.FileSystemObject") Set myFSO = nothing %>

Using the File Object


To retrieve a File Object in ASP you must know the relative or complete file path to the desired file. In this example we will assume that a file exists at "C:\Inetpub\wwwroot\tizagASP\firstscript.asp". myFO stands for my File Object. This small script will get a file object and print out the filename using the Name property.

ASP Code:
<% Dim myFSO, myFO Set myFSO = Server.CreateObject _ ("Scripting.FileSystemObject") Set myFO = myFSO.GetFile _ ("C:\Inetpub\wwwroot\tizagASP\firstscript.asp") Response.Write("The filename is: " & myFO.Name) Set myFO = nothing Set myFSO = nothing %>

Display:
The filename is: firstscript.asp

Using the Folder Object


To retrieve the Folder Object you must once again supply the relative or complete folder path. If you followed along with our How to Run ASP setup then you will have a folder tizagASP located at "C:\Inetpub\wwwroot\tizagASP\". myFolderO stands for my Folder Object. This example is borrowed from one of the previous lessons, ASP Components and it will display a list of all the files in the "tizagASP" folder. We will once again be using the Name property for both the Folder and File objects.

ASP Code:
<% Dim myFSO, myFolderO

Set myFSO = Server.CreateObject("Scripting.FileSystemObject") Set myFolderO = _ myFSO.GetFolder("C:\Inetpub\wwwroot\tizagASP") Response.Write("Current folder is: " & myFolderO.Name) For Each fileItem In myFolderO.Files Response.Write("<br />" & fileItem.Name) Next Set myFolderO = nothing Set myFSO = nothing %>

If you have been following along with this tutorial start to finish your browser will display something like this when you execute the script.

Display:
The filename is: tizagASP firtscript.asp tizag.mdb tizagComponent.asp tizagEmail.asp tizagForm.html tizagGet.asp tizagPost.asp That's all we have for files in ASP for the time being. Look for a full coverage of ASP Files in the near future.

ASP Dates
This lesson will teach you how to use the ASP Date Function, how to convert an ASP Date to a String and how to format an ASP Date.

ASP Date Function


The ASP Date function has to be one of the easiest date retrieval methods of all time. To display the date on your page all you need to do is place the Date function as the Response.Write argument.

ASP Code:
<% Response.Write(Date()) %>

Display:
9/28/2011 You can even use some shorthand techniques to make printing out the current date to your web page only one line of ASP Code. See our ASP Special Characters Lesson for more information.

ASP Code:
<%=Date%>

Display:
9/28/2011 Pretty sweet.

Convert ASP Date to String


The conversion of an ASP Date to string is unnecessary. If you want to use the Date in a string simply concatenate it onto the string or use the write function as we have above and you're done. However, if you want to use ASP to format a date into a specific form other than the default format of DD/MM/YYYY (D = day, M = Month, Y = Year) then you will need to use the FormatDateString function. This function is covered in the next section. If you want to convert a string to date format, check out our String to Date lesson.

FormatDateTime Function
The Format Date Time function takes two arguments: a date and (optional) an integer from 0 through 4. The meanings of these numbers are as follows:

0 - This is the default setting. A short date DD/MM/YYYY will be used. 1 - A long date defined by the computer's regional settings. 2 - A short date defined by the regional settings. 3 - (time)A time using the time format defined by the regional settings. 4 - (time)A time using military time HH:MM (H = hour, M = Minute)

Below is an example of all five used to format the Date function.

ASP Code:
<% Response.Write("0 = Response.Write("<br Response.Write("<br Response.Write("<br Response.Write("<br %> " & />1 />2 />3 />4 FormatDateTime(Date, 0)) = " & FormatDateTime(Date, = " & FormatDateTime(Date, = " & FormatDateTime(Date, = " & FormatDateTime(Date, 1)) 2)) 3)) 4))

Display:
0 = 9/28/2011 1 = Friday, October 21, 2005 2 = 9/28/2011 3 = 12:00:00 AM 4 = 00:00 You'll notice that the last two options are pretty worthless if you are just working with a standard date, but they are useful for formatting ASP's Time.

ASP Hosting: SQL

If you are looking for a web host that supplies both support for ASP and for SQL, amongst other things, then check out our list of hosts we have gathered up. The list is broken up into three classes: Personal, Business, and Expensive Custom Solutions.

SQL and ASP Hosting: Personal


These web hosts and services are cheap and good for those who don't have a huge budget and just need minimal resources and support.

FreeSQL - This web site allows developers to practice their SQL for free. This is not a web host. DiscountASP.net - Cheap SQL Hosting. This is a shared web hosting environment.

SQL and ASP Hosting: Business


These web hosts are more expensive than the above hosts, but offer more features and powerful solutions for your business's needs.

Fortune City - Extra features for small businesses. Aschosting - 24 hour toll free emergency support line.

SQL and ASP Hosting: Custom Solutions


These web hosts are set up to provide a custom solution for your business and usually provide a dedicated server solution for your projects.

ICO - Dedicated Server Solutions. The Planet - Another option for a dedicated solution.

ASP Hosting: MySQL


If you are looking for a web host that supplies both support for ASP and for MySQL, amongst other things, then check out our list of hosts we have gathered up. The list is broken up into three classes: Personal, Business, and Expensive Custom Solutions.

MySQL and ASP Hosting: Personal


These web hosts and services are cheap and good for those who don't have a huge budget and just need minimal resources and support.

FreeSQL - This web site allows developers to practice their SQL for free. This is not a web host. Think Host - Cheap MySQL Hosting. This is a shared web hosting environment.

MySQL and ASP Hosting: Business


These web hosts are more expensive than the above hosts, but offer more features and powerful solutions for your business's needs.

ISP Server - MySQL only web hosting.

MySQL and ASP Hosting: Custom Solutions


These web hosts are set up to provide a custom solution for your business and usually provide a dedicated server solution for your projects.

We do not recommend MySQL for large businesses.

ASP Manual(s)
On this page we have collected a bunch of useful sites that provide a manual to ASP and VBScript, the language that you program ASP in by default. This page itself is not a manual. ASP is proprietary software of Microsoft and so we have split up information into Microsoft and Non-Microsoft related resources.

Microsoft

MSDN ASP Tutorial - Microsoft's ASP Tutorial under Windows 2000 Server Documentation Online. ASP to ASP.NET - This manual provides information on migrating from ASP to ASP.NET MSDN VBScript User Guide - Microsoft's VBScript User Guide. If you're going to be programming in ASP you might want to get a strong grasp of VBScript, the default language to program ASP in.

Non-Microsoft

ASPIN - ASPIN has a huge collection of resources for ASP. The only downside is the time and effort it takes to get what you want.

También podría gustarte