Friday, September 5, 2008

ASP Basics

Let us start by creating a simple HTML file named a.html, using any text editor, and storing it in a subdirectory called wwwroot i.e. c:\inetpub\wwwroot.

a.html

hi

bye

We then start Internet Explorer (IE) to check-out the output. You can use Netscape or any other browser of your choice, since, it will not affect the output in any way. In the Internet Explorer Address bar, enter the following: c:\inetpub\wwwroot\a.html

The abovementioned line will beckon IE or the web browser to pick up a file called a.html from the wwwroot subdirectory and display its contents in the browser window. Thus, the resultant output is as follows:

Output

hi bye

Any text enclosed within a less than sign (<) and a greater than sign (>) is called an HTML tag. As the character 'b' is enclosed within <>, we call 'b' a tag. The 'b' tag indicates to the browser that everything following this tag is to be displayed in bold, until the browser encounters the same tag; however, it should be preceded by a / symbol. A tag preceded with a slash signifies the end of the tag. These tags are found in pairs. Thus, 'hi' is displayed in bold, whereas, 'bye' is displayed as normal text.

Thereafter, in IE, we rewrite the address as:

http://localhost/a.html

The output, to our pleasant surprise, remains unchanged.

(To be able to see the output as shown above, make sure you are running the IIS Web Server from Microsoft. In case you have not installed ASP.Net, please refer to the Installation section of the Introduction chapter in this book for details.)

The only difference between the current output and the one displayed earlier is that:

In the earlier case, the HTML file was obtained from a specified directory on our hard disk.

In this case, the HTML file has been obtained from the IIS Web Server.

How did this sudden variation occur?

Every machine on the Internet is recognized by a name. Thus, the Microsoft server on the Internet is called Microsoft, while our server is called vijaymukhi. In the same vein, as all human beings on the planet earth are called humans, every machine on the internet is recognized by the common nomenclature of 'localhost'. Hence, your machine and my machine, both share this common name. The World Wide Web or WWW is also technically described as http. Therefore, while executing http://localhost/a.html, IE requests the Web Server running on the local machine, to send back a file called a.html. Had we replaced the name localhost with Microsoft, the browser would have requested the web server running on the Microsoft machine, for the same file, a.html.

The pertinent question that crops up is "Where does the file a.html reside?"

To answer this question, we need to understand, that every Web Server has a default sub-directory or root directory through which it serves the requested files. The root directory could also be termed as the home directory. In the case of IIS, it hunts for the file in the subdirectory wwwroot of the directory inetpub on the default drive, which in this case is the c drive. Thus, the path along which it searches for the file is: c:\inetpub\wwwroot. IIS loads the file from disk and transfers the contents to IE for display. This file, when handed on to the Web Browser, can be viewed by clicking on the menu option View - Source. Regardless of the address that we type, the same HTML file is displayed in Notepad.

Now, we shall add one more tag to our HTML file.

a.html

hi

<$ hi $>

bye

First, we supply the location of the file in IE, i.e. c:\inetpub\wwwroot\a.html. The output displayed by the browser is as shown below.

Output

hi <$ hi $> bye

The output clearly indicates that the $ tag is alien to the browser. The HTML documentation lucidly lists all the possible valid tags of the HTML specification. So, we can safely conclude that if a browser does not support a tag, it simply ignores it and treats it akin to simple text. View-Source menuoption displays our hand-written html file.

In the next round, we give the address or the URL as http://localhost/a.html. The address of a file on Internet is also known as a URL or Uniform Resource Locator. The output that is displayed in the browser window is as follows:

Output

hi <$ hi $> bye

View-Source

hi

<$ hi $>

bye

Each time IIS stumbles upon a tag that it does not recognize, it simply sends the tag across to the browser. Thus, the $ tag too is sent to the browser. The file present on the server's hard disk is similar to the one that finally reaches the Web Browser.

In the context of the above explanation, we hope that you are truly able to appreciate the difference between the following:

Asking a Web Browser to read a file from the disk.

Requesting for the same file from the Web Server.

Let us now rename the same file as a.aspx. Here, we have merely changed the file extension and asked IE to fetch the file from the local hard disk. On providing the file location on the address bar, IE displays a dialog box that requests us to choose a program that shall open this file. We choose IE itself from the list of programs displayed.

The output we receive now is as shown below

Output

hi

<$ hi $>

bye

Since the file extension is not html anymore, the browser refuses to parse the tags contained in the file and displays it as is.

In the next instance, we ask the Web Server to pick up a.aspx, using the URL. On doing so, IIS seems to go into a slumber or appears to be preoccupied elsewhere. As a result, it takes a very long time to yield the output. It finally displays the following:

Output

hi <$ hi $> bye

View-Source

hi

<$ hi $>

bye

Thus, it may be observed that the Web Server behaves differently in this situation. It interprets a file with an aspx extension, as a special file and therefore, takes longer to process it than before. As before, it also sends the $ tag along with the other tags.

We shall now make a small change in the a.aspx file by replacing the $ sign with a % sign

a.aspx

hi

<% hi %>

bye

When IE displays the file from the local hard disk, the output remains unchanged.

Output

hi

<% hi %>

bye

A tag is a tag is a tag. IE does not understand the tag <$ or the tag <%. So, it ignores both of them.

