www.tamertolba.4t.com

 

Chapter 2

Writing ASP Scripts

 

This chapter introduces the basic elements of Active Server Pages (ASP) scripts. For a hands-on introduction to ASP scripting.

 

2.1- What is an .Asp File?

Active Server Pages (ASP) is built around files with the file name extension .asp. An .asp file is a text file and can contain any combination of the following:

           Text

          HTML tags

          Script commands.( A script command instructs your computer to do

                              something, such as assign a value to a variable.)

 

It’s easy to create an .asp file: Just rename any HTML file, replacing the existing .htm or .html file name extension with .asp. To make the .asp script file available to Web users, save the new file in a Web publishing directory (be sure that the associated virtual directory has Execute permissions enabled). When you view the file with your browser, you see that ASP processes and returns HTML, just as before. ASP really begins to work for you, however, when you add scripts to your HTML.

2.2- What is a Script?

 1) In computer programming, a script is a program or sequence of instructions that is interpreted or carried out by another program rather than by the computer processor (as a compiler program is).

Some languages have been conceived expressly as script languages. Among the most popular are Practical Extraction and Reporting Language, Restructured Extended Executor (on IBM mainframes), JavaScript, and Tcl/Tk. In the context of the World Wide Web, Perl, VBScript, and similar script languages are often written to handle forms input or other services for a Web site and are processed on the Web server. A JavaScript script in a Web page runs "client-side" on the Web browser.

In general, script languages are easier and faster to code in than the more structured and compiled languages such as C and C++ and are ideal for programs of very limited capability or that can reuse and tie together existing compiled programs. However, a script takes longer to run than a compiled program since each instruction is being handled by another program first (requiring additional instructions) rather than directly by the basic instruction processor.

2) A script is sometimes used to mean a list of operating system commands that are prestored in a file and performed sequentially by the operating system's command interpreter whenever the list name is entered as a single command.

3) Multimedia development programs use "script" to mean the sequence of instructions that you enter to indicate how a multimedia sequence of files will be presented (the sequence of images and sounds, their timing, and the possible results of user interaction).

 Executing a script sends the series of commands to a scripting engine, which interprets and relays them to your computer. Scripts are written in languages that have specific rules; thus, if you want to use a given scripting language, your server must run the scripting engine that understands the language. ASP provides scripting engines for the VBScript and Jscript scripting languages. Your primary scripting language—that is, the language that ASP assumes you are using if you don't specify a language—is VBScript by default.

 

2.3- ASP Syntax :

ASP is not a scripting language; rather, ASP provides an environment that processes

scripts that you incorporate into your HTML pages. To use ASP successfully, you need to learn the syntax, or rules, by which it operates.

 

2.3.1- Delimiters:

 HTML tags are differentiated from text by delimiters. A delimiter is a character or sequence of characters that marks the beginning or end of a unit. In the case of HTML, these delimiters are the less than (<) and greater than (>) symbols.

 Similarly, ASP script commands and output expressions are differentiated from both text and HTML tags by delimiters. ASP uses the delimiters <% and %> to enclose script commands. For example, the command <% sport = "climbing" %> assigns the value climbing to the variable sport.

 ASP uses the delimiters <%= and %> to enclose output expressions. For example, the output expression <%= sport %> sends the value climbing (the current value of the variable) to the browser.

 

2.3.2- Single Expressions:

 You can include within ASP delimiters any expression valid for your primary scripting language. For example, the following line produces text ending with the current server time:

 This page was last refreshed at <%= Now %>.

 In this case, the Web server returns the value of the VBScript function Now to the browser along with the text.

 

2.3.3- Statements :

 A statement, in VBScript and other scripting languages, is a syntactically complete unit that expresses one kind of action, declaration, or definition. The conditional If...Then...Else statement that appears below is a common VBScript statement.

 <%

If Time >=#12:00:00 AM# And Time < #12:00:00 PM#  Then

  greeting = "Good Morning!"

