Wednesday, February 14, 2007

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.

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 :< %
Respon se.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!

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:
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.

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:

Open up "My Computer" or "Windows Explorer" so that you can view your system's files and directories.

Select and Open the C drive (C:)

Double click the Inetpub folder

Double click the wwwroot folder - The full path to this location is "C:\Inetpub\wwwroot" for you advanced users

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.

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.

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:
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
If IIS was install appropriately you should be taken to the welcome screen http://localhost/localstart.asp

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.

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!

Complete Solution - ASP

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.

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.

Tuesday, February 13, 2007

Visual Basic Script (VBScript)

There are three ways to use VBScript in ASP pages:
1. In-line VBScript statements: The VBScript statements must be enclosed in the special in-line script tag: <% %>. The enclosed statements will be executed by the server, and the output of response.write() calls will be merged in-line with the surrounding static HTML text. In-line VBScript statements require a language declaration statement to define explicityly VBScript as the server side scripting language, if you are not sure what is the default language defined on the Web server. <%@ language="vbscript"%>
...
<%
vbscript_statement
vbscript_statement
...
%>
2. In-line VBScript expression: The VBScript expression must be enclosed in the special in-line script tag: <% %> with a leading "=" sign. The enclosed expression will be evaluated, and the resulting value will be converted into a string and merged in-line withh the surrounding static HTML text. In-line VBScript expression also require a language declaration statement to define explicityly VBScript as the server side scripting language, if you are not sure what is the default language defined on the Web server. <%@ language="vbscript"%>
...
<%
= vbscript_expresion
%>
3. Script block of VBScript statements: The VBScript statements must be enclosed by the starting script block tag . Two attributes are required on the script tag: "language" and "runat".
Please note that the script block VBScript statements will be executed by the server. But the output of response.write() calls will not be merged in-line with the surrounding static HTML text. It will be:
Inserted at the beginning of the HTTP reponse before any static HTML text, if the server's default scripting language is not VBScript.
Appended at the end of the HTTP reponse after any static HTML text, if the server's default scripting language is VBScript.
This rule was a big supprise to me. I had to post a message to microsoft.public.inetsdk.programming.scripting.vbscript, and got confirmed from Microsoft. See the article Using VBScript and JScript on a Web Page.
Mixing VBScript Statements with Static HTML Text
Here is an ASP page example to show you how in-line statements and expressions can be mixed with static HTML text: <%@ language="vbscript"%>


Good
<% if 0 <= hour(time) and hour(time) <>
moring,
<% elseif 12 <= hour(time) and hour(time) <>
afternoon,
<% else
response.write("evening,")
end if %>
Herong.

<% response.write("The current server time is: ") %>
<% = Time %> on <% = Date %>

Output: Good evening, Herong.
The current server time is: 10:01:56 PM on 5/24/2003
In the previous example, I was able to break the "if" statement into two parts and use in-line script for one part and static text for the other.

In the next example, I will show you the difference between in-line scripts and script blocks:


Text line 2.


Text line 4.


Output: Text line 2.
Text line 4.
Text line 1.
Text line 3.
Supprised? I was supprised before I learned that execution rule about script blocks mentioned in the previous section. The output also tell us that the default language on IIS 5.0 is set to VBScript. Otherwise, text line 1 and 3 would be displayed first. The problem can be avoided by using the in-line scripts: <%@ language="vbscript"%>