In numerous instances, when you enter the same URL, i.e. http://localhost/a.aspx, IE may not request the Web Server to send the file again. It may simply display the same contents as it did earlier. This happens because, technically, IE fetches the file from its cache. Thus, you should invariably click on the refresh button to make a new request to the Web Server. We shall not remind you about this salient feature hereon.

On requesting IIS to fetch the file a.aspx, all hell seems to break loose. To our utter shock and dismay, we get the following error page:

Output

Server Error in '/' Application.

--------------------------------------------------------------------------

Compilation Error

Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: BC30451: The name 'hi' is not declared.

Source Error:

Line 1: hi

Line 2: <% hi %>

Line 3: bye

Source File: c:\inetpub\wwwroot\a.aspx Line: 2

Your sagging spirits are bound to receive a fillip on knowing that we did not commit a blunder in the above code. The only faux pas committed was that, one of the tags had been prefixed and suffixed by the symbol %, and it did not have a corresponding closing tag. The error message conveys to us that the name 'hi' is not declared. What does declare mean? In cricket, it means that one team decided not complete its innings. But in the world of programming, it has a very different connotation.

So what really went wrong?

After a significant amount of brainstorming, we deciphered that the Web Server understands and reads the text placed between the <% and %> symbols. These tags have a special significance for IIS and hence, we need to be extremely careful about the statements that are inserted within them. Further, on viewing the HTML source code, it was confirmed that the Web Server was greatly annoyed by this syntax. It conveyed its irritation by generating a large HTML file. All this ruckus was created for the lone word 'hi'. But IE does not seem to care.

Now, we shall carry out one more change in our aspx file.

a.aspx

hi

<% Response.Write("hell") %>

bye

The local file with the complete path gives the following output in the browser window:

Output : c:\inetpub\wwwroot\a.aspx

hi

<% Response.Write("hell") %>

bye

As before, IE ignores all the tags as it does not recognize the aspx extension. Henceforth, we will not request the Web Browser to fetch an aspx file from the hard disk.

When IE requests the Web Server for the same file, the output generated is as follows:

Output : http://localhost/a.aspx

hi hell bye

View-Source

hi

hell

bye

Finally, we have arrived at an error free program ! No error has been generated !! This goes on to prove that IIS gets involved when the tags are enclosed within the symbols <% and %>. However, it does not take any notice of the tags that are enclosed within the symbols <$ and $>. Thus, the symbol % indicates that the tag has a special significance as far as IIS is concerned.

The text Response.Write, with the word "hell" enclosed within double inverted commas, is converted into HTML 'hell' and sent over. Using the View-Source menuoption, observe carefully that the syntax Response.Write is not sent over. This concept of the Web Server being able to understand a % tag and specific syntaxes like Response.Write, forms the very core of ASP+ or Active Server Pages Plus.

The fundamental concept of ASP.Net is that, it merges the programming language code with HTML. You can place unlimited code between the <% and %> symbols which finally is executed by IIS, and the output is merged with the rest of the static HTML text.

Thus, ASP.Net is capable of creating dynamic web pages. If this had not been possible, the Internet would not have been such a "moving experience". All that the web server would have done then would be, serve static HTML pages, thus giving us a very limited range of experiences available on the Internet.

On the other hand, if the web server is well equipped to create dynamic HTML pages that do not originally exist on the server's hard disk, the variety of content that can be generated is boundless. This dynamism is extensively exploited in different garbs, by developers of web sites to build business applications.

In order to learn how to program ASP.Net, we have to ascertain what IIS understands. It understands text such as Response.Write.

Response.Write is called a function. A function is represented by a word that is followed by a pair of round brackets. IIS understands innumerable such functions. It is these functions that make the ASP.Net programming astoundingly powerful. Functions are like black boxes that are designed to accomplish specific tasks. As a programmer, you have to understand their functionality and syntax. You should know what a function accomplishes, and how it operates.

The function Response.Write accepts a word enclosed within double inverted commas. Technically, a word that is passed to this function is called a parameter. In a.aspx, the parameter passed to the Response.Write function is merged by the server with the HTML file.

In the ultimate analysis, an ASP.Net program is a concoction of static HTML text and code. The Web Server IIS, converts the code written within the tags <% %> into text, and thereafter, sends it over to the Web Browser. As the Web Browser can only accept and understand HTML files, it simply displays this file, ignoring the tags that it cannot comprehend. Thus, an aspx file undergoes dramatic transformation before it reaches the Web Browser. Consequently, a file on the server's hard disk is very different from the file that finally reaches the Web Browser.

ASP.Net is the single largest concept being used extensively to build Internet Enabled Applications. In order to appreciate the concepts more deeply, you need to study the source file using the View-Source menuoption. You can also execute the examples on the web server and ascertain for yourself, that the results produced are identical.

a.aspx

hi

<% Response.Write("hell ") %>

<% Response.Write("no") %>

bye

Output : http://localhost/a.aspx

hi hell no bye

You are at liberty to insert unlimited ASP.Net tags. All the extra spaces preceding or following the text within the tag are removed while displaying the output. The View-Source menuoption will make it unambiguously apparent that IIS sends the spaces over, but it is the Web Browser that filters them out and refuses to display them.

View-Source

hi

hell no

bye

a.aspx

hi

<% response.Write("hell") %>

bye

The letter r of the function Response is in lower case in the above program. However, IIS simply turns a blind eye to it and displays the same output as before. Thus, it can be concluded that IIS is not case sensitive.

We then initiate one more change in the program, we spell Write with an additional s.

a.aspx