Else

  greeting = "Hello!"

End If

%>

 This statement stores either the value "Good Morning!" or the value "Hello!" in the variable greeting. It does not send any values to the client browser. The following lines send the value,in green, to the client browser:

 <FONT COLOR="GREEN">

<%= greeting %>

</FONT>

 Thus, a user viewing this script before 12:00 noon (in the Web server’s time zone) would see

Good Morning!

A user viewing the script at or after 12:00 noon would see

Hello!

 

2.3.4- Including HTML in a Statement:

 You can include HTML text between the sections of a statement. For example, the following script, which mixes HTML within an If...Then...Else statement, produces the same result as the script in the previous section:

 <FONT COLOR="GREEN">

<% If Time  > = #12:00:00 AM# And Time < #12:00:00 PM#  Then %>

Good Morning!

<% Else %>

Hello!

<% End If %>

</FONT>

 If the condition is true—that is, if the time is midnight or after, and before noon—then the Web Server sends the HTML that follows the condition (“Good Morning”) to the browser; otherwise, it sends the HTML that follows Else (“Hello”) to the browser.

  

2.3.5- Script Tags:

 The statements, expressions, commands, and procedures that you use within script

delimiters must be valid for your default primary scripting language. ASP is shipped with the default primary scripting language set to VBScript. However, with ASP you can use other scripting languages; just use the HTML script tags <SCRIPT> and </SCRIPT>, together with the LANGUAGE and RUNAT attributes, to enclose complete procedures written in any language for which you have the scripting engine.

 For example, the following .asp file processes the JScript procedure MyFunction.

 <HTML>

<BODY>

<% Call MyFunction %>

</BODY>

</HTML>

 

<SCRIPT RUNAT=SERVER LANGUAGE=JSCRIPT>

  function  MyFunction ()

  {

      Response.Write("MyFunction Called")

  } 

</SCRIPT>

 

 Important :   Do not include within <SCRIPT> tags any output expressions or script commands that are not part of complete procedures.

 You can include procedures written in your default primary scripting language within ASP delimiters.

 

2.3.6- Variable and Object Scope:

 ASP variables and objects can have application, session, or page scope. Application

scope enables the variable or object to be shared by all users. Session scope enables

any page in a user session to share the object or variable. Page scope, the default, is

available only while the page is processing. You will learn in a next section how to create application- and session-level variables. When using ActiveX components, an application scope component is a single instance of the component shared by all users that is destroyed when the application ends. A session scope component is a single instance of the component per user session and is destroyed when the session ends. A page scope object is created while processing the page and is destroyed when the page processing completes.

 

2.3.7- Including Other Files:

 Server-side includes is a mechanism you can use to insert information into a file prior to processing. ASP implements only the #INCLUDE pre-processing directive of this mechanism. You can use this directive to insert the content of another file into an .asp file before ASP processes the .asp file. Use the following syntax:

 <!--#INCLUDE VIRTUAL|FILE="filename"-->

 Where you must type either VIRTUAL or FILE, which are keywords that indicate the type of path you are using to include the file, and filename is the path and file name of the file you want to include.

 Included files do not require a special file-name extension; however, Microsoft recommends giving included files an .inc file-name extension to distinguish them from other types of files.

  

2.3.8- Using the Virtual Keyword:

 Use the Virtual keyword to indicate a path beginning with a virtual directory. For example, if a file named Footer.inc resides in a virtual directory named /Myapp, the

following line would insert the contents of Footer.inc into the file containing the line:

 <!--#INCLUDE VIRTUAL="/myapp/footer.inc"-->

 

 2.3.9- Using the File Keyword:

 Use the File keyword to indicate a relative path. A relative path begins with the directory that contains the including file. For example, if you have a file in the directory Myapp, and the file Header1.inc is in Myapp\Headers, the following line would insert Header1.inc in your file:

 <!--#INCLUDE FILE="headers/header1.inc"-->

 Note that the path to the included file, Headers/header1.inc, is relative to the including file; if the script containing this Include statement is not in the directory /Myapp, the statement would not work.

 You can also use the FILE parameter with ../ syntax to include a file from a parent, or higher-level, directory if the EnableParentPaths registry setting is 1.

 