<%
response.write("Text line 1.
")
%>
Text line 2.

<%
response.write("Text line 3.
")
%>
Text line 4.


Now you know the different ways to use VBScript in ASP pages. But which way is better?
In-line script, <%...%>, is very flexible in mixing dynamic data with static HTML text. But the syntax is not so XML friendly.
Script block, , is not useful at all if you want to keep static HTML text in your page. It can only be used, if you want to write the entire page in a single block, and output all HTML text with response.write() calls.
Personally, I prefer script block syntax, because I could easily manipulate it with XML tools. So I will be using script blocks most of the time for my sample ASP pages in this book. Note that even HTML comment tag must be moved into the script blocks.
Variables and Expressions in VBScript
Special rules about variables and expressions:
Variables used without declarations are called "variant" variables.
Variant variables can be used to store different data types.
Variable names are case insensitive.
"=" is the assignment operator. But it is also the boolean equality operator.
"&" is the string concatenation operator.
Here is a sample ASP page, variable.asp:
Output: Tests on variables:
Sum = 6
Is the answer correct? True
"i = i=6" is a very unusual statement. First of all, variable "i" has changed its data type from integer to boolean. Secondly, two "=" signs are used next to each other, the first one is an assignment operation, and the second one is a boolean equality operator.

Arrays
Array is a build-in data structure in Visual Basic language. It can used to store a collection of data elements with indexes to access each element. Arrays can be declared to hold a fixed number of elements as: dim weekdays(5)
Arrays can also be declared to a variable number of elements as: dim weekdays()
redim weekdays(5)
other statements
redim preserve weekdays(7)
Elements in a array can be iterated with the "for each ... next" statement as: dim weekdays(5)
other statements
for each day in weekdays
other statements
next
Here is a simple ASP page to how the features of arrays:
Output Tests on arrays:
Element 1 = Mon
Element 2 = Tue
Element 3 = Wed
Element 4 = Thu
Element 5 = Fri
Two days added:
Element 1 = Mon
Element 2 = Tue
Element 3 = Wed
Element 4 = Thu
Element 5 = Fri
Element 6 = Sat
Element 7 = Sun
Element 8 =
Note that:
Indexes of elements in arrays starts with 0.
"redim" can only be used against arrays that are declared with dynamic size.
"redim" can be used repeatedly.
"redim preserve" can be used to preserve the elements that already exist.
"for each ... next" statement revealed an extra element in the array. I am not sure why?
"Collection" Class
Collection: A class representing a collection of ordered elements. The stored elements can be referred by an index number or by the key associated with the elements. It offers the following methods and properties based on the documentation of Visual Basic .NET:
"Item(ikey)": Property to return the element of the specified index or key. Item() is the default method of a collection object, so you can call this method without the method name, like object(ikey), instead of object.Item(ikey).
"Count": Property to return the number of elements in the collection.
"Add(element)": Method to add an element at the end of the collection without a key.
"Add(element, key)": Method to add an element at the end of the collection with a key.
"Remove(ikey)": Method to remove the element of the specified index or key.
Unfortunately, I was not able to write an ASP page with a new collection object.
write200x90("ASP");

Displaying an RSS Feed using ASP

This tutorial will walk you through adding dynamic content from an RSS 2.0 data feed. RSS is a XML format for syndicating news content, web site updates, and blogs. Learn how to add this content to your web site with ASP.

RSS 2.0 Format
The RSS 2.0 is a very simple XML format. In the RSS feed, the tag will repeat for news item. The following is a very simple example of an RSS feed. See the Resources below for complete RSS 2.0 specification.



<>channel title
link to channel
description
en-us


<em>item title</em>
link url
unique id
item description


Reading the RSS Feed
To read the RSS feed, the MSXML2.DOMDocument object is used to read and parse the XML. This object allows for the XML DOM (Document Object Model) to be easily accessed.

The following example read an RSS feed into the XML DOM object:

Set xmlDOM = Server.CreateObject("MSXML2.DOMDocument")xmlDOM.async = False
xmlDOM.setProperty "ServerHTTPRequest", TruexmlDOM.Load("http://www.codebeach.com/rss-it-jobs.asp")

Parse the news items
The information in the RSS feed that we are interested in is within the tags. To start, all of the items are placed in a list by calling the getElementsByTagName() method. Once we have the list of items, we will iterate over the list and get the data for each item in the feed.

'Get all of the  tags in the feedSet itemList = xmlDOM.getElementsByTagName("item")
strHTML = strHTML & "
    "
    'Iterate over each itemFor Each item In itemList

    'Parse the item children
    For each child in item.childNodes
    Select case lcase(child.nodeName)
    case "title"
    title = child.text
    case "link"
    link = child.text
    case "description"
    description = child.text
    End Select
    Next

    'Build the HTML for each bullet item
    strHTML = strHTML & "
  • "
    strHTML = strHTML & "& Server.HTMLEncode(link) & "'>"
    strHTML = strHTML & Server.HTMLEncode(title)
    strHTML = strHTML & "
    "
    strHTML = strHTML & "
    "
    strHTML = strHTML & description
    strHTML = strHTML & "
    "
    strHTML = strHTML & "
  • "
    Next
    strHTML = strHTML & "
"
Set xmlDOM = Nothing
Set
itemList = Nothing
Response.Write(strHTML)

Final Version
Below is the complete version of the example to read the RSS 2.0 feed. The final version will also cache the HTML content built on the RSS feed. This is so it won't get the RSS feed everytime the web page is loaded. By caching the resulting HTML, it will improve the page performance and it won't overload the server that you are requesting the feed from. To view more information on caching, you may want to read the tutorial Caching Data in ASP.

<%@ Language="VBScript" %><html>
<
head>
<
title>RSS Reader</title>
<
/head>
<
body><%If DateDiff("h", Application("rss-html-time"), Now()) >= 2 then

Set
xmlDOM = Server.CreateObject("MSXML2.DOMDocument")
xmlDOM.async = False

xmlDOM.setProperty "ServerHTTPRequest", True
xmlDOM.Load("http://www.codebeach.com/rss-it-jobs.asp")

'Get all of the tags in the feed
Set itemList = xmlDOM.getElementsByTagName("item")

strHTML = strHTML & "
    "

    'Iterate over each item
    For Each item In itemList

    'Parse the item children
    For each child in item.childNodes
    Select case lcase(child.nodeName)
    case "title"
    title = child.text
    case "link"
    link = child.text
    case "description"
    description = child.text
    End Select
    Next

    'Build the HTML for each bullet item
    strHTML = strHTML & "
  • "
    strHTML = strHTML & "& Server.HTMLEncode(link) & "'>"
    strHTML = strHTML & Server.HTMLEncode(title)strHTML = strHTML & "
    "
    strHTML = strHTML & "
    "
    strHTML = strHTML & description
    strHTML = strHTML & "
    "
    strHTML = strHTML & "
  • "
    Next
    strHTML = strHTML & "
"

Set xmlDOM = Nothing
Set
itemList = Nothing

Application.Lock
Application("rss-html") = strHTML
Application("rss-html-time") = Now()
Application.UnLockEnd If
Response.Write(Application("rss-html"))%></body>
<
/html>

cheching if user is online

<%If Response.IsClientConnected=true thenResponse.Write(”The user is still connected!”)elseResponse.Write(”The user is not connected!”)end if%>


Explanation by Line
1. Starts the ASP code block.
2. Here we start an if statement that says if the user is connected then the statement is true and it goes to line three, otherwise it goes to line 5.
3. It prints that the user is connected.
4. The else statement says; if the initial if statement was false then execute line 5, otherwise skip over it.
5. It prints that the user isnt connected if the if statement was false.
6. This tag closes the if statement.
7. This tag ends the ASP code block.

Hoped this helped

Converting all applicable characters to HTML entities

In this code sample we will converting all applicable characters to HTML entities using htmlentities(). Using 'htmlentities' all characters which have HTML character entity equivalents are translated into these entities.


Syntax

string htmlentities ( string string [, int quote_style [, string charset]] )

Example :



$strMessag = "You're my best friend.";


echo
htmlentities($strMessage,
ENT_COMPAT);

echo htmlentities($strMessage, ENT_QUOTES);

echo htmlentities($strMessage, ENT_NOQUOTES);

?>


Available quote_style constants :
ENT_COMPAT : Will convert double-quotes and leave single-quotes alone.
ENT_QUOTES : Will convert both double and single quotes.
ENT_NOQUOTES : Will leave both double and single quotes unconverted.


Supported charsets :
ISO-8859-1 ISO8859-1 Western European, Latin-1
ISO-8859-15 ISO8859-15 Western European, Latin-9. Adds the Euro sign, French and Finnish letters missing in Latin-1(ISO-8859-1).
UTF-8 ASCII compatible multi-byte 8-bit Unicode.
cp866 ibm866, 866 DOS-specific Cyrillic charset. This charset is supported in 4.3.2.
cp1251 Windows-1251, win-1251, 1251 Windows-specific Cyrillic charset. This charset is supported in 4.3.2.
cp1252 Windows-1252, 1252 Windows specific charset for Western European.
KOI8-R koi8-ru, koi8r Russian. This charset is supported in 4.3.2.
BIG5 950 Traditional Chinese, mainly used in Taiwan.
GB2312 936 Simplified Chinese, national standard character set.
BIG5-HKSCS Big5 with Hong Kong extensions, Traditional Chinese.
Shift_JIS SJIS, 932 Japanese
EUC-JP EUCJP Japanese

Creating Word Files Online

ASP has the ability to dynamically output any kind of office application format. Before to start coding, The first thing we need to do is set correct file type. Becase the browser needs to know what to do with the file. Second step is to edit file name. You can use HTML and CSS to create styles in your word document.


Here is a comple source code :

<%

Response.ContentType = "application/msword"

Response.AddHeader "Content-Disposition", "attachment;filename=NAME.doc"

response.Write("Dotnetindex.com : Visit Site
" & vbnewline)


response.Write("

We can use HTML codes for word documents

")


response.Write ("
CSS can be used tooo")

%>

<% Response.ContentType = "application/msword" Response.AddHeader "Content-Disposition", "attachment;filename=NAME.doc" response.Write("Dotnetindex.com : Visit Site
" & vbnewline)

response.Write("

We can use HTML codes for word documents

")

response.Write ("
CSS can be used tooo")

%>