About Me

Showing posts with label ASP. Show all posts
Showing posts with label ASP. Show all posts

Saturday, 21 April 2012

ASP Hosting: MySQL

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.

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 Hosting: SQL

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.

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 Dates

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:

4/21/2012
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:

4/21/2012
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 = " & FormatDateTime(Date, 0))
Response.Write("<br />1 = " & FormatDateTime(Date, 1))
Response.Write("<br />2 = " & FormatDateTime(Date, 2))
Response.Write("<br />3 = " & FormatDateTime(Date, 3))
Response.Write("<br />4 = " & FormatDateTime(Date, 4))

%>

Display:

0 = 4/21/2012
1 = Friday, October 21, 2005
2 = 4/21/2012
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 Files

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\nullvoidASP\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\nullvoidASP\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\nullvoidASP\".
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
nullvoid.mdb
nullvoidComponent.asp
nullvoidEmail.asp
nullvoidForm.html
nullvoidGet.asp
nullvoidPost.asp

ASP ADO

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
%>

Friday, 20 April 2012

ASP DLL Information

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 Special Characters

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 x
Dim y
Dim z
x=3 : 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
4/20/2012

ASP Comments

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 Object

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.

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 Email Form

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 Form Post

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="nullvoidPost.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.

ASP Forms Get

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.

nullvoid.html Code:

<form method="GET" action="nullvoidGet.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:

ASP Forms

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="nullvoidGet.asp">
Name <input type="text" name="Name"/>
Age <input type="text" name="Age"/>
<input type="submit" />
</form>

ASP Strings

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 Cookies

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 Session

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:02:44 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 Arrays

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 Variables - VBScript


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.

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. Variable name must start with an alphabetic character (A through Z or a through z)
  2. Variables cannot contain a period
  3. Variables cannot be longer than 255 characters (don't think that'll be a problem!)
  4. 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 Select Case

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 is Two")
 Case 3
  Response.Write("myNum is Three")
 Case 5
  Response.Write("myNum is Five")
 Case Else
  Response.Write("myNum is " & myNum) 
End Select
%>

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 is Two")
 Case 3
  Response.Write("myNum is Three")
 Case 5
  Response.Write("myNum is Five")
 Case Else
  Response.Write("myNum is " & myNum) 
End Select
%>

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 - If Statement

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!