2.3.10- Including Files: Tips and Cautions:

 An included file can, in turn, include other files. An .asp file can also include the same file more than once, provided that the <INCLUDE> statements do not cause a loop. For example, if the file First.asp includes the file Second.inc, Second.inc must not in turn include First.asp. Nor can a file include itself. ASP detects such loop or nesting errors, generates an error message, and stops processing the requested .asp file.

 ASP includes files before executing script commands. Therefore, you cannot use a script command to build the name of an included file. For example, the following script would not open the file Header1.inc because ASP attempts to execute the #Include directive before it assigns a file name to the variable name.

 <!-- This script will fail -->

<% name=(header1 & ".inc") %>

<!--#include file="<%= name %>"-->

 Scripts commands and procedures must be entirely contained within the script delimiters

<% and %>, the HTML tags <SCRIPT> and </SCRIPT>, or the HTML tags <OBJECT> and </OBJECT>. That is, you cannot open a script delimiter in an including .asp file, then close the delimiter in an included file; the script or script command must be a complete unit. For example, the following script would not work:

 <!-- This script will fail -->

<%

For i = 1 To n

  statements in main file

  <!--#include file="header1.inc" -->

Next

%>

 The following script would work:

 <%

For i = 1 to n

  statements in main file

%>

<!--#include file="header1.inc" -->

<% Next %>

 

2.3.11- Using a Server Script to Modify a Client Script:

 Although ASP is used primarily to process server-side scripting, you can extend its reach by using it to generate client-side scripts that are then processed by the client browser. ASP does this by combining client-side scripts that are enclosed by HTML comments with server-side scripts that are enclosed by delimiters:

 <SCRIPT LANGUAGE="VBScript">   

<!--

client script

<% server script  %>

client script

<% server script  %>

client script

...

-->

</SCRIPT>

 With this functionality in your scripts, you can create exciting applications.  

Example: .

 <%

define server side var

myvar="Hello"

%>

<script language="JavaScript">

var x;

x="<%=myvar:%>

document.write("the statment is " + x)

 </script>

 

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">

 

2.4- Using Scripting Languages:

Scripting languages are an intermediate stage between HTML and programming languages such as Java, C++, and Visual Basic. HTML is generally used for formatting and linking text. Programming languages are generally used for giving a series of complex instructions to computers. Scripting languages fall somewhere in between, although scripting languages function more like programming languages than simple HTML docs. The primary difference between scripting languages and programming languages is that the syntax and rules of scripting languages are less rigid and intricate than those of programming languages.

Scripting engines are the COM (Component Object Model) objects that process scripts. Active Server Pages provides a host environment for scripting engines and distributes scripts within .asp files to these engines for processing. For each scripting language that is used in coordination with ASP scripting, the related scripting engine must be installed on the Web server. For example, VBScript is the default language of Active Server Pages, so the VBScript engine resides as an COM object accessible by Active Server Pages so that it can process VBScript scripts. Likewise, Active Server Pages can provide a scripting environment for a number of other scripting languages, including JScript, REXX, and Perl, and others.

Active Server Pages makes it possible for the Web developer to write complete procedures by using a variety of scripting languages without having to worry about whether a browser supports them all. In fact, several scripting languages can be used within a single .asp file. This can be done by identifying the script language in an HTML tag at the beginning of the script procedure.

In addition, because scripts are read and processed on the server side, the client browser that requests the .asp file does not need to support scripting.

 

2.4.1- Setting the Primary Scripting Language:

VBScript is the default scripting language that is used for primary scripting. If you use primary scripting, which uses the <% and %> delimiters, you can place any valid VBScript command inside the scripting delimiters and Active Server Pages will process the commands inside of the delimiters as VBScript. Active Server Pages makes it possible to set any scripting language as the primary scripting language. You can set the primary scripting language on a page-by-page basis, or for all pages on your Web server.

To change the primary scripting language for all pages in all applications, you must change the value of the DefaultScriptLanguage entry in the registry to that

language.

The procedure for setting the primary scripting language depends on whether the chosen language supports Object.Method syntax. The procedures are detailed below.

 

2.4.2- Languages That Support Object.Method Syntax:

For languages that support Object.Method syntax and use parentheses to enclose parameters, such as VBScript and JScript, you can change the primary scripting language for a single page by adding a command line to the beginning of your .asp file. The syntax for this command is:

<%@ LANGUAGE = ScriptingLanguage %>

where ScriptingLanguage is the primary scripting language that you want to set for that particular page.

Follow these guidelines when setting the primary scripting language for a page:

·        Set the primary scripting language on the first line of the file.

·        Do not set the page’s primary scripting language in an include file.

·        Place a space between @ and LANGUAGE.

·        Do not place any elements other than @ and LANGUAGE = ScriptingLanguage between the scripting delimiters (<% and %>).

If you do not follow these guidelines for setting the primary scripting language for a page, an error will be generated.

 

2.4.3- Languages That Do Not Support Object.Method Syntax:

In order to use a language that does not support the Object.Method syntax as the primary scripting language, you must first create the LanguageEngines registry key with the corresponding language name subkey and values:

 

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services

 \W3SVC

  \ASP

   \LanguageEngines

    \LanguageName

       Value: Write REG_SZ: Response.WriteEquiv |

       Value: WriteBlock REG_SZ: Response.WriteBlockEquiv |

where LanguageName is the name of the chosen language, Response.WriteEquiv is the language’s equivalent of Response.Write, and Response.WriteBlockEquiv is the language’s equivalent of Response.WriteBlock. The pipe symbol (|) is an insertion used by Active Server Pages to send expressions and HTML blocks that are normally processed with Response.Write and Response.WriteBlock methods. This may be done automatically when installing additional scripting languages.

 

Note  :  Some scripting languages are sensitive to white space or newline characters; it may not be possible to use such languages as the primary scripting language by changing the registry entries as described above. An alternative to using these as primary scripting languages is to manually write HTML blocks to the browser rather than using Active Server Pages to automatically handle interleaved <% ... %> script directives and HTML. Another option is to write that language’s functions within tagged script blocks (<SCRIPT> ... </SCRIPT> ) and call them from any other language.

 

2.4.4- Using VBScript and JScript:

When using VBScript on the server with ASP, two VBScript features are disabled. Because Active Server Pages scripts are executed on the server, the VBScript statements that present user-interface elements, InputBox and MsgBox, are not supported. The VBScript functions CreateObject and GetObject are also not supported. Use of these statements will cause an error.

 

2.4.5- Including Comments:

HTML Comments

Because the processing of all ASP scripts is done on the server side, there is no need to include HTML comment tags to hide the scripts from browsers that do not support scripting, as is often done with client-side scripts. All ASP commands are processed before content is sent to the browser.

VBScript Comments

Basic REM and apostrophe-style comments are supported in VBScript. Unlike HTML comments, these are removed when the script is processed and are not sent to the client.

<%

REM This line and the following two are comments

'The PrintTable function prints all

'the elements in an array.

Call PrintTable(myarray())

%>

 

Important   You cannot include a comment in an output expression. For example, the first line that follows will work, but the second line will not, because it begins with <%=.

 

<% i = i +1 'this increments i. This script will work. %>

 

<%= name 'this prints the variable name. This script will fail. %>

 

JScript Comments