hi

<% Response.Writes("hell") %>

bye

Output

Compiler Error Message: BC30456: The name 'Writes' is not a member of 'System.Web.HttpResponse'

Alas! An error message has been flashed. IIS can recognize only predefined functions, thus it informs us that it is not aware of a function called Writes.

It is because of the cryptic error messages generated by the programming languages, that people like us are in business. It is our job to decipher them for you. The two words, 'member' and 'function' are identical in meaning.

All these are rules and it is these rules that constitute a programming language. Within the ASP.Net tags, IIS works on the default assumption that we are following the rules of a language called VBScript. Our only grouse with VBScript is that it is a language of considerable vintage. Hence, we would rather use a language like C# which Microsoft has recently released, which is on the cutting edge of technology. So, we decided to write all our code in C#. In order to facilitate this, all that we need to do is, direct IIS to follow the rules of C#. This instruction is given using a directive.

a.aspx

<%@ language="C#" %>

hi

<% Response.Write("hell") %>

bye

Output

Compiler Error Message: CS1002: ; expected

Line 4: bye

We started our ASP.Net page with a % symbol as usual, but now we shall follow it up with a @ symbol. A directive in ASP.Net is indicated with the @ sign following the % sign. In a directive, we simply specify the language that we want to use.

The word language is called an attribute and we have initialized it to C#, the language that we want to use in the ASP.Net tags, henceforth.

Note that the name of the programming language is enclosed within double quotes. Most programmers of ASP.Net code however, may not use the double quotes since they are optional.

We have not yet removed the shrouds of mystery behind the error that has been generated. Every language has its own set of rules. In C#, every statement has to be terminated by a semi colon symbol i.e. ;. The absence of the semicolon at the end of the function statement, caused the error. It is pertinent for you to ask, as to why was the semi colon symbol selected ? Since, the C programming language used a ; symbol to mark the end of every statement, and thereafter, C++ and Java also adopted the same syntax, C# also chose to follow suit.

a.aspx

<%@ language=C# %>

hi

<% Response.Write("hell"); %>

bye

Output

hi hell bye

On inserting the semicolon, the error vanishes. Thus to conclude, a statement in VB takes an enter to mark the end of every statement, but in C#, it is mandatory to use a ; .

Let us now see as to what happens when we change the R of Response to lower case. If you recall, VB ignored it completely since it is case insensitive.

a.aspx

<%@ language=C# %>

hi

<% response.Write("hell"); %>

bye

Output

Compiler Error Message: CS0246: The type or namespace name 'response' could not be found (are you missing a using directive or an assembly reference?)

On changing the letter R to r, C# creates havoc, since the language is case sensitive. Thus, in C#, a lower case and an upper case R are two different characters. In this sense, C# is more restrictive than VB. The differences between them are not extensive, but they are sufficient to make you cling on to one of these programming languages.

a.aspx

<%@ language=C# %>

hi

<% Response.Write("hell"); %>

bye

Output

hi hell bye

Whatever parameter we pass to the Response.Write function gets sent over to the browser unchanged. IIS does not read this parameter at all. It simply makes it a part of the text file that it has to send over. The word 'hell' is underlined because of the u tag.

a.aspx

<%@ language=C# %>

hi

<% Response.Write(""); %>

bye

We now see the Windows 2000 logo displayed between the words 'hi' and 'bye'. IIS sends an html file containing an image tag over to the Web Browser. The attribute src with img denotes the name of the picture to be displayed.

When the browser sees the img tag, it reverts to the Web Server to obtain the image file. In this case, the specified file is win2000.gif, located in the wwwroot sub-directory. The Web Server sends this graphic file over and the Web Browser displays it.

The Web Server cannot send a mixture of a text file as well as graphic files at the same time. It can send only one of them at a time. The View-Source file menu option can be used to view the textfile .

a.aspx

<%@ language=C# %>

hi

<% Response.Write(vijay); %>

bye

Output

Compiler Error Message: CS0103: The name 'vijay' does not exist in the class or namespace 'ASP.a_aspx'

Line 3: <% Response.Write(vijay); %>

Initially, we shall display two lines of the error message, but once you get acquainted with the error screen, we will display the error message only. The first line contains the actual error message and the second line, depicted in red, indicates the position where according to C#, feels that the error has occurred. This is only an approximation, which may not be correct. The word vijay, without quotes, is passed as a parameter to the Response. Write function. Since, C# is not familiar with my name, it displays an error.

This really hurts my ego, because I thought I was known world over. 'Arrogance thy name is Vijay Mukhi !' you may say. So, how do we make the word vijay significant to C# ?

a.aspx

<%@ language=C# %>

hi

<%

String vijay;

vijay = "good";

Response.Write(vijay);

%>

bye

Output

hi good bye

Reason to Rejoice! No errors have been generated by the above program. Further, vijay has been replaced by the word 'good'. Are these two words linked in any way ?

Programmers will call vijay a variable. A variable is a word that can hold a value. We have created a variable called vijay, and in the next line, we have assigned it the value 'good'. Thus, from now on, wherever C# comes across vijay, it will replace it with the word 'good'. One mystery has been solved. Now, let us take the next one by its horns!

What is the word String doing in front of the variable vijay? This word is called a data type. It apprizes us of the nature of the content that the variable vijay shall store. Since, we want to store letters of the alphabet or words in vijay, we precede it with the String data type.

