Archive for the 'asp' Category
Loop Structures in JScript
There are a lot of times when you would want to execute more or less the same statements for a large number of times. You can do this though the use of loops. The concept of looping is based on the fact that a value is changed every time the loop executes an iteration - which is a single execution of the loop. The loops is typically controlled by a test of a variable, and it is that variable's value that should change in the iteration, because if we don't do nothing, be will have an infinite loop which does the same thing over and over again, and it never stops. That's not good, and it may be the answer why your script hangs for a long time and it produces no result.
There are four types of loops in JScript: for loops, for…in loops, while loops, do…while loops. The easiest one is the for statement. It specifies a counter variable which it will use for a test condition, and an action that updates the counter before each iteration.
for (variable_initialization; expression; increment)
statements
"for" executes the statements as long as the specified expression is evaluated to "true". The following example fills an array with numbers from 0 to 9:
var numbers = new Array();
for (i = 0; i < 10; i++) //as long as the variable "i" is smaller than 10…
{
numbers[i] = i;
}
A special kind of loop structure is the for…in loop. Jscript uses it for stepping through all the elements of an array, or all the user-defined properties of an object. The syntax is slightly different from the original:
for (variable in [object | array])
statements
But if you want a more open approach to loops, you can always use the while structure. There is a slight difference between for loop and while loop - when you use while, you must do all the counter variable initialization and variation yourself. "while" will only accept a expression, and if the expression is evaluated to "true", then it will execute the statements you provide. Because while loops don't have an explicit built-in counter variable, they are more exposed to infinite loops, so always remember to change the counter-variable's value inside the loop! Here is the same loop example as before, but we use "while" instead of "for":
var numbers = new Array();
i = 0; //we have to do the initialization ourselves
while(i < 10)
{
numbers[i] = i;
i++; //don't forget to alter the counter-variable's value, or else you'll get an infinite loop
}
Similar to the while loop is the do…while loop, which actually performs the test after it executes the loop. This guarantees that the loop is executed at least once, after which it may or may not continue, based on the evaluation of the expression provided with while:
var numbers = new Array();
i = 0;
do
{
numbers[i] = i; //this is parsed at least once…
i++; //this too
}
while (i < 10);
There are times when you encounter special values within a loop, and you may want to simple exit the loop, or continue to the next iteration. JScript provides two such statements: "break" and "continue". The break statement immediately stops the execution of the loop, while the continue statement stop the current iteration only, and starts the next one. No matter which statement you choose to use, the previous statements before break or continue are always executed, but the following ones will not be parsed.
You can use break and continue with any of the "for", "while" or "do…while" loops.
var numbers = new Array();
for (i = 0; i < 10; i++) //as long as the variable "i" is smaller than 10…
{
if(i == 5)
continue; //let's skip the number 5
numbers[i] = i;
}
No commentsConditional Structure in JScript
Conditional structures are one the most important feature in any programming language. Jscript implements the if…else statement, just like a lot of other languages. The process is simple: the if structure evaluates an expression to a truth value (true or false); if the expression is evaluated to "true", then some certain statements are called afterwards, otherwise, if the user provides an else statement, Jscript parses the statements after "else". This is how you declare such a structure:
if (expression)
statements_if;
[else
statements_else];
We placed the "else" part in brackets because it's optional, so you can use "if" without "else". Here are some examples of both structures:
if (number == 1) //tests if the variable "number" holds the value "1″
{
response = "The number is one"; //this is executed if the expression is true
}
else
{
response = "The number is not one"; //this is executed if the expression is false
}
if (color == "white") //tests if the variable "color" holds the value "white"
color = "black"; //if so, let's change the white color to black
If you have an if…else structure with only one statement in each part (if and else), then you might find it easier to use the conditional operator "?"…":". This way, you will reduce the amount of written text.
expression ? statement_true : statement_false;
As you can see, we first type the expression, then the question mark. If the expression is evaluated to true, the statement after the question mark is parsed. Otherwise, the statement after ":" is parsed. You should know that you must have both operators for the whole thing to work; so if you don't use "else" in your structure, stick to using the standard if structure.
(number = 1) ? response = "The number is one" : response = "The number is not one";
Jscript also provides a way to execute more than two block of statements based on more than two values of a single expression. This can be accomplished by using the switch statement:
switch (expression)
{
case value_1:
statements_1
case value_2:
statements_2
…
[ default:
statements_default]
}
"switch" tests the expression for all the specified values, then executes the statements after it has encountered the first value that is equal to the expression's result. If it doesn't find any, then it executes the default statement, if there is one. If no values match the expression's result, and there is no "default" statement specified, then nothing is executed. After it has started to run the first block of statements it continues to run also the other statements, even if they don't "belong" to the value which was equal to the expression's result. To stop it, you can use a "break" statement:
switch (color)
{
case "black":
html_color = "000000″;
break;
case "white":
html_color = "FFFFFF";
break;
case "red":
html_color = "FF0000″;
break;
default:
html_color = "FFFFFF";
}
No commentsArrays in JScript
While variables are used for storing single values (a string, a number, etc.), arrays special variables that can hold for multiple values in the same variable. It's pretty difficult to store 50 names of different people in 50 variables, so this is the main purpose of a variable: it allows you to store as many elements as you want in it. You've already used arrays in the loops created before, and they didn't puzzle you, because they are quite logical and easy to understand.
Because you have such many elements, there must be a very quick way to access them. Well, you should know that there is this thing called indexing, which means that each item has an associated index. JScript indexes an array's elements starting from zero and increments the element's index with each new addition, this way you can always find out the last index of an element: it's the total number of elements minus one.
A second way to index an array is by using strings. These types of array are often referred to as associative arrays, because they have a string associated with each element. This is really useful when you're using small arrays and you want to know exactly what each element is all about. The index, either numeric or string, is always enclosed by brackets "[]".
There are two types arrays in Jscript: typed arrays and object arrays. The typed array has a base data type, so this means that each elements of the array must be of the same type (for example, all elements are strings). You can declare a typed array using the "new" operator, for instance:
var country_capitals = new Array(4)
This creates a new array, with four elements. You can do the same, by specifying each element:
var country_capitals = new Array("Washington", "Paris", "London", "Moscow")
In order to refer to one of the elements of the array, you'll have to use the name of the array, and the index number. Remember that the first index number is 0. So, when you want to assign data to the elements of the array, you have to use the following syntax:
country_capitals[0] = "Washington"
country_capitals[1] = "Paris"
country_capitals[2] = "London"
country_capitals[3] = "Moscow"
When you need to, you can retrieve the data stored in the elements of the array, with this syntax:
town = country_capitals[0]
There is a wide variety of uses for the arrays and the data they store. In web pages, you will often see the elements of an array displayed as tables. Also, you can use them for a basic word search, or a filter operation.
Properties can be attributed to an array, by using the syntax: object.property_name. There are three properties for the arrays: prototype (which ads properties to the array), length (for the number of elements) and constructor (with the function that created the prototype of the object).
There are several methods you can use in connection with the arrays, through which they perform the respective actions. The syntax is object.method_name().
One such function you will often find is concat() which joins two arrays (or more, as the case may be). The returned result will be a new array, of course. Another method is pus("element"), which ads the respective element (or more than one) at the end of the given array. In this case, the returned value is the new length of the array.
The names of these methods are quite intuitive, so in many cases you'll understand what they do when you'll see them - reverse(), for instance, reverses the order of the elements of the array, while sort(), well, it sorts the elements. You should spend some time looking at these methods - you don't need to learn them by heart or anything, but it would be useful to know that they exist, so you may use them when you need them.
No commentsOperators & Expressions in ASP
You are already familiar with some operators in JScript, even if you've never used a programming language before. In fact, you've already used some of them in the previous chapters, and they didn't look unusual at all to you.
The arithmetic operators are quite what you expect them to be, similar to the ones used in the basic arithmetic you learned in the first grade:
+ for addition
- for subtraction
* for multiplication
/ for division
% for modulus
++ increment
– decrement
The increment and decrement operators may seem a little stranger at first sight: they are used to increase, respectively decrease a variable by one. So, when you write
x = 1
x++
this means that x equals 2
You will see a lot more of these operators when we discuss the conditional structures and the loops below.
Note that the "+" sign can also be used as a string operator - for instance, when you need to put two strings of text together. Begin by assigning the text to a variable, and then use the "+" operator to bring them together:
text = "The capital city is ";
capital_city = "Washington";
text_complete = text + capital_city;
Now the text_complete variable contains the string "The capital city is Washington". Make sure you include the blank spaces in the string, or, if you want to use them separately, place them between quotation marks:
text = text1 + " " + text2 + " " + text3;
JScript also has assignment operators. You've used one of them to assign values to variables, and it probably "felt" quite normal:
x = 5;
meaning that you've assigned the value 5 to the variable x.
JScript also uses the compound assignment operators, which assign a value after performing the designed operation: x += y is the same as x = x + y. If both x and y are numeric or boolean, then they will be added, is both are strings, or only one of them is a string, they will be concatenated.
In the same way, you have:
x -= y the same as x = x - y
x += y the same as x = x * y
x /= y the same as x = x / y
x %= y the same as x = x % y
When you need to find out if x is equal to 5, you'll use one of the comparison operators: ==. So, x == 5 will return either "true" or "false". The comparison operators, all of whom return the values "true" or "false", as the following:
== for "is equal to"
!= for "is not equal to"
> for "is greater than"
< for "is less than"
>= for "is greater than or equal to"
<= for "is less than or equal to"
Finally, you have the logical operators. Again, you've probably seen these ones before as well:
! for "not"
&& for "end"
|| for "or"
Also like in regular arithmetic, parentheses are used to alter the order in which the operations are performed, meaning that the operations between brackets have the priority.
Considering the variables:
x = 1
y = 2
the comparison
x == y
will return "false", but the comparison
!(x == y) will return "true.
Considering the same variables, (x == 1 || y == 5) returns true.
Translated into plain English, this sounds like this: If x is equal to 1, and y is equal to 2, than the statement "Either x equals one OR y equals 5″ is true. Learning a programming language is a lot like learning a foreign language (a bit easier, though), so, when you tell the computer do to something, make sure you know exactly what you want to say, and then translate it into the respective programming language. Usually, there is more than one way for telling the computer to do the same thing, same is, in the English language, there are several sentences with the same meaning, and you decide which one you want to use.
So, when you "translate" from English into JScript, "if both x equals 1 AND y equals 5 " will look like (x == 1 && y == 5), and will return "false" (both in plain English and in JScript).
No commentsVariables in JScript
A programming language cannot function without variables. Variables are used to store, retrieve, and also manipulate the value it contains. Based on that value, a variable can contain a string, a number, a boolean value etc. To use a variable, you must first declare it, which means that some memory is allocated to store the variable, so you can refer to it later in your script. You can use the "var" statement to define a variable, and you can choose to initialize also initialize the variable. If you don't initialize a variable in the var statement, then it will be assigned the value "undefined".
var money; //a simple declaration
var first_number, second_number; //multiple declarations in one var keyword
var name1 = "Jack", name2 = "Laura"; //multiple declarations and initializations at the same time
You can always declare a variable without using the var keyword, and then assign a value to it:
price = 1500; // The variable price is declared implicitly.
Take a little time to assign the variable a meaningful name so you know what it holds. Because Jscript is a case-sensitive language, a variable name such as "MyName" is different from "myName". There are some rules in using variable names. First, remember that the first character of the variable must be a letter or the underscore character "_". While a number cannot be used as the first character, the following characters can be numbers, letters, and underscores.
Also, you should not assign a variable the same name as a reserved word.
As you may have noticed, you don't have to also declare the variable type. In other languages, this is a very important step, but JScript is very flexible from this point of view. Its variables have a type corresponding to the type of value they contain. The first benefit of this flexible feature is that you can treat a variable as if it were of another type. This means that if you try to "add" a number to a string, then the number will be converted to a string and then both variables will be concatenated. This process is called coercing. This way, adding a number or a boolean to a string will coerce the result into a string; the result of adding a number to a boolean variable will coerce the result to a number.
No commentsJScript Data Types
There three main (primitive) data types in JScript: string, number and boolean. Like in any other language, strings are collection of characters (letters, digits, signs, blanks, etc.) strung together. The string type is used mainly to represent text, and the string values must be enclosed in matching pairs of single or double quotation marks.
When it comes to numbers, Jscript doesn't differentiate integers and floating point values, like other languages do. Integer values can be positive whole numbers, negative whole numbers, and 0. You can represent these numbers in base 10 (decimal), base 8 (octal), and base 16 (hexadecimal), but most numbers in JScript are written in decimal. If you want to specify an octal integer, you should add a leading zero in front of the number containing digits from 0 to 7. If you add 8 or 9, the number will be interpreted as a decimal number. To represent hexadecimal integers, you must add the characters "0x" in front of the number. Hexadecimal numbers can contain digits from 0 through 9, and letters A through F.
Floating-point values are whole numbers with a decimal portion. You can also express these values using a scientific notation: the character "e" is used to represent "ten to the power of". You should know that numbers beginning with "0x" and "00″ who also contain a decimal point will generate an error, because floating-point values are available only for decimal values, and not also octal or hexadecimal values.
While a number and a string can contain lots of values, the boolean data type can only contain two: true or false. This is because a Boolean value is a truth-value, and it expresses whether an expression evaluates to true of false.
There are two special data types in JScript: "null" and "undefined". The null data type can only hold one value: null; this data type cannot be used as the name of a function or a variable. Data containing null is interpreted as containing "no value" or "no object". This means that is doesn't hold a valid number, string, boolean, array or object; so if you want to erase the contents of a variable, without deleting it, you can always assign it the null value.
The undefined data type is used instead of display some error messages, for example when some data has been declared, but no value was assigned to it.
No commentsJScript Syntax
The JScript code is written in text format like most other programming languages. It consists of blocks of statements, that, when combined together, create a script. You can find most programming tools within such a block: variables, expressions, calls to functions, and immediate data references such as strings and numbers (also called "literals").
A statement is like a sentence in English, and consists of one or more expressions, operators, keywords, etc. Statements are separated by semicolons ";", and, in most cases, a statement is written using a single line of text. Nevertheless, you can write a statement over two or more lines, most of all to improve the accessibility of it all. It's one thing to have write a statement using a really long line of text, where you must scroll a lot to actually "see it", and it's another to have the same statement written on multiple lines.
In the previous JScript we wrote, you can notice the semicolon at the end of the statement.
Response.Write("Hello World!");
Sometimes, you need to use multiple statements as if they were one. To do this, you must surround all these statements with bracers "{…}"; this is referred to as a block of statements. So even if JScript expects one statement, you can insert a whole block. There are some exceptions to this rule, and some of the most important are the headers of some functions such as "for" and "while". One more thing you might need to know is that, even though a statement ends with a semicolon, this rule does not apply to a block of statements.
Commenting your source code helps a lot. A comment is some text that is not taken into consideration by JScript when it parses the text, so it's there only for the user's "eyes". It helps a lot, as I was saying, because there are times when you want to get back to the script you just wrote, and you need to know what a script or a part of it does without actually browsing through its source code. You might also want to write down to-do's, tips about improvement, etc.
There are two ways you can use comments in JScript: single line comments and multi-line comments. Single-line comments are useful for small comments, when you need to add a to-do or small notice. To define a single line comment, you must add a pair of forward slashes "//", then the comment itself. Multi-line comments are useful for when writing details information about how the code works, copyright information etc. A multi-line comment begins with a forward slash followed by an asterisk "/*", and it ends with the opposite, the asterisk followed by the forward slash "*/". Here are some examples of both types:
/* This is a demo script
It is free of charge, and you can modify it as much as you want.
Copyright(C) softwareprojects 2004
*/
dbName = "database"; //the name of your database
dbHost = "localhost"; //the address of your database server
//to-do: add more info here
No commentsFirst ASP Script
You can write ASP scripts the same way you write HTML code. You don't need expensive tools or professional programming environment; you only need the most basic text editor in the world - Notepad - which can be found in any Windows version. Just like a HTML document, ASP files are made out of plain text. So let's give it a try. Click on Start, point to Programs, Accessories, than click on Notepad. Presto! Now type in the following text:
<html>
<body>
<%
Response.Write("Hello World!")
%>
</body>
</html>
That's it! Save the file to your "Inetpub\wwwroot\" folder, and give it an easy to remember name - "hello.asp". ASP files use the ".asp" extension, so remember to include this. To take a look at the output of the file, point your web-browser to "http://localhost/hello.asp". Now try to view the source of the document - right click somewhere on the page, and then click "View Source". You will not see the ASP source code, because your web-browser didn't receive it.
This way you can figure out for yourself that the web-server parses the text within the ASP tags - "<% (…) %>" - and leaves the rest of the HTML code untouched. While the previous example was made out of both HTML and ASP code, you can choose to use only ASP code:
<%
Response.Write("<html>")
Response.Write("<body>")
Response.Write("Hello World!")
Response.Write("</body>")
Response.Write("</html>")
%>
Save this file under the name "hello2.asp", in the same folder. Again, if you try to view its source after you have opened the file with your browser - "http://localhost/hello2.asp" - you will not see any ASP code. In fact, you will see the same HTML code as the previous "hello.asp".
There are two approaches to ASP scripting: VBScript or JScript. VBScript is the default scripting language, so you don't have to inform ASP that you're using it. But if you want to use JScript as the default language, you must insert a language specification at the top of the page:
<%@ language="javascript"%>
<html>
<body>
<%
Response.Write("Hello World!");
%>
</body>
</html>
While this might look the same at first, it's a complete different language. But the most important thing about it is that, unlike VBScript, JavaScript is CaSe SeNsItIvE. This means "Write" is not the same as "write", so you should really pay attention to your code.
The VBScript and JScript (which is Microsoft's implementation of JavaScript) languages are included in ASP, so you don't have to install any extra components. On the other hand, if you want to use another scripting language - for example Perl, REXX or Python - you will have to a script engine to handle that specific language.
1 commentInstalling ASP
No matter if you want to use ASP just to learn web-programming, or you want to create a major dynamic web-site, you must use a web-server that supports the ASP technology. There are two approaches to this. Either you choose to install Microsoft's Personal Web Server (PWS) or Internet Information Services (IIS) on your own PC, or you will have to find a web-hosting company running IIS which will host your web-site. If you're just looking to check out what ASP is all about, forget about the web-hosting company. Installing PWS or IIS on your computer is not such a big deal, and you don't have to be a highly qualified programmer to do this, some basic computer skills will do just fine.
First of all, you should know that there are different installation methods according to your Windows version. Even if you can install PWS on Windows 95, this operating system is really old and unstable, so you should forget about it. You should have at least Windows 98 if you want to use ASP, but Windows 2000 is highly recommended.
To run ASP on Windows 98, you have to install PWS from the Windows 98 CD. Explore the CD, and you will find the PWS in the Add-ons folder. Run setup.exe, and after the installation is done, you will find a folder called "Inetpub" on your hard-drive. Inside, there is another folder called "wwwroot", which holds all the files of your local web-server. Give it a try. Copy a HTML file in "wwwroot", and then open your web-browser and type in the address: "http://localhost/my_file.html". Don't forget to actually replace "my_file.html" with the name of your HTML file you copied. The same thing you must do when you want to use an ASP page.
To install ASP on Windows NT, you will have to download "Windows NT 4.0 Option Pack from Microsoft", because PWS is not included in Windows NT. This is not the case for Windows 2000. Click on Start, and select Settings, then Control Panel. Double-click Add/Remove Programs, then select Add/Remove Windows Components. A wizard window will show up on your screen, where you will see "Internet Information Services". Check that item, then click OK. Windows will then install IIS, and create the "Inetpub" folder. From now on, you can use IIS the same way you can use PWS on Windows 98. Check the previous section for additional details. But unlike Windows 98, you will see that the installation program has added a new icon on your taskbar - the IIS symbol. You should click the Start button that appears, so IIS can start.
Windows XP differs a little bit. You might know that there are two versions - Windows XP Home Edition and Windows XP Professional. Unfortunately, IIS is only available for Windows XP Professional. To install it, take a look at the previous section - the installation process of IIS on Windows XP Professional is identical to installing IIS on Windows 2000. You can start or stop the IIS web-server by going into the Control Panel, then the Administrative Tools. You will find the "IIS Manager" item, which you can double-click to view its properties.
Regardless of the operating system that you're using, don't forget to test the web-server after you have installed it.
1 commentWhat is ASP?
ASP stands for Active Server Pages, and it is Microsoft's implementation of server-side scripting. In short, this server-site scripting basically means that a script is parsed and executed by the server. When a user requests a web-page containing ASP, the web-server will parse code and send the result to the user, so the ASP code will never reach the user's browser. This is the exact opposite of JavaScript.
You don't need to be a programmer to understand ASP, but you should have some HTML knowledge, as the actual design of the web page will require it.
To use ASP scripts, you must have installed Microsoft's IIS (Internet Information Services), which is a web-server included in Windows 2000 and Windows XP Professional. It is also a part of the Windows NT 4.0 Option Pack, which can be downloaded from Microsoft's web-site. If IIS is not already installed on your computer, you can install it using the Add/Remove Programs section within the Windows Control Panel. The ASP engine is included within IIS, so you won't have to download it and install it separately. You must have Windows NT 4.0 or later to run IIS, so if you use Windows 98 you should install PWS (Personal Web Server), which is the smaller brother of IIS.
You can use ASP code to do a lot of things: dynamically edit, change or add any content to a web-page, access and query databases, read or write files, connect to remote computers, create images - the only limit is your imagination. The most obvious difference from HTML files is that ASP files have the extension ".asp", but this doesn't mean that you need to separate the ASP code from the HTML code in different files; you can use one file which will include both HTML and ASP code. The web-server won't mind at all, it will parse the ASP code and forget about the HTML code. Depending on your ASP code, the web-server will output some HTML instead of the ASP code, so the web-browser will only see HTML.
This provides a higher level of security, because nobody will be able to view your ASP code, and copy it and use it on their own web-page. Furthermore, you don't need any extra components for your web-browser, because the ASP files are returned in plain HTML, so they can be viewed in any web-browser.
In case you don't have Windows, you should know that some companies also didn't like the fact the ASP was only available for Windows platforms, so they decided to adapt ASP to other operating systems. So they created technologies like ChiliASP and iASP which allow you to take advantage of the ASP technology while using other web-servers, not just IIS. And because other web-servers run on many operating systems - like Apache web-server - this extends the ASP technology too, so it can run on other operating systems.
3 comments

Bas de Baar, blogging as "The Project Shrink", is taking his message to the International Project Management community with a vengeance: "Projects Are About Humans. Now Deal With That!" ...