The // comment characters are supported in JScript. These characters should be used on each comment line.

<% Call PrintDate %>

<SCRIPT LANGUAGE=JScript RUNAT=Server>

function PrintDate()

{

  var x

  x = new Date()

  Response.Write(x.getDate())

}

// This is a definition for the procedure PrintDate.

// This procedure will send the current date to the client-side browser.

</SCRIPT>

 

 

 

2.5- Writing Procedures with Multiple Languages:

An attractive feature of Active Server Pages is the capability to incorporate several scripting language procedures within a single .asp file. With this functionality, you can use scripting languages that have particular strengths to help you get a specific job done.

 

2.5.1- Creating Procedures:

A procedure is a group of script commands that performs a specific task. You can define your own procedures and call them repeatedly in your scripts. Procedure definitions can appear within <SCRIPT> and </SCRIPT> tags and must follow the rules for the declared scripting language. You can also define a procedure within scripting delimiters (<% and %>) as long as it is in the same scripting language as the primary script.

You can place procedure definitions in the same .asp file that calls the procedures, or you can put commonly used procedures in a shared .asp file and use a server-side include statement (that is, <!--#INCLUDE FILE= ...) to include it in other .asp files that call the procedures. Alternatively, you could package the functionality in an ActiveX server component.

 

2.5.2- Calling Procedures:

To call procedures, include the name of the procedure in a command.For VBScript, you can also use the Call keyword when calling a procedure. However, if the procedure that you are calling requires arguments, the argument list must be enclosed in parentheses. If you omit the Call keyword, you also must omit the parentheses around the argument list. If you use Call syntax to call any built-in or user-defined function, the function’s return value is discarded. If you are calling JScript procedures from VBScript, you must use parentheses after the procedure name; if the procedure has no arguments, use empty parentheses.

The following example illustrates creating and calling procedures by using two different scripting languages (VBScript and JScript).

<HTML>

<BODY>

<TABLE>

<% Call Echo %>

</TABLE>

<% Call PrintDate %>

</BODY>

</HTML>

 

<SCRIPT LANGUAGE=VBScript RUNAT=Server>

Sub Echo

  Response.Write _

  "<TR><TD>Name</TD><TD>Value</TD></TR>"

  Set Params = Request.QueryString

  For Each p in Params

  Response.Write "<TR><TD>" & p & "</TD><TD>" & _

  Params(p) & "</TD></TR>"

  Next

End Sub

</SCRIPT>

 

<SCRIPT LANGUAGE=JScript RUNAT=Server>

function PrintDate()

{

  var x

  x = new Date()

  Response.Write(x.toString())

}

</SCRIPT>

 

Note : To pass an entire array to a procedure in VBScript, use the array name followed by empty parentheses; in JScript, use empty square brackets.

 

2.6- Creating Functions and Calling them:

 Here is a demonstration to making  a function and display it's results in your page.

 

<title>functionworkingdays.asp</title>

<body bgcolor="#FFFFFF">

<%

response.write "3 working days from today is " & dtaddWorkingDays(now(),3) & "<p>"

%>

2  working days from today is <%=dtaddWorkingDays(now(),2)%>

</body>

<%Function dtAddWorkingDays(dtStartDate, nDaystoAdd)

      'Adds working days based on a five day week

     

      Dim dtEndDate

      Dim iLoop

     

      'First add whole weeks

      dtEndDate=DateAdd("ww",Int(nDaysToAdd/5),dtStartDate)

     

      'Add any odd days

      For iLoop = 1 To (nDaysToAdd Mod 5)

       dtEndDate=DateAdd("d",1,dtEndDate)

       'If Saturday increment to following Monday

       If WeekDay(dtEndDate)=vbSaturday Then

       'Increment date to following Monday

       dtEndDate=DateAdd("d",2,dtEndDate)

       End If

      Next

dtAddWorkingDays=dtEndDate

End Function

%>