Whenever a variable is created, C# must be informed about the nature of data or the contents of the variable. C# recognizes a large number of data types.

One more question that may crop up in your mind to vex you is, "Why is vijay called a variable?"

a.aspx

<%@ language=C# %>

hi

<%

String vijay;

vijay = "hell";

Response.Write(vijay);

vijay = "no";

Response.Write(vijay);

%>

bye

Output

hi hellno bye

A variable is a word whose value can vary. The variable vijay first stored the value hell and then 'hi'. Thus, a variable can hold one value at one point in time, and a different value at another point in time. Every program that you pen down, will revolve around variables.

a.aspx

<%@ language=C# %>

hi

<%

String vijay;

vijay = "hell";

Response.Write(vijay + "
");

vijay = "no";

Response.Write(vijay);

%>

Output

hi hell

no

In the above program, we want to write the words hell and no, on two separate lines. To do so, we firstly add a + sign to join the two strings. The first string is our variable vijay, and the second string is an HTML tag br that results in a line break. The + sign does not attempt to add the two strings as is done in arithmetic, but concatenates them to form a single string. As a result, the final HTML file sent to the browser, is as follows:

View-Source

hi

hell
no

With this limited knowledge, we shall proceed to unravel the workings of a Search Engine.

Search Engines are programs that accept a word from you, and as soon as you click on a specified button, it generates a page with a list of sites containing the specified word.

Let us first fortify our knowledge of HTML by learning some more of its basics.

a.aspx

<%@ language=C# %>

The HTML tag input along with the attribute text, enables us to input characters just as we do in a textbox. This widget is used to accept data from the user.

a.aspx

<%@ language=C# %>


We have added another input tag with the attribute 'submit'. This generates a button on the screen. This button has the word Click as its label, because the value attribute is assigned the word Click. The attribute value for the textbox is vijay. Thus, vijay is displayed in the textbox when the page is loaded.

When we click on the button, nothing happens. Had we clicked on a similar button in a Search Engine, it would have displayed a page with the results of the search. Let us achieve the same functionality here also.

a.aspx

<%@ language=C# %>


a1.aspx

<%@ language=C# %>

Hi in a1.aspx

A new HTML tag called form, makes its debut in our aspx file. This tag has an attribute called action, which has been assigned the value a1.aspx. Similarly, the textbox has been given an attribute called name that has been initialized to aa.

In the textbox, we input vijay1 and click on the submit button. This act awakens IE, which searches for a tag called form, within the HTML file. The tag form also has an attribute called action, with the value a1.aspx. IE takes this value and creates a new URL as http://localhost/a1.apx. Since, only the filename is specified in the action attribute without any machine name, it defaults to the machine containing the file a.aspx.

With a URL in the action attribute followed by the file name will have the form tag as follows:

Once the address is framed, IE looks for all the controls in the HTML file which have the name attribute. We have a textbox called aa with a value of vijay1. On acquiring a name, IE adds a ? symbol and follows it up with the name=value pair. In our case, after ?, the text given is aa=vijay1. Thus, the IE address bar now reads as follows:

http://localhost/a1.aspx?aa=vijay1

The browser window has the following contents:

Hi in a1.aspx

The addition of the ? symbol, followed by the name=value pair, followed by the above course of action, is called CGI or the Common Gateway Interface. What if we had two textboxes?

a.aspx

<%@ language=C# %>



We have added one more textbox and named it bb. On clicking the submit button, the following URL is shown in the address bar:

http://localhost/a1.aspx?aa=vijay&bb=mukhi

IE uses the ampersand sign (&) as a delimiter between values of the textboxes. The web browser connects back to the Web Server requesting it for a1.aspx, and then transfers all the extra data that it has gathered. It is now the server's onus to hand over this data to the relevant file and send the output to the browser.

To do so, a1.aspx has to accept and process the data keyed in by the user. The next program in the series does just that. We will use the files a.aspx and a1.aspx throughout this chapter. Only when we make any change to these files, will we display their new contents. In the following program, the file a.aspx remains the same, whereas, a1.aspx has some new code inserted in it.

a1.aspx

<%@ language=C# %>

Hi in a1.aspx

<%

String a;

a = Request.QueryString["aa"];

Response.Write(a);

%>

Output

Hi in a1.aspx vijay

As before, we click on the button labeled Click. This generates the ouput 'Hi in a1.aspx vijay', signifying that the aspx file has retrieved the value given to aa and displayed it along with the text.

Lets look at the additional code added in the file a1.aspx. We first create a variable called ‘a' of type String. Then, we call a function Request.QueryString with one parameter, viz. aa, which is the name of the textbox. The parameter aa is enclosed within square brackets [] instead of round brackets ( ). These syntactical nuances have to be committed to memory, whenever we learn a new language. This function returns the value of the textbox aa, i.e. vijay, which is finally stored in a. Thereafter, the value is displayed using the Write function. A string enclosed in double inverted commas can instead be replaced with a variable of type String.

a1.aspx

<%@ language=C# %>

Hi in a1.aspx

<%

String a;

a = Request.QueryString["aa"];

Response.Write(a + "
");

a = Request.QueryString["bb"];

Response.Write(a);

%>

Output

Hi in a1.aspx vijay

mukhi

Just as we displayed one parameter value, we can also display another one. The same concept is relevant, except that the values supplied as parameters get altered. The variable a, first stores the word vijay, and subsequently, it stores the value mukhi. Thus, its value fluctuates.

Let us now write a program that has a superior level of built-in intelligence. It will display different values depending upon the name of the user. So, here we go!

a1.aspx

<%@ language=C# %>

Hi in a1.aspx

<%

String a;

a = Request.QueryString["aa"];

if ( a == "vijay")

Response.Write("

Welcome " + a + "

");

if ( a == "sonal")

Response.Write("

You are not Welcome " + a + "

");

%>

If we input the word sonal in the first textbox and click on the submit button, we get the following output:

Output

Hi in a1.aspx

You are not Welcome sonal

Now, if we input the word vijay, we get the following output:

Output

Hi in a1.aspx

Welcome vijay

Thereafter, if we input the word vijay1, the output obtained is as follows:

Output

Hi in a1.aspx

Thus, we get a different output depending upon the data entered in the textbox. This is only an elementary demonstration of code that generates dynamic pages.

One way of introducing dynamism is by using the 'if' statement. The 'if' statement inserts a lot of intelligence into our code. The 'if' statement checks whether the value of the variable a is equal to vijay or not. If the answer is yes, it executes the next line. If the answer is no, then the next line is ignored. Thus, we now have the ability to conditionally execute some code, depending upon the value of a variable.

Variables now seem to have come of age and have begun to prove their usefulness. The 'if' statement assists in making intelligent decisions. When the parameter aa holds the value of vijay, the first if statement is true, but the second one is false. Similarly, when the parameter aa has the value sonal , the first 'if' statement is false, whereas, the second one is true. In the last case, where the value is neither vijay nor sonal, none of the 'if' statements evaluate to true. Hence, no code within the % signs is executed.

We hope the use of the double 'equal to' , == to check for equality, did not slip your attention. It does not alter the value of a variable. It evaluates either to true or to false. A single 'equal to' symbol =, is used for assigning values.

a1.aspx

<%@ language=C# %>

Hi in a1.aspx

<%

String a;

a = Request.QueryString["aa"];

if ( a == "vijay")

Response.Write("

Welcome " + a + "

");

Response.Write("Not in the range of a if
");

if ( a == "sonal")

Response.Write("

You are not Welcome " + a + "

");

%>

Output

Hi in a1.aspx Not in the range of a if

You are not Welcome sonal

In the above program, when we typed in the word sonal in the textbox, surprisingly the Write function containing the text 'Not in the range of a if ', also got called. If you had been mindful and observant just a few paragraphs earlier, you would be able to remember us having stated very clearly that, the 'if' statement operates only on the immediately succeeding line. Thus, the second Write function does not come under the influence of the first 'if' statement. The default number of the lines under the influence of the 'if' statement, is only one.

What if we desire to have the next 10 lines controlled by the 'if' statement ? The next program has the answer to that.

a1.aspx

<%@ language=C# %>

Hi in a1.aspx

<%

String a;

a = Request.QueryString["aa"];

if ( a == "vijay")

{

Response.Write("

Welcome " + a + "

");

Response.Write("Not in the range of a if
");

}

if ( a == "sonal")

Response.Write("

You are not Welcome " + a + "

");

%>

Output

Hi in a1.aspx

You are not Welcome sonal

The only way to execute or bypass a block of statements with the 'if' statement is, by placing them within curly braces. Code written in curly braces is treated as one lengthy statement. Thus, if there are more than one statement to be executed by the 'if' statement, the code should be placed in curly braces.

a1.aspx

<%@ language=C# %>

Hi in a1.aspx

<%

String a;

a = Request.QueryString["aa"];

if ( a == "vijay")

Response.Write("

Welcome " + a + "

");

else

Response.Write("

You are not Welcome " + a + "

");

%>

Output

Hi in a1.aspx

You are not Welcome sonal1

The data entered in the textbox is sonal1. In a1.aspx, C# stores this value in the variable a and then checks the value against vijay, using the 'if' statement. As the content of the variable a is not vijay, the 'if' statement becomes false. Hence, the 'else' statement is executed. The 'else' statement can only be used as part of the 'if' statement. When the 'if'' statement is false, the code associated with the 'else' statement is executed. Conversely, when the 'if' statement is true, the code associated with the 'else' statement is ignored. Therefore, under any eventuality, either the 'if' or the 'else' gets called, in other words, only one of them is executed.

We now run the program a1.aspx directly, using http://localhost/a1.aspx.

a1.aspx

<%@ language=C# %>

Hi in a1.aspx

<%

int i;

i = 10;

Response.Write(i);

%>

Output

Hi in a1.aspx 10

We have made a few changes to our above program. We first created a variable i of type int and not of type String, as given earlier. String and int are called classes; and i, which is a variable of these types, is called an object. An object is technically an instance of a class. The idea behind introducing these remarkable words is to enable you to overawe people with your profound knowledge of programming.

The variable i can now store numbers, since its data type is an int, i.e. an integer. It is initialized to a number, 10. Then we used the same old Response.Write function to display this number.

ASP.Net gives us a large number of free objects such as Response and Request. Before the book winds up, we shall certainly explain all the free objects. The object Response has innumerable functions, and Write is just one of them. We use a dot(.) to separate the object name from the function name. The use of the dot forms one of the rules of the C# programming language. Onto the next program.

a1.aspx

<%@ language=C# %>

<%

int i;

i = 10;

Response.Write(i + " ");

i = 20;

Response.Write(i + " ");

i = i + 10;

Response.Write(i + " ");

i = i + 1;

Response.Write(i + " ");

i++;

Response.Write(i + " ");

%>

Output

10 20 30 31 32

Let us understand variables from a different perspective. We first created an int i and gave it a value of 10. We then displayed it using the Write function. We also added a space within double quotes at the end of the display to space them out. The familiar + sign is used to concatenate a blank space with the value of i. The + sign is not used literally to add numbers, but to join a number and a string. The value of the variable i is then modified to 20. Thereafter, we display this value in the manner described earlier.

Now, we come across a strange line containing the text i = i + 10. An expression with an 'equal to' sign must always be evaluated from right to left. The variable i in the expression i + 10 gets replaced by the number 20 and the final expression evaluates to 20+10, summing up to the final value of 30. Once C# finishes evaluating the right hand side of the 'equal to' sign, it simply assigns this new value to the variable on the left hand side. Hence, the variable i now receives the new value of 30. If you find this confusing, you can run through the explanation once again.

The next line simply increments the value of i by 1. Hence, its new value is now 31.

The facility of incrementing the value of a variable by 1, is required very often in programming. Therefore, C# has provided a short form. The expression i++ increases the value of the variable i by 1. You can even use the expression i=i+1 interchangeably.

a1.aspx

<%@ language=C# %>

<%

Response.Write( 6 >9 );

Response.Write(" ");

Response.Write( 16 > 9 );

Response.Write(" ");

Response.Write( 6 <>

Response.Write(" ");

Response.Write( 6 <>

Response.Write(" ");

Response.Write( 6 <= 6 );

Response.Write(" ");

Response.Write( 6 == 6 );

Response.Write(" ");

Response.Write( 6 == 7 );

Response.Write(" ");

Response.Write( 6 != 7 );

Response.Write(" ");

Response.Write( 6 != 6 );

%>

Output

False True False False True True False True False

The above program has thrown a volley of questions.

The first Write function displays the answer to the question "Is 6 > 9?". Since the number 6 is not greater than the number 9, the answer is either False or No. The plus sign +, the minus sign -, and the greater than > sign are all called operators.

The next question is 'Is 16 > 9?', and the answer obviously is Yes or True. Anything that results in True or False is called a condition. Thus, the expression 16 > 9 is called a condition. Next, we have another condition 6 <>

We are permitted to use a combination of operators. Thus, the condition 6 <= 6 evaluates to True. The == operator that had been used earlier to compare strings, can be used to compare numbers too. The number 6 is equal to 6, but not equal to 7.

The last operator is != , which is the 'Not Equal To' operator. It is reverse of the == operator.

a1.aspx

<%@ language=C# %>

<%

int i = 7;

if ( i > 5)

Response.Write("true");

else

Response.Write("false");

%>

Output

True

An 'if' statement either evaluates to a True or to a False. Therefore, conditions can be placed within an 'if' statement. As the condition in the 'if' statement i > 7 is True, True is displayed in the browser.

a1.aspx

<%@ language=C# %>

<%

int i = 7;

if ( i )

Response.Write("true");

else

Response.Write("false");

%>

Output

Compiler Error Message: CS0029: Cannot implicitly convert type 'int' to 'bool'

Line 4: if ( i )

The C# language is a stickler for rules. It expects specific data types at certain places. If this rule is violated, an error is generated, as seen above. In the 'if' statement, C# expects a logical value of True or False and not a numerical value. Unlike many other languages, the C# language is considerably ruthless when it stumbles upon any such mistakes. However, we prefer the C# way of checking the source code rigidly and thoroughly.

a1.aspx

<%@ language=C# %>

<%

bool b;

b = true;

if ( b )

Response.Write("true ");

b = false;

if ( b )

Response.Write("false");

b = 6 > 1;

if ( b )

Response.Write("false");

%>

Output

true false

We had mentioned earlier that there are numerous classes available in ASP.Net. So far, we have seen only two of them, i.e. int and String. In this program, we have introduced one more class called bool. The variable b is of type bool, so it can only store either a value of True or False. The C# programming language recognizes the words true and false, and hence, they are termed as reserved words. The variable b is initialized to True. Since the 'if' statement requires a logical value or a value of type bool, the expression if (b) evaluates to the expression if(true). Hence, no error is generated. Then, as the next value of b is false, the 'if' statement evaluates to false. Therefore, the Write function is not executed.

All the logical operators <, >, ==, !- etc. return a bool value. Hence, they can be used with ease within the 'if' statement.

a1.aspx

<%@ language=C# %>

<%

int i;

for ( i = 1; i<=5;i++)

Response.Write(i + " " );

%>

Output

1 2 3 4 5

Very often, we like to do certain things repeatedly in life, such as having a cup of coffee 10 times in a day. The computer programs too use the same analogy to repeat certain instructions. Just as the 'if' statement assisted us in making our programs more intelligent and decisive, the 'for' statement facilitates repetition of specific code.

A 'for' statement incorporates two semicolons. The explanation of the 'for' statement is as follows:

The instruction up to the first semicolon is executed only once. So, the variable i is assigned the value of 1 only once.

Then, the condition i<= 5 is checked. If this condition results in True, which is what the present situation is because the value of the variable i is 1, C# proceeds to execute the next line. The Response.Write function replaces the value of i with 1, thereby, displaying the value of 1 in the window.

After executing the instruction following the 'for' statement, the statement after the second semicolon is executed. The statement i++ increments the value of i to 2. This value of i is again checked with the condition i <= 5. Since 2 is less than 5, the Write function prints 2 and proceeds to execute the statement i++. The value of i now becomes 3 and the same loop repeats itself again.

When the value of i becomes 6, the condition fails and the loop is terminated. We have executed the Write function 5 times without writing the function 5 times.

a1.aspx

<%@ language=C# %>

<%

int i;

for ( i = 1; i<=5;i++)

Response.Write(i + " " );

Response.Write(i + "..." );

%>

Output

1 2 3 4 5 6...

The above program proves that the 'for' statement, like the 'if' statement, acts only on the immediately succeeding line, by default. Also, when the last Write function gets called after the 'for' loop finishes execution, the value of i is displayed as 6 with two trailing dots. This output confirms our explanation of the for loop laid down earlier.

a1.aspx

<%@ language=C# %>

<%

int i;

for ( i = 1; i<=3;i++) {

Response.Write(i + " " );

Response.Write(i + "..." );

}

%>

Output

1 1...2 2...3 3...

If we want the 'for' loop to have control over multiple statements, we have to use curly braces { } to enclose the following code, just as we had done in the 'if' statement. On doing so, both the Write functions get called thrice.

a1.aspx

<%@ language=C# %>

<%

int i;

i = 1;

while ( i<=3)

{

Response.Write(i + " " );

i++;

}

%>

Output

1 2 3

There are a million ways of achieving the same result in a programming language. Our blood pressure is bound to mount upwards if we have to keep learning new ways of arriving at the same outcome. All the same, it is not irrelevant to mention here that the 'while' statement performs the same job as the 'for' statement.

The variable i is initialized to the value of 1, prior to entering the 'while' statement. The 'while' statement evaluates a condition. If the condition is true, it enters the loop, however. if the condition is false, it terminates the loop. In this case, since i is less than 3, the function Write displays 1. Thereafter, the statement i++ increments the value of i by 1. The condition is checked again to determine if the value of i is less than 3. When the value of i becomes 4, the condition becomes false and the loop terminates.

Thus, the 'for' and 'while' loops achieve the same functionality. They differ only in the syntax. You are at liberty to select any of the constructs that you fancy. If you have difficulty in taking a decision, tossing a coin may be the best option. If it is heads, you may use a 'for' loop, and if it turns out to be tails, you may use a 'while' loop.

a1.aspx

<%@ language=C# %>

<%

int i;

for ( i = 1 ; i <= 3; i++)

Response.Write(" hi ");

%>

Output

hi hi hi

Let us now explore the convenience that a loop provides to help us write code, which otherwise would have been difficult to write. The font tag in HTML takes an attribute called size. This tag determines the size of the font for the text to be displayed. Using the 'for' loop, we are assigning different values to the variable i in such a way that we get three different font tags, each of which has different values for the size attribute. The View-Source output endorses our statement.

View Source

hi

hi

hi

a1.aspx

<%@ language=C# %>

<% int i = 10; %>

<%= i %>

Output

10

There are a number of shortcuts in ASP.Net. One of them being, the expression <%= which is an equivalent of the function Response.Write. Only the parameter supplied to the Response.Write function is used with %=. It is mandatory to insert a space after the 'equal to' sign.

The code using the <%= expression is very compact and precise, and it does not require a semicolon at the end of the statement. Let us incorporate this directive in the next example.

a1.aspx

<%@ language=C# %>

<%

int i;

for ( i = 1; i<=3 ; i++)

{

%>

> hi

<% } %>

The output of the above program is similar to that of a previous program. The only variation is in the style and approach. If you observe very carefully, the file contains ASP.Net tags, as well as HTML tags. Unlike the earlier case, where the code contained only ASP.Net tags, the source code in this case, uses ASP.Net and HTML. Thus, the font tag is written in HTML with the exception of the attribute size.

Since, a different value is required each time, variable i is enclosed within % tags. Moreover, in a 'for' statement, only the first line following the 'for' statement is acted upon by the 'for' loop, unless we enclose multiple lines using curly braces. Here, the variable i, the 'for' loop and the curly braces are also enclosed within the ASP.Net tags. Thus, we are able to dynamically generate different HTML tags. Finally, all the code is translated into an HTML file for the convenience of the Web Browser.

All the HTML tags in an aspx file are converted into one gigantic C# program, wherein, the static HTML tags are converted into parameters to the Response.Write function. Someday, we shall disclose to you the source of the above information. The final transition is from one large C# program to one large HTML file.

a1.aspx

<%@ language=C# %>

<%

int i;

for ( i = 1; i<=3 ; i++)

{

%>

> hi >

<% } %>

Output

hi

hi

hi

The word 'hi' is displayed in three different sizes because, the heading tag (h) changes with each iteration of the 'for' statement. This program is very similar to the font program seen earlier. The View-Source menuoption will clear all the cobwebs in your mind, in this regard.

View-Source

hi

hi

hi

When the 'for' loop iterates, the h tag changes from h1 to h2 and then to h3. The same logic is applied for the closing tag also.

a1.aspx

<%@ language=C# %>

bye

<%

if ( false)

%>

hi

Output

bye

Since, the 'if' condition has a false value, 'hi' is not displayed in the browser window. Thus, we can safely assume that the C# code acts upon HTML statements.

Let us look at it this way: Since all the code is finally amalgamated into one large C# program, the 'if' statement does not act on the HTML text 'hi', but on the function Response.Write("hi").

a1.aspx

<%@ language=C# %>

<%

abc();

%>

Output

Compiler Error Message: CS0103: The name 'abc' does not exist in the class or namespace 'ASP.a1_aspx'

Line 3: abc();

Here, we are calling a function called abc by writing its name, following it by a pair of round brackets, and then ending it with a semicolon. The compiler reports an error as there is no function called abc. This error is pretty obvious. The function call to a non-existent function was done on purpose to educate you on the error messages thrown up by the compiler.

The next series of programs will focus on writing functions and making function calls.

a1.aspx

<%@ language=C# %>

<%

abc();

%>

Output

abc

A function in an aspx file is created within an HTML tag called script. This tag uses two attributes:

The first one called language, is used to denote the language used in the code that follows.

The second one, called runat, is used to indicate the location where the execution of the code should take place.

In our file, we have stated that the language to be used in the function is C#, and it is the server that should execute the code, not the browser.

To create a function in C#, we simply write the name of the function followed by (). Then, within the pair of curly braces, we are free to write as much code as our heart desires. As of now, we have included a simple call to the Write function. The word void will be explained shortly, as we believe in explaining 'one concept at a time'.

Thus, a function is created following one set of rules and executed following another set of rules.

a1.aspx

<%@ language=C# %>

<%

abc();

pqr();

abc();

%>

Output

abc pqr abc abc

We are at liberty to create as many functions as we like. In the above program, we have created two functions, abc and pqr. First, a call is made to function abc which simply prints abc. Then, the function pqr is called, which prints the word pqr and calls the function abc. Hence, the word abc is displayed again.

There is no difference between calling functions like Write, written by the programmers at Microsoft, and calling functions like abc written by us. The call to the function abc by the function pqr again proves that we can call the function abc as many times as we like.

a1.aspx

<%@ language=C# %>

<%

abc("hi");

%>

Output

Compiler Error Message: CS1501: No overload for method 'abc' takes '1' arguments

Line 9: abc("hi");

Remember a cardinal rule in programming: "Write one line of code at a time and check for errors". The only way to be proficient in programming is by reading and deciphering error messages, no matter how cryptic they may be. Here, we are passing a string parameter while calling the function abc, but the function does not accept any parameters. Hence, the error is generated.

C# is very meticulous in matching the type and number of parameters that are actually passed to a function with the parameters that it expects. Since the function in the above example does not except any parameters, we've made a cardinal mistake by passing it one.

a1.aspx

<%@ language=C# %>

<%

String s = "bye";

abc("hi",s);

%>

Output

hi bye

This time, we have got it right. We are calling the function abc with two parameters 'hi' and 's'. The variable s is of type string and is initialized to the string 'bye'. So, in a sense, we are calling abc and passing it two strings as parameters, within the open and close brackets. In the script, abc is created with two variables i and j, both of which are type String or class String. These variables receive the values 'hi' and 'bye' from the function abc, respectively. These values are thereafter displayed using the Write function.

While executing the code at the server's end, C# pauses for a moment before assigning the value to j. This is because, 's' has to first be converted to 'bye', and then sent over as a parameter value to j. Thus, if we use variables, C# takes an extra step and replaces the variable with the value. The advantage of using variables is that, when we change its value, something altogether different happens.

a1.aspx

<%@ language=C# %>

<%

String s = "bye";

abc("hi",10);

%>

Output

Compiler Error Message: CS1502: The best overloaded method match for 'ASP.a1_aspx.abc(string, string)' has some invalid arguments

Line 10: abc("hi",10);

We may fall asleep at the wheel, but the C# compiler keeps a constant vigil. It constantly scrutinizes our code, hunting for errors. In the earlier example, C# expected the second parameter to the function, to be a string; whereas, we have passed a number. The error message could have been more lucid, but no one heeds our advise.

a1.aspx

<%@ language=C# %>

<%

abc(20,10);

%>

Output

Compiler Error Message: CS0161: 'ASP.a1_aspx.abc(int, int)': not all code paths return a value

And yet another crime has been committed. Carrying out a slight modification to our earlier function abc, we changed the word void to int, and the compiler generated an error. It is time to tackle the words void and int that precede a function name.

a1.aspx

<%@ language=C# %>

<%

int k;

k = abc(20,10);

Response.Write(k);

%>

Output

30

The function abc adds two numbers that are passed to it as parameters and returns the result. In this case, the numbers 20 and 10 are stored in variables, or parameters i and j in the function abc. To return a value, the keyword return is used with the number. The function abc returns the sum of 20+10 i.e. 30.

The function call abc(20,10) is now replaced by the return value, and this return value is assigned to the variable k. Thus, when the word int precedes a function name, it signifies that an integer value will be returned. Had we written String instead, the function would have to return a String, instead of an int. No code following the return statement gets called. Hence, the word 'hi' is not displayed. Thus, program execution of a function halts when it encounters a return statement.

a1.aspx

<%@ language=C# %>

<%

abc(20,10);

%>

Output

Compiler Error Message: CS0127: Since 'ASP.a1_aspx.abc(int, int)' returns void, a return keyword must not be followed by an object expression

The word void signifies that the function does not return any value. Since we tried to return a value, in spite of the fact that the return type of the function is void, an error was generated. Whenever a function does not return any value, we have to declare the return type to be void. But, if we do specify a return type, then we must ensure that the value returned by the function is of this type.

Your Title