Sie sind auf Seite 1von 414

Introduction

ASP.Net provides the most powerful environment for development of sophisticated, real-life business applications. It was only natural for us to get sucked into the vortex of the exciting opportunity that this language provides, to satiate our technical appetite. This book presents a realistic tableau of the vast repertoire of features of the ASP.Net language. We have scythed through the maze of technological jargon to present to you, in a simple yet comprehensive manner, all the salient features of the language.

The book commences with the assumption that you are a programming tyro, with no previous knowledge of ASP.Net or C#. It however, expects you to have a working knowledge of the Hyper Text Markup Language (HTML). The book covers the length and breadth of the ASP.Net framework. Since the C# language has been used for programming, the fundamentals of this language have also been covered.

The book begins with the basics of the ASP.Net and C#. Thereafter, it moves on to the built-in controls of ASP.Net. Next, it demonstrates how you can build your own custom controls. The text then veers on to the concepts of the built-in C# classes, and shows you how to build your own custom classes. It also covers the myriad aspects of handling databases, advanced concepts of controls, mysteries of Cookies, CGI Progamming and state management,Web Services and finally a Class Browser Application. It finally winds up with a peek into the security issues of designing an Internet application using ASP.Net. Thus, youll be able to appreciate, that a vast array of technical concepts of ASP.Net have been covered by this book.

This book is teeming with examples and explanations that discuss each concept threadbare. The various disparate concepts have been woven together to create a beautiful tapestry of the ASP.Net language. It has always been our modus operandi to break up large programs into smaller fragments, comprehend each fragment thoroughly and subsequently, synthesize all the fragments together to retrieve the original program. The same strategy has been employed in this book also. Each concept has been substantiated with examples so that you can see how each concept is implemented in real-life applications.

In our books, we have presented examples that emulate a concept supplied in the documentation, or some idea we found on the Internet. However, some of the concepts introduced are purely ours, and thus original. As far as we are concerned, you are free to use our accepted wisdom, as long as someone somewhere in the world benefits from it.

We are sanguine that this book will go a long way in providing ample food for thought, to sate the technological hunger of your minds. We implore you to put in sedulous effort in mastering this language, by reading all the material provided to you in this book with sincerity, and also by trying out all the examples that have been presented. We are confident that on doing so, you will be able to scale dizzying heights in the world of Internet programming.

Requirements

The software requirements to successfully run all the programs in this book are

Operating System - Windows 2000 Microsoft IIS ver 5.0 SQLServer 2000 (Evaluation Edition) Internet Explorer 5.5 .Net Framework SDK Beta 2 (111 MB)

Internet Explorer 5.5 can be downloaded off the Microsoft site

http://www.microsoft.com/windows/ie/download/ie55sp1.htm

Net Framework SDK Beta 2 can be downloaded off the Microsoft site

http://download.microsoft.com/download/VisualStudioNET/Trial/2.0/W982KMeXP/ENUS/setup.exe

Alternatively, you can visit the download section at Microsoft ( http://msdn.microsoft.com/downloads/default.asp ) and download the .Net framework SDK Beta 2 under the Software Development Kit option.

SQLServer 200
While installing the evaluation edition of SQLServer 2000, we have chosen the default selected settings. The only modification made is in the Authentication Dialog Box.

You see two options

Windows Authentication mode

Mixed mode (Windows Authentication and SQL Server Mode)

The default option selected is Windows Authentication mode. We have instead selected Mixed mode (Windows Authentication and SQL Server Mode). Once this option is selected, the password text boxes for the sa user gets activated. As we would prefer using a blank password in our programs, we select Blank Password. On selecting this option, the text boxes get disabled again.

Acknowledgements

We wish to thank a number of people who gave us their support, new ideas and inspiration while writing this book.

First and foremost, thanks to Manish Jain, BPB Publications for publishing the book.

To my co-authors, Sonal and Neha who have put in a lot of hard work to complete the work assigned to them.

To Tanuja Sodhi, an ex-Naval Officer from the first batch of lady officers and an MBA from Jamnalal Bajaj, for editing the book. She is presently freelancing as a creative writer.

To Altaf Hemani and Kishore Rohra, for designing the cover.

Thanks to Manish Purohit for putting in all the time he had to verify the code with the explanation, testing all the applications in the book and updated them to work under the Release version of the product.

To Pradeep Mukhi and Shivanand Shetty, who have always been there, as a source of inspiration and encouragement.

My Mother, Shana Aunty and a long list of friends need a mention here for their patience and cooperation on this book while it was being written.

-1-

Getting Started
This book strikes up with the basics of ASP.Net or ASP+. We shall get started with the assumption that you are a total novice as far as ASP.Net is concerned. We will go to the extent, that even the full form of the acronym ASP sounds queer to you. We also presume that you are unable to comprehend any programming language. Therefore, we will commence with the absolute fundamentals. We do however take for granted, that you possess the basic knowledge of the Hyper Text Markup Language (HTML).

So, now that we have divulged all our assumptions, let us get focused on writing code, and applications that achieve useful results. It is our sincere aspiration that the knowledge imparted by this book, goes a long way in furthering your career in the Information Technology field.

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 <b> hi </b> 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 < and >, 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:

disk.

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

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 subdirectory 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 <b> hi </b> <$ 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 <b> hi </b> <$ 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 <b> hi </b> <$ 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 <b> hi </b> <$ 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 <b> hi </b> <% hi %> bye

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

Output <b> hi </b> <% 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: <b> hi </b> 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 <b> hi </b> <% 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 <b> hi </b> <% 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 <b> hi </b> 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 <b> hi </b>

<% 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 <b> hi </b> hell bye a.aspx <b> hi </b> <% response.Write("hell") %> bye no

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 <b> hi </b> <% 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#" %> <b> hi </b>

<% 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# %> <b> hi </b> <% 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# %> <b> hi </b> <% 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# %> <b> hi </b> <% Response.Write("<u>hell</u>"); %> 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# %> <b> hi </b> <% Response.Write("<img src=win2000.gif>"); %> 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 menuoption can be used to view the textfile .

a.aspx <%@ language=C# %> <b> hi </b> <% 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# %>

<b> hi </b> <% 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# %> <b> hi </b> <% 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# %> <b> hi </b>

<% String vijay; vijay = "hell"; Response.Write(vijay + "<br>"); 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 <b> hi </b> hell<br>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# %> <input type= text >

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# %> <input type= text value=vijay> <br> <input type= submit value=Click >

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# %> <form action=a1.aspx> <input type= text value=vijay name=aa> <br> <input type= submit value=Click > </form>

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:

<form action=http://localhost/a1.aspx>

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# %> <form action=a1.aspx> <input type= text value=vijay name=aa> <br> <input type= text value=mukhi name=bb> <br> <input type= submit value=Click > </form>

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 + "<br>"); 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("<h1> Welcome " + a + "</h1>"); if ( a == "sonal") Response.Write("<h2> You are not Welcome " + a + "</h2>"); %>

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("<h1> Welcome " + a + "</h1>"); Response.Write("Not in the range of a if <br>"); if ( a == "sonal") Response.Write("<h2> You are not Welcome " + a + "</h2>"); %>

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("<h1> Welcome " + a + "</h1>"); Response.Write("Not in the range of a if <br>"); } if ( a == "sonal") Response.Write("<h2> You are not Welcome " + a + "</h2>"); %>

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("<h1> Welcome " + a + "</h1>"); else Response.Write("<h2> You are not Welcome " + a + "</h2>"); %> 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 < 2 ); Response.Write(" "); Response.Write( 6 < 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 < 2, which evaluates to false. Following this is the condition 6 < 6 which is also false, since the number 6 is equal to the number 6 and not less than 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 12345

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 123

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("<font size = " + i + " > hi </font>"); %>

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 <font size = 1 > hi </font> <font size = 2 > hi </font> <font size = 3 > hi </font>

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++) { %> <font size= <%= i %> > hi </font>

<% } %>

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++) { %> <h<%= i %> > hi </h<%= i %> > <% } %>

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 <h1 > hi </h1 > <h2 > hi </h2 > <h3 > hi </h3 >

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# %> <script langauage="C#" runat=server> void abc() { Response.Write("abc"); } </script> <% 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# %> <script langauage="C#" runat=server> void abc() { Response.Write("abc "); } void pqr() { Response.Write("pqr "); abc(); } </script> <%

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# %> <script langauage="C#" runat=server> void abc() { Response.Write("abc "); } </script>

<% 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# %> <script langauage="C#" runat=server> void abc( String i, String j) { Response.Write(i + " " + j); } </script>

<% 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# %> <script langauage="C#" runat=server> void abc( String i, String j) { Response.Write(i + " " + j); }

</script> <% 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# %> <script langauage="C#" runat=server> int abc( int i, int j) { } </script> <% 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# %> <script langauage="C#" runat=server> int abc( int i, int j) { return i + j; Response.Write("hi"); } </script> <% 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# %> <script langauage="C#" runat=server> void abc( int i, int j) { return i + j; } </script> <% 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.

-2-

Server Controls
In this chapter, we will use the controls freely available with IIS to build a real life application in ASP+. Once you get familiar with the workings of these controls, we will then show you how you can build a similar control yourself. So get hooked on to your computer and start on.

The file a.aspx, sent by the server, will display a textbox and a button in the browser window.

a.aspx <%@ language=C# %> <form action="a1.aspx" > <asp:textbox id="aa" runat="server"/> <asp:button text="Click a.aspx" runat="server" /> </form>

a1.aspx <%@ language=C# %> <form action="a1.aspx" > Name: <asp:textbox id="aa" runat="server"/>

<asp:button text="Click a1.aspx" runat="server"/> </form>

You may be tempted to ask as to what is so unique about a textbox and a button.

To begin with, we have not used any HTML tags to generate these two controls. A special tag asp:textbox has been implemented, using two attributes called id and runat. In a similar manner, a tag called asp:button, having the attributes text and runat, has been employed for the button. This ASP.Net directive asks the server to generate the HTML tags for the corresponding user interface widgets, at the server end with the specified attributes. The View-Source menuoption displays the following in respect of a.aspx:

View-Source <form action="a1.aspx" > <input name="aa" type="text" id="aa" /> <input type="submit" name="ctrl2" value="Click a.aspx" /> </form>

When these special ASP.Net tags are converted into input tags in the HTML file, the attribute runat is discarded. Further, the button is not assigned any name in the aspx file, due to the missing id attribute. Therefore, the server names it ctrl2. The View-Source confirms that the aspx file now resembles an HTML file.

After the text vijay12 is entered in the textbox and the submit button is clicked, the IE requests for the file a1.aspx and the address bar changes to:

http://localhost/a1.aspx?aa=vijay12&ctrl2=Click+a.aspx

But to our astonishment, the textbox is blank despite the fact that we entered the word vijay12 in it. All the details that were entered in the earlier browser windows too are nowhere to be seen. The View-Source displays the same contents as before.

View-Source <form action="a1.aspx" > Name: <input name="aa" type="text" id="aa" /> <input type="submit" name="ctrl2" value="Click a1.aspx" /> </form>

When we click on the button after writing 'no', the address bar changes tohttp://localhost/a1.aspx?aa=no&ctrl2=Click+a1.aspx but the output displayed by View-Source remains the same.

View-Source <form action="a1.aspx" > Name: <input name="aa" type="text" id="aa" /> <input type="submit" name="ctrl2" value="Click a1.aspx" /> </form>

This erratic behavior is the outcome of initializing the action form with the name a1.aspx, which is also the name of the file in which it is contained. The server discards any data that is typed in. Hence, the fields are initialized to default blank values.

Take a situation where we have a large form with numerous fields. You may enter all the data correctly, barring one, where you may have committed some error. In consonance with the behavior illustrated above, all the fields will be returned empty. They will have to be retyped, thereby compelling us to be cautious in future while entering data. This is the penalty that we get, for being inattentive while entering data.

A better way out would be to redisplay the form with all the fields that have correct entries in one colour, and the field having the incorrect entry in a different colour. This would obviate the need to re-enter a large amount of data.

Let us see how the server can be solicited to retain information that has been typed in.

a.aspx <%@ language=C# %> <form action=a.aspx runat="server"> <asp:textbox id="aa" runat="server"/> <asp:button text="Click a.aspx" runat="server" /> </form>

The only modification made by us in the source code has been, the addition of the attribute runat to the form tag in the file a.aspx. Also, the action attribute is initialized to the same file. After the addition of this attribute, the View-Source now displays a file that is vastly at variance from the earlier one.

View-Source <form name="ctrl0" method="post" action="a.aspx" id="ctrl0"> <input type="hidden" name="__VIEWSTATE" value="dDwxNDgwNTg2MzM2Ozs+" />

<input name="aa" type="text" id="aa" /> <input type="submit" name="ctrl1" value="Click a.aspx" /> </form>

A field called __VIEWSTATE has been created, which is of the type hidden. A hidden field does not show up in the browser window, but its value is sent across to the server. We shall explain this concept with a simple HTML example.

a.html <form action=a1.html> <input type=hidden value=hell name=aa> <input type=submit value=click> </form>

We have a hidden field aa whose value is 'hell'. While displaying this file, only the submit button labeled 'click' is displayed. The hidden field remains invisible in the browser window. However, when the submit button is clicked, the URL that is generated, shows this field as well as its value, as: http://localhost/a1.html?aa=hell

In a.aspx, the value of the hidden field is a long and cryptic number. The form is assigned a name and an id, both initialized to ctrl0. The method attribute is given a value of post. We shall explain this concept later. By default, the method attribute has a value of 'get'. In the textbox, we enter 'vijay13' and then click on the button. The page is refreshed and the URL bar shows http://localhost/a.aspx As the method is 'post', the parameters are not displayed in the URL, as was done earlier. 'Post' does not send the parameter values along with the URL, whereas, the 'get' method does so. In the case of 'post', they are transferred as a separate packet with data. As far as the ASP.Net page is concerned, the task of fetching the parameter values remains the same. With the new contents in the HTML file, the data that is entered most recently, is recovered. Thus, the textbox shows 'vijay13'.

Let us now look 'behind the scenes' to figure out why this happens.

View-Source <form name="ctrl0" method="post" action="a.aspx" id="ctrl0"> <input type="hidden" name="__VIEWSTATE" value="dDwxNDgwNTg2MzM2Ozs+" />

<input name="aa" type="text" value="vijay13" id="aa" /> <input type="submit" name="ctrl1" value="Click a.aspx" /> </form>

This time, the textbox's value field displays the word 'vijay13'. This could have been possible only if the Web Server remembered what was transferred. Hence, in the return round trip from the server to the browser, it adds the value attribute to the textbox and assigns the new value to it. Thus, runat asks the server to retain the values assigned to the attributes.

If you change 'vijay13' to 'vijay14' in the textbox and click on the button again, 'vijay14' will be displayed in the textbox. Thus, new values are restored.

We now change the name of the textbox from aa to aaa in a.aspx. On executing the whole program again, the textbox of a.aspx is displayed as empty. This occurs because the names are different, and thus, they refer to different textboxes.

Restore the name of aa again and load a.aspx in the address bar. As the textbox names now match, the earlier value of vijay14 is displayed again. The name and the id value of the form too can be changed without disturbing the above process.

To improve your grasp of the above proceedings, open another copy of the browser and load a.aspx. You will then notice that the two copies maintain distinct values. This implies that the web server is informed about the newly opened browser too.

This book will delve deeper into these concepts. So, continue reading if you wish to satiate your curiosity any further.

a.aspx <%@ language=C# %> <form action=a1.aspx> <select name=item> <option> Wood </option> <option> Copper </option> <option> Iron </option> </select> <input type= submit value=Click > </form>

View Source <form action=a1.aspx> <select name=item> <option> Wood </option> <option> Copper </option> <option> Iron </option> </select>

<input type= submit value=Click > </form>

To create a listbox, the HTML tag 'Select' is used. 'Select' requires 'option' as a sub-tag, where the values within the listbox are placed. We have the prerogative to pick out any of the items from the listbox, but when we click on the submit button, the name of the listbox is intialized to the value that has been selected. Thus, item will be initialized to the value Copper, when Copper is selected. This feature is a slight deviation for HTML novices or for those with a frail memory, where HTML is concerned. There is no change in the aspx file other than the aspx directive with language as C#. Select the item as Copper and the url changes to

http://localhost/a1.aspx?item=Copper

a.aspx <%@ language=C# %> <form action="a.aspx" runat="server"> <asp:dropdownlist id="aa" runat=server> <asp:listitem>wood</asp:listitem> <asp:listitem>copper</asp:listitem> <asp:listitem>steel</asp:listitem> </asp:dropdownlist> <asp:button text="Click a.aspx" runat="server" /> </form>

For the sake of completeness, we have shown how you can display a combo box using the tags asp:dropdownlist and asp:listitem, instead of the 'select the option' tag. It is more advisable to use these tags instead of the above displayed standard HTML tags.

We will gradually proceed to build a real life application in ASP+. Has it ever ceased to astonish you, as to how a different advertisement appears each time you visit the same website. The application given below clarifies this mystery.

a.aspx <%@ language=C# %> <form action="a.aspx" runat="server"> <asp:adrotator AdvertisementFile="a.xml" runat="server"/> <asp:button text="Click" runat="server"/> </form>

a.xml <Advertisements> <Ad> <ImageUrl>/quickstart/aspplus/images/banner2.gif</ImageUrl> </Ad> <Ad> <ImageUrl>/quickstart/aspplus/images/banner3.gif</ImageUrl> </Ad> </Advertisements >

Each time we click on the Click button, we come across a different advertisement of banner. How does this happen? To unravel this mystery, we first look at the HTML source that is generated by the server for the file a.aspx.

View-Source <form name="ctrl0" method="post" action="a.aspx" id="ctrl0"> <input type="hidden" name="__VIEWSTATE" value="dDw3MTQ1NDk0MTs7Pg==" />

<a target="_top"><img src="/quickstart/aspplus/images/banner3.gif" border="0" /></a> <input type="submit" name="ctrl2" value="Click" /> </form>

The anchor ( a ) and the image ( img ) tags are the newly inserted tags corresponding to asp:adrotator. The attribute AdvertisementFile="a.xml" directs the web server to a file, a.xml, which contains a series of img files that the web server is required to serve. a.xml must be in the same directory as a.aspx i.e c:\inetpub\wwwroot. The runat attribute retains the information for the web server.

An XML file is simply an HTML file. We start with a root or a starting tag called Advertisements. Within this, is located a tag called Ad, which contains another tag called ImageUrl. ImageUrl contains the images that are to be served in rotation. These images are present in the images subdirectory i.e. quickstart/aspplus/images, which is created while installing ASP+ and its samples.

a.aspx <%@ language=C# %> <form action="a.aspx" method="post" runat="server"> <script language="C#" runat=server> void abc(Object a, EventArgs e) {

Response.Write("hell"); } </script> <asp:textbox id="aaa" runat="server"/> <asp:button type=submit text="Click" OnClick="abc" runat="server"/> </form>

We have created a function abc that accepts two parameters; the first one is 'a' which looks like a class Object, and the second one is 'e' which looks like EventArgs. The asp:button tag is used with an additional attribute called OnClick, which is initialized to the abc function. This function is called, when the button is clicked. The two controls viz. textbox and button, are visible when a.aspx is displayed in the browser window. View-Source displays the following:

View-Source <form name="ctrl0" method="post" action="a.aspx" id="ctrl0"> <input type="hidden" name="__VIEWSTATE" value="YTB6MTk4ODc0NjcyX19feA==f2f03fae" /> <input name="aaa" type="text" id="aaa" /> <input type="submit" name="ctrl4" value="Click" type="submit" /> </form>

The OnClick attribute is not visible in the contents displayed by View-Source. Further, the function abc simply vanishes without a trace ! Where did they actually vanish? If you observe carefully, in the input tag for the button, the attribute type is displayed twice.

We now write vijay in the textbox and click on the button. The browser window displays 'hell', followed by the textbox that contains 'vijay', and then the View-Source displays the following:

View-Source hell<form name="ctrl0" method="post" action="a.aspx" id="ctrl0"> <input type="hidden" name="__VIEWSTATE" value="YTB6MTk4ODc0NjcyX19feA==f2f03fae" /> <input name="aaa" type="text" value="vijay" id="aaa" /> <input type="submit" name="ctrl4" value="Click" type="submit" /> </form>

This proves the fact that when the button was clicked, the web server was asked to execute a.aspx. The button 'Click' has a function abc associated with it that displays 'hell'. So, IIS executes this function and then generates an HTML file with the output of the function abc. Furthermore, it remembers that the data entered in the textbox was 'vijay'. Hence, the value with the textbox is initialized to this value. a.aspx <%@ language=C# %> <form action="a.aspx" method="post" runat="server"> <script language="C#" runat=server> int i = 0; void abc(Object a, EventArgs e) { i++; Response.Write("hell " + i.ToString()); }

</script> <asp:textbox id="aaa" runat="server"/> <asp:button type=submit text="Click" OnClick="abc" runat="server"/> </form>

The browser window shows the same controls as before. Before the button is clicked, the variable i is initialized to 0, and thereafter, the web server executes the function abc. Within the function abc, i is increased by one and then its value is displayed.

An int class has a function called ToString that converts a number into a String. The + sign concatenates two strings. Thus, in the first instance, we see 'hell 1', and the View-Source shows the following:

View-Source hell 1<form name="ctrl0" method="post" action="a.aspx" id="ctrl0"> <input type="hidden" name="__VIEWSTATE" value="YTB6MTk4ODc0NjcyX19feA==f2f03fae" /> <input name="aaa" type="text" value="vijay" id="aaa" /> <input type="submit" name="ctrl4" value="Click" type="submit" /> </form>

Each time we click on the button, the entire aspx file gets executed from the very beginning. Therefore, the value of the variable i gets initialized to zero everytime. This results in the text 'hell 1' being displayed each time. The variable i does not retain its previous values, because everything starts afresh whenever the button is clicked. a.aspx <%@ language=C# %>

<form action="a.aspx" method="post" runat="server"> <script language="C#" runat=server> void abc(Object a, EventArgs e) { cc.Text = aa.Text + " " + bb.SelectedItem; } </script> <asp:textbox id="aa" runat="server"/> <asp:dropdownlist id="bb" runat=server> <asp:listitem>Wood</asp:listitem> <asp:listitem>Copper</asp:listitem> <asp:listitem>iron</asp:listitem> </asp:dropdownlist> <asp:button type=submit text="Click" OnClick="abc" runat="server"/> <asp:label id="cc" runat="server"/> </form>

In the above example, we have introduced one more tag called asp:label, having the id of cc. This label, for the moment, does not get displayed on the screen. Its behaviour is similar to that of hidden types. We then enter the text 'vijay' in the textbox named aa, and select the option named Wood from the listbox called bb.

The Web Server first executes the function abc. Every textbox has a property called Text,which returns the text entered by the user. Thus, aa.Text will return 'vijay'. Setting aa.Text to 'Mukhi' will change 'vijay' to 'Mukhi'. Also, a listbox has a property called SelectedItem that returns the item selected. Thus, bb.SelectedItem returns the value 'Wood'.

It is our intent to display these details using the label control. Similar to the textbox, every label has a member or a property called Text. We initialize this property to the contents of the textbox and listbox. Hence, 'vijay Wood' is displayed in the browser window.

a.aspx <%@ language=C# %> <script language="C#" runat="server"> void Page_Load(Object Src, EventArgs E) { aa.Text = "Time is : " + DateTime.Now; } </script> <asp:label id="aa" font-size="24" font-bold="true" runat=server/>

Output Time is : 2001-03-22T19:08:46

View Source <span id="aa" style="font-size:24px;font-weight:bold;">Time is : 2001-03-22T19:08:46</span>

In this program we have a tag called asp:label with an id of aa. No text is initially assigned to the label. Therefore, the text attribute is not specified. Instead, two new attributes are given, viz. the font-size and font-bold with the values of 24 and True, respectively.

As before, we did not expect our HTML file to display any labels, since no text value is assigned. But to our utter disbelief, we can see the current date and time displayed in bold, on our screen.

We shall now reveal a secret to you: The Web Server is programmed to call the function Page_Load in the beginning, whenever it is present in an aspx file. In this function, we change the Text property of the label aa to "Time is : " and to the value returned by DateTime.Now.

DateTime has a variable called 'Now' that returns the current date and time on our server. Hence, the contents in View-Source display the date and time in the specified font format, using the HTML span tag.

The essential point to be remembered is that the server is oblivious to C# code. Whenever the function Page_Load is present, it is executed prior to generating the page.

a.aspx <%@ language=C# %> <script language="C#" runat="server"> void Page_Load(Object Src, EventArgs E) { aa.Text = "vijay"; bb.NavigateUrl = "a1.aspx?cc=" + aa.Text; } </script> <asp:hyperlink id="bb" font-size=24 runat=server> Hi <asp:label id="aa" runat=server/> Click here </asp:hyperlink>

We now have an asp hyperlink tag that is equivalent of the <a href=> </a> tag in HTML. It is given an id of bb. The file also contains a label called aa.

In the Page_Load function, the label is changed to vijay and the NavigateUrl property of the hyperlink bb is changed to a1.aspx?cc=vijay. Thus, the first screen merely displays 'Hi vijay Click here'. When you click on the anchor, a1.aspx is called with cc initialized to vijay.

a1.aspx <%@ language=C# %> <script language="C#" runat="server"> void Page_Load(Object s,EventArgs e) { aa.Text = Request.Params["cc"]; } </script> Hi <asp:label id="aa" runat=server/>!

In the file a1.aspx, Page_Load is the first function to be called by the server. The function Request.Params is similar to Request.QueryString. It accepts the name of the parameter cc which is enclosed within square brackets, and returns its value, i.e. vijay. Consequently, the browser window displays the text 'Hi vijay'!

You are granted with great flexibility in performing a lot of activities using the Page_Load function.

a.aspx

<%@ language=C# %> <script language="C#" runat="server"> void abc(Object Src, EventArgs E) { if (aa.Text != "") { Response.Redirect("a1.aspx?bb=" + aa.Text); } else { cc.Text = "Enter your name in the textbox!"; }

} </script> <form runat=server> Name: <asp:textbox id="aa" runat=server/> <asp:button text="Enter" Onclick="abc" runat=server/> <p> <asp:label id="cc" forecolor="red" font-bold="true" runat=server/> </form>

a1.aspx

<%@ language=C# %> <script language="C#" runat="server"> void Page_Load(Object s,EventArgs e) { aa.Text = Request.Params["bb"]; } </script> Hi <asp:label id="aa" runat=server/>!

The above example performs many more error checks than its predecessor. Here, there is a textbox called aa and a simple button that has a label named 'Enter'. The Onclick attribute of this button points to the function abc. The label is named cc and displayed in red colour. It has no text associated with it.

Without entering any data in the textbox, you can click on the button to call the function. This function scrutinises the contents of the textbox attribute for a value. If the textbox contains some text, in other words, if it is not blank, the function Response.Redirect creates a new URL called a1.aspx, followed with the ? and abc=vijay and then travels to it. We are assuming that the text entered is vijay. If the textbox contents are blank, the text attribute of the label is displayed with a warning message in red.

The html code is totally unaware about the 'behind the scene' tasks carried out by the server. Hence, the View-Source displays a simple html file. Thus, error checks can be automated using the programming language. The above program also demonstrates that parameters can be passed to an aspx file.

a.aspx <%@ language=C# %> <script language="C#" runat="server">

void abc(Object Src, EventArgs E) { String a = System.Web.HttpUtility.UrlEncode(aa.Text, System.Text.Encoding.UTF8); cc.Text = a; } </script> <form runat=server> Name: <asp:textbox id="aa" runat=server/> <asp:button text="Enter" Onclick="abc" runat=server/> <p> <asp:label id="cc" forecolor="red" font-bold="true" runat=server/> </form>

Output vijay+mukhi+%2b

In the textbox, we have keyed in the text 'vijay mukhi +'. Thereafter, if we click on the button, the abc function calls another function UrlEncode, which accepts two parameters. The first parameter is the text written in the textbox aa.Text and the second parameter is System.Text.Encoding.UTF8, which is the encoding style used on the Internet.

A URL is used to signify a computer address. It cannot contain characters such as a space, the plus sign etc. Therefore, all these special characters are converted into a form that is acceptable in a URL. To achieve this, C# has functions like UrlEncode, that converts a space into a + sign, and all other reserved characters into their ASCII equivalents in hex . In addition to this, it prefixes them with the % sign. This conversion is termed as URL encoding. Its reverse is termed as URL decoding. If the data received from the Internet is encoded, then it has to be decoded before it can be used in our programs.

Validation Controls

a.aspx <%@ language=C# %> <form action="a.aspx" runat="server"> <asp:RequiredFieldValidator ControlToValidate="aaa" errormessage="Please Write something" runat=server /> <asp:textbox id="aaa" runat="server"/> <asp:button type=submit text="Click" runat="server"/> </form>

In the browser, a textbox and a button are displayed. When we click on the button, the following error message is displayed 'Please Write something'. Here, we have created a simple error check. We offered the user a textbox where we expected him to enter some data. If, for any reason, he refuses to do so, we can prevent him from proceeding further.

To validate data, we use a new ASP.Net tag called asp:RequiredFieldValidator with the attribute ControlToValidate initialized to the control id. In our case, the control to be checked is the textbox, hence, aaa is given. The attribute errormessage of this new tag is provided with text of the error message that we desire to display on the occurrence of an error.

In order to implement error checks, this is all that is required to be done by us. On implementing this error check, we receive an error message if the textbox is left blank. If you select the ViewSource menuoption, you will be surprised to see a large number of lines of code written in a language called Javascript. This code is executed on your web browser. View-Source
<form name="ctrl0" method="post" action="a.aspx" language="javascript" onsubmit="ValidatorOnSubmit();" id="ctrl0"> <input type="hidden" name="__VIEWSTATE" value="dDwtNTEwNzM4MzUzOzs+" />

<script language="javascript" src="/aspnet_client/system_web/1_0_2914_16/WebUIValidation.js"></script>

<span id="ctrl1" controltovalidate="aaa" errormessage="Please Write something" evaluationfunction="RequiredFieldValidatorEvaluateIsValid" initialvalue="" style="color:Red;visibility:hidden;">Please Write something</span>

<input name="aaa" type="text" value="kk" id="aaa" /> <input type="submit" name="ctrl2" value="Click" onclick="if (typeof(Page_ClientValidate) == 'function') Page_ClientValidate(); " language="javascript" type="submit" /> <script language="javascript"> <!--var Page_Validators = new Array(document.all["ctrl1"]);// --> </script> <script language="javascript"> <!-var Page_ValidationActive = false; if (typeof(clientInformation) != "undefined" && clientInformation.appName.indexOf("Explorer") != -1) { if (typeof(Page_ValidationVer) == "undefined") alert("Unable to find script library '/aspnet_client/system_web/1_0_2914_16/WebUIValidation.js'. Try placing this file manually, or reinstall by running 'aspnet_regiis -c'."); else if (Page_ValidationVer != "121") alert("This page uses an incorrect version of WebUIValidation.js. The page expects version 121. The script library is " + Page_ValidationVer + "."); else ValidatorOnLoad(); } function ValidatorOnSubmit() { if (Page_ValidationActive) { ValidatorCommonOnSubmit(); } }

// --> </script> </form>

A massive program has been generated by the server. If you go to the script sub-directory mentioned in the src attribute, aspnet_client/system_web/1_0_2914_16, you will find a file called WebUIValidation.js that contains almost 455 lines of code.

The salient concept to be grasped here is that, the server is not called upon for conducting error checks, as this process takes too long. Instead, code that can be executed by the client is generated. Further, this code is generated in Javascript (invented by Netscape), which is a language that is compatible with all browsers. You can use the Microsoft version of Javascript i.e. Jscript, in ASP.Net, in lieu of the C# programming language.

The crucial concept that has been implemented is that, it is more sensible for the browser to carry out validations and then send the corrected data to the server for processing. If the entire responsibility of data validation is assigned to the server, it would have to send the data to and fro very often, resulting in data congestion. The browser speeds up the process of data validation and it ensures greater interaction with the user.

Whenever we click on the button, some Javascript code gets called, which executes the error checking.

a.aspx <%@ language=C# %> <form action="a.aspx" runat="server"> <asp:dropdownlist id="aa" runat=server> <asp:listitem><!--Choose--></asp:listitem> <asp:listitem >Wood</asp:listitem> <asp:listitem >Copper</asp:listitem>

<asp:listitem >Steel</asp:listitem> </asp:dropdownlist> <asp:RequiredFieldValidator ControlToValidate="aa" InitialValue="<!--Choose-->" errormessage="You must select something" runat=server/> <asp:button type=submit text="Click" runat="server"/> </form>

To perform similar error checks for a listbox or any other control, we enforce the use of the attribute InitialValue to ensure that the user selects some value from the listbox before clicking on the button. If none of the values is selected, an error message is displayed. You should make sure that the InitialValue contains some informative message. This is to ensure that if the user does not select any of the options, the error message that is displayed is meaningful.

The Web Forms framework has a repertoire of validation server controls that are used to validate input forms for errors. They also display relevant error messages which inform the user about any inaccuracies.

There is no difference in the procedures for adding a listbox control or a validation control to a form. So far, we have delved upon only one type of Validation. However, a large number of validations are possible. We shall deliberate over them in the pages to come. There is no restriction on adding multiple Validation controls to an HTML control. However, it is pertinent to note that not all HTML controls can be validated.

a.aspx <html> <head> <script language="C#" runat=server> void abc(Object S, EventArgs e) {

if (Page.IsValid == true) { aa.Text = "Page is Valid!"; } else { aa.Text = "Some of the required fields are empty"; } } </script> </head> <body> <form runat="server"> <asp:Label ID="aa" text="fill it up" runat=server /> <ASP:RadioButtonList id=bb runat=server> <asp:ListItem>a1</asp:ListItem> <asp:ListItem>a2</asp:ListItem> </ASP:RadioButtonList> <asp:RequiredFieldValidator id="r1" ControlToValidate="bb" InitialValue="" runat=server> * </asp:RequiredFieldValidator> <ASP:TextBox id=cc runat=server /> <asp:RequiredFieldValidator id="r2" ControlToValidate="cc" Width="100%" runat=server>

hey </asp:RequiredFieldValidator> <ASP:Button id=B1 text="Validate" OnClick="abc" runat=server /> </form> </body> </html>

Now we have presented a more complicated validation example. The two widgets that have been used in the form are:

A radio button that displays two values A textbox.

We also have to apply a validation control to each of the controls. The first validation control has an asterick sign ( * ). The second validation control has the word 'hey'.

The validation ensures the follows:

When no text is entered in the textbox, the word 'hey' is displayed in front of the textbox. When the user enters some text in the textbox, the word 'hey' disappears. When no option is chosen in the radio button, a red coloured asterix (*) is displayed in front of the radio button. When the user selects an option in the radio button, the * vanishes.

Finally, when we fill up both the controls, the page is considered valid, since all controls on the page now contain some value or the other.

Every ASP+ page has a free variable called Page.IsValid, that tells us if all the controls on the page contain valid data or meet the validation rules. If all the controls satisfy the validation rules, then and only then, the free variable Page.IsValid is assigned a value of True. Otherwise, by default, it is assigned the value of False.

Thus, after all the controls contain valid data, when we click on the button labeled Validate, IsValid is assigned the value True. Hence, the label displays the text 'Page is Valid'.

Code can be validated either on the server or on the client. ASP+ has no knowledge of the browser that is being used. But, if your browser supports dynamic HTML, then the HTML page that is generated will contain a large amount of code to be executed on the browser.

In such a situation, whenever we click on a submit button, before the data can be sent to the server, the browser code in your HTML file gets executed first. In case of any error, the form is not sent to the server. Therefore, the data is sent to the server only if it is free from all errors. This concept is known as Client Side Programming. Note that it is the Web Server that generates the client side verification code.

A URL is created when we click on the Submit button. Alternatively, the same URL can be keyed into the address bar by the user. There is no way that a web server can differentiate between these two actions. In both these situations, the Web Server will perform the same error checks at its end, regardless of the fact that the client has already carried out validation of all the fields.

a.aspx <%@ language=C# ClientTarget=DownLevel %> <form action="a.aspx" runat="server" method=get> <asp:RequiredFieldValidator ControlToValidate="aaa" errormessage="Please Write something" runat=server /> <asp:textbox id="aaa" runat="server"/> <asp:button type=submit text="Click" runat="server"/>

</form>

View Source <form name="ctrl0" method="get" action="a.aspx" id="ctrl0"> <input type="hidden" name="__VIEWSTATE" value="dDwtMTQ5NzczMjY1MDs7Pg==" />

&nbsp; <input name="aaa" type="text" id="aaa" /> <input type="submit" name="ctrl2" value="Click" onclick="if (typeof(Page_ClientValidate) == 'function') Page_ClientValidate(); " language="javascript" type="submit" /> </form>

On changing the value of the property ClientTarget to DownLevel, the contents displayed by View-Source menuoption do not contain the Javascript code generated by the Web Server. By default, this property has a value of UpLevel, which results in a request to the browser to perform error checking on the data entered by the user.

a.aspx <%@ language=C# ClientTarget=DownLevel %> <html> <head> <script language="C#" runat=server> void abc(Object S, EventArgs e) { if (Page.IsValid == true)

{ aa.Text = "Page is Valid!"; } else { aa.Text = "Some of the required fields are empty"; } } </script> </head> <body> <form runat="server"> <asp:Label ID="aa" text="fill it up" runat=server /> <ASP:TextBox id=cc runat=server /> <asp:RequiredFieldValidator id="r2" ControlToValidate="cc" Width="100%" runat=server> hey </asp:RequiredFieldValidator> <ASP:Button id=B1 text="Validate" OnClick="abc" runat=server /> </form> </body> </html>

This program is identical to its predecessor, but with a slight modification in that, the server performs all the validation checks and not the client. This has been achieved by assigning the value of Downlevel to the property ClientTarget.

Previously, the form had the filename a.aspx. However, this file name has been omitted here. Thus, when we click on the button the first time without entering any text, the function abc is called from the server. The function fills up the label with the message 'Some of the required fields are empty'.

When we enter some text in the textbox, and click on the button, the server receives a True value for Page.IsValid and thus, it changes the value of the label to 'Page is Valid!'. This happens only when the same form is sent back to the server.

a.aspx <%@ language=C# ClientTarget=DownLevel%> <html> <head> <script language="C#" runat=server> void abc(Object Sender, EventArgs E ) { ss.DisplayMode = (ValidationSummaryDisplayMode) aa.SelectedIndex; } </script> </head> <body> <form runat="server"> Select Fruit

<ASP:RadioButtonList id=rr runat=server> <asp:ListItem>Apples</asp:ListItem> <asp:ListItem>Oranges</asp:ListItem> </ASP:RadioButtonList> <asp:RequiredFieldValidator id="r1" ControlToValidate="rr" ErrorMessage="Select one fruit " InitialValue="" runat=server> * </asp:RequiredFieldValidator> Enter the quantity : <ASP:TextBox id=tt runat=server /> <asp:RequiredFieldValidator id="R2" ControlToValidate="tt" ErrorMessage="Quantity cannot be blank" runat=server> * </asp:RequiredFieldValidator> <asp:ValidationSummary ID="ss" runat="server" HeaderText="You must enter a value in the following fields:"/> <ASP:Button id=Button1 text="Validate" runat=server /> <br> <p> Select display format for error messages <asp:DropDownList id="aa" OnSelectedIndexChanged="abc" AutoPostBack =true runat=server > <asp:ListItem>List</asp:ListItem> <asp:ListItem selected>Bulleted List</asp:ListItem> <asp:ListItem>Single Paragraph</asp:ListItem> </asp:DropDownList>

</form> </body> </html>

We have a similar program as before, i.e. it has two controls, viz. a textbox and a radio button, with a validator for each of them. We have also added a new tag called <asp:ValidationSummary that has the name ss, and some text in the attribute HeaderText.

Further, a listbox having the name aa is added which contains three items. Whenever the user changes the selection from the listbox, the function abc gets called.

The function changes the value of the attribute DisplayMode from the ValidationSummary tag, to one of the values stated in the listbox. The listbox conatins a list of different formating style. The attribute SelectedIndex returns the option that is selected from the listbox.

Thus, each time we change the item selected from the listbox, we see the error summary displayed in different formats. As the client target property is assigned the value of DownLevel, all error checks take place only at the server. The AutoPostBack attribute is True. This gets converted into a select statement in HTML, with the Onchange attribute pointing to a function called __doPostBack.

<select name="aa" id="aa" onchange="javascript:__doPostBack('aa','')">

This function reads as follows:

function __doPostBack(eventTarget, eventArgument)

{ var theform = document.ctrl2 theform.__EVENTTARGET.value = eventTarget theform.__EVENTARGUMENT.value = eventArgument theform.submit() }

The function merely calls Submit with all the form parameters. This reaches the server, which thereafter, generates a fresh p

-3-

Writing our own Web Controls


So far, we have been exclusively using controls provided by Microsoft. Since they are web based, they are also termed as Web Controls. In this chapter, we will show you how to create your own web control. Any Web Form can be modified to become a Web Control. A Web Form that is used as a server control is termed as a user control.

a.aspx <%@ Language="C#" %> <%@ Register TagPrefix="vijay" TagName="sonal" Src="a1.ascx" %> <html> hi <br> <vijay:sonal runat="server"/> </body> </html>

a1.ascx Great ASP+ book

Output hi Great ASP+ book

Nothing can be simpler than creating a user control. We first need a tag or a tag prefix to identify the control. In the previous chapter, all ASP+ controls started with the tag prefix asp:. This tag prefix was then followed by the word button or textbox. These type of words are given the nomenclature of tag names.

In the case of user controls, we initially need to register our control with ASP+. To achieve this, a directive called Register is used. It is followed by the attributes TagPrefix, TagName and Src. Register is known as a directive because it is preceded by the @ sign. TagPrefix and TagName are initialized to vijay and sonal, respectively. So, the tag usage will now be vijay:sonal. Finally, it is essential to provide the file name of the file that contains the source code of our control. To accomplish this, Src is initialized to a1.ascx.

By convention, we shall always name our source code file as a1.ascx. The big boys at Microsoft have requested the developers to standardize the file extension as ascx, but this is not mandatory. The file a1.ascx has only a single line of text i.e. Great ASP+ book. Hence, the output replaces the control tag vijay:sonal with this line. Life could not get any simpler !

a.aspx <%@ Register TagPrefix="vijay" TagName="mukhi" Src="a1.ascx" %> <html> hi <br> <form runat="server"> <vijay:mukhi id="aaa" runat="server"/> <br>

</form> </body> </html>

a1.ascx <script language="C#" runat="server"> public String Color = "blue"; </script> The color property is <%= Color %>

Output hi The color property is blue

This program associates a property called Color with the control. A property can be introduced by simply adding a public variable in the ascx file, and then displaying it using <%=. Here, the public variable Color is initialized to blue. Hence, we catch sight of the colour blue in the browser. This simple act of creating a public variable, which gets converted into a property, can also be used with tags created by us. The next program illustrates this point.

a.aspx <%@ Register TagPrefix="vijay" TagName="mukhi" Src="a1.ascx" %> <html> hi <br> <form runat="server">

<vijay:mukhi id="aaa" Color="green" runat="server"/> <br> </form> </body> </html>

Output hi The color property is green

The original value of the property can be overwritten in the tag. Hence, we see the value as green and not blue.

a.aspx <%@ Register TagPrefix="vijay" TagName="mukhi" Src="a1.ascx" %> <script language="C#" runat="server"> void abc(Object s, EventArgs E) { aaa.Color = "red"; } </script> <html> hi <br> <form runat="server">

<vijay:mukhi id="aaa" Color="green" runat="server"/> <br> <asp:button text="Change " OnClick="abc" runat=server/> </form> </body> </html>

Output hi The color property is red

Bear in mind that there is no distinction between the properties created by us and the built-in properties of the tag. Thus, in the function abc, we can modify the value of the property Color to red. The new values override the default ones.

a.aspx <%@ Register TagPrefix="vijay" TagName="mukhi" Src="a1.ascx" %> <script language="C#" runat="server"> void abc(Object s, EventArgs E) { aaa.Color = "red"; } </script> <html>

hi <br> <form runat="server"> <vijay:mukhi id="aaa" Color="green" runat="server"/> <br> <asp:button text="Change " OnClick="abc" runat=server/> </form> </body> </html>

a1.ascx <script language="C#" runat="server"> String aa = "blue"; public String Color { get { return aa; } set { aa = value; } }

</script>

The color property is <%= Color %>

We start with the output window displaying the following output:

Output hi The color property is green

And after we click on the button, the output that is now displayed, is as follows:

Output hi The color property is red

We have carried out numerous modifications to the file a1.ascx, but we have left the file a.aspx untouched.

The C# programming language understands properties and uses keywords/accessors like 'get' and 'set' to operate upon them. Since the language used in the ASP+ file is given as C#, this feature can easily be exploited to act upon the tag properties.

In the ascx file, the local variable aa is initialized to the value blue. On the next line, the statement commences with the word 'public' associated with the Color property and with the return value as String.

A property can either be used on the left or the right side of an = sign. If it is on the left, then it is being assigned a value. So, when we write Color="blue" in a tag, we are setting the value of the property Color to blue, which is a string. ASP+ uses the set accessor to store the value into the property. The variable aa contains the value blue. Hence, the property Color is initialized to blue.

When a property is placed on the right side of the 'equal to' sign, it will return the value contained in it. In the aspx file, <%= Color> is used to obtain the current value of the property Color. Accordingly, ASP+ calls the 'get' accessor. The only statement within 'get' is 'return aa' which will return the value stored in aa to the aspx file.

Apparently, both the techniques that used to create a property, appear identical; however,there is a subtle difference. In the first case, we are merely changing the value of a variable, whereas, in the second instance, we are calling functions.

A function can contain and execute innumerable lines of code. These statements can perform error checks and ensure that the user does not infringe on the permissible values of the property. A similar paradigm is noticeable in the highly successful Microsoft product, Visual Basic, which extensively supports the concept of properties.

a.aspx <%@ Register TagPrefix="vijay" TagName="mukhi" Src="a1.ascx" %> <html> <script language="C#" runat="server"> void Page_Load(Object s, EventArgs E) { if (Page.IsPostBack) { Response.Write("true a.aspx");

aa.Text = bb.Password; } else Response.Write("false a.aspx"); } </script> <form runat="server"> <vijay:mukhi id="bb" Password="hell" runat="server"/> </form> <asp:Label id="aa" runat="server"/> </body> </html>

a1.ascx <script language="C#" runat="server"> public String Password { get { return Pass.Text; } set {

Pass.Text = value; } } </script> <ASP:TextBox id="Pass" TextMode="Password" runat="server"/> <ASP:Button Text="Submit" runat="server"/>

Output false a.aspx

The file a.aspx has a custom tag called vijay:mukhi. It has an id of bb and a property called password, which has been initialized to 'hell'.

Since the label aa has no value, Page_Load does not display any text when the page is loaded. Since the file a.aspx has been requested for, from the server by writing the url as http://localhost/a.aspx, (submit button is not used), the property IsPostBack is false. Hence, the output is depicted as false.

The source code file a1.ascx has a property called password, which is declared public and which returns a String. In order to initialize and retrieve values of the property, a textbox with an id of Pass is used instead of a variable. Since the TextMode is Password, the characters that are keyed in are not visible.

Further, a button labeled as 'submit' has been added to the ascx file to take us back to the server. Therefore, an existing control can be used to hold a value.

A user control can accommodate multiple controls. The View-Source too does not spring up any surprises.

View-Source false a.aspx <html> <form name="ctrl1" method="post" action="a.aspx" id="ctrl1"> <input type="hidden" name="__VIEWSTATE" value="YTB6MTI3MTQyMTk4M19fX3g=d6c4c93a" />

<input name="bb:Pass" type="password" value="hell" id="bb_Pass" /> <input type="submit" name="bb:ctrl1" value="Submit" /> </form> <span id="aa"></span> </body> </html>

In the ascx file, the textbox was assigned the id of Pass, and the control name in a.aspx name was bb. Hence, in the HTML file generated by the server, it is termed as bb:Pass. This is done merely to maintain the sanctity of names, as the same name could have been assigned to the textbox in both the files. When we type hell in the textbox and click on the button, the output that is displayed is as follows:

Output True a.aspx Hell

When we click on the submit button, the file a.aspx is called. Since the button is responsible for calling the a.aspx file, the property IsPostBack is assigned a value of true. Hence, True is displayed. The label in Page_Load is initialized to the password 'hell' because our textbox contains the word 'hell'.

Had we modified this value, we would not have been in such a muddle. Instead, the label would have displayed these values too. All this happens only on the server. An ascx file can definitely contain code that is normally written in an aspx file.

a.aspx <%@ Register TagPrefix="vijay" TagName="mukhi" Src="a1.ascx" %> <html> <script language="C#" runat="server"> void Page_Load(Object Src, EventArgs e) { if (Page.IsPostBack) Response.Write("true1"); else Response.Write("false1"); } </script> <form runat="server"> <vijay:mukhi runat="server"/> </form> </body>

</html>

a1.ascx <script language="C#" runat="server"> void Page_Load(Object Src, EventArgs e) { if (Page.IsPostBack) Response.Write("true"); else Response.Write("false"); } void abc(Object sender, EventArgs e) { Response.Write(aa.SelectedItem.Value); } </script> <ASP:DropDownList AutoPostBack="true" id="aa" OnSelectedIndexChanged="abc" runat="server"> <ASP:ListItem value="business">Business</ASP:ListItem> <ASP:ListItem value="trad_cook">Traditional Cooking</ASP:ListItem> <ASP:ListItem value="mod_cook">Modern Cooking</ASP:ListItem> </ASP:DropDownList>

Output

false1falsetrad_cook

Along with properties, a user control can also have events associated with it. In fact, it can contain every feature that is usually built into a tag. We can implement our own callbacks also. The above example amply validates this feature.

We have integrated a listbox in our control and associated a function abc with it. With every change in the item that is selected from the options in the listbox, abc shall be called.

Both files have a Page_Load function. It is relatively easy to verify which Page_Load function gets invoked first. This can simply be accomplished by placing a Write function with each of these functions, and verifying the output by determining the order in which they are being executed.

The output lucidly and comprehensively demonstrates that the Page_Load, which forms the part of the main file a.aspx, is summoned first, followed by the user controls. Moreover, as we keep changing the current selection, the abc function gets called repeatedly, resulting in the display of the newly selected values.

-4-

Classes
In the earlier chapters, we had exploited the existing C# classes like String and int, which were utilized to display text and values. In this chapter, we shall focus on creating our own classes.

a.aspx <%@ Inherits="zzz" Src="b1.cs" language=C# %>

b1.cs public class zzz { }

Output Parser Error Message: 'zzz' is not a valid base class because it does not extend class 'System.Web.UI.Page'.

So far, we have learnt about the 'language' attribute with the ASP directive, which is used to specify the programming language that we shall be using in the file. The 'language' attribute was initialized to C#, thereby signifying that the rules of C# will be applicable on the code inserted with the aspx tags.

We now introduce two more attributes in addition to the 'language' directive. inherits - This attribute requires the name of a class and hence, we have provided the name zzz. src - This attribute is initialized to b1.cs, which is a program file that contains the class.

A class is a collection of variables and methods, which have been bunched together. It can therefore be considered as a container of things.

The file b1.cs is a C# file which contains the syntax 'public class zzz', followed by a pair of curly braces. The keyword 'class' results in the creation of a class called zzz. The curly braces signify the beginning and end of a class. Currently, the class that we have created does not contain any variables or methods.

Thus, we can conclude that the integer class was created through the syntax 'class int', while the string class was created through the use of the syntax 'class string'. There is no other procedure available, to create a class. The rules that apply to one class are common to the rest of the classes in C#. All the code in the C# language is contained in classes only.

In the above program, an error is generated, since ASP+ does not expect an empty class. It expects the class to contain variables and functions that it needs to invoke. However, they are not currently present in the class. Since there is a paucity of time, and moreover, due to lack of perseverance that is vital for writing all this code ourselves, we shall borrow code from an existing class that contains the relevant functions and variables.

To inherit or borrow from another class, we have to make one small amendment to the source code in the file b1.cs.

b1.cs public class zzz : System.Web.UI.Page

{ }

There exists a free class called System.Web.UI.Page that has been written by the programmers at Microsoft. This class has all the functions that ASP+ requires. To inherit or borrow from an existing class, we are required to place a colon : after the name of the class (as in zzz), and then specify the class that we want to inherit from, i.e. System.Web.UI.Page. You may have noticed that, for the Page class, the name System.Web.UI.Page is an extended one. We shall look into the reasons for the same, a little later.

Technically, we can say that the class zzz derives from class Page. This implies that all the methods and variables of class Page are now available to class zzz also. In a sense, it is akin to writing all the methods and variables in the zzz class, by ourselves. When we derive from the class Page, whatever is contained in the class, also exists in the derived class zzz, making it a rich class.

The word 'public', which precedes the class name, is an access modifier. Access modifiers are used to restrict access to a class, since it may not be desirable to allow everyone to access the class. The access modifier 'public' facilitates anyone and everyone to access the class. On making these changes to the source code, no errors are generated when we run our program.

a.aspx <%@ Inherits="zzz" Src="b1.cs" language=C# %> <form action="a.aspx" runat="server"> <asp:button type=submit text="Click" OnClick="abc" runat="server"/> </form>

b1.cs public class zzz : System.Web.UI.Page

{ public void abc(System.Object a, System.EventArgs e) { Response.Write("hi"); } }

After every click on the button, you will see the word 'hi' displayed. Let us now understand how the button works. Each time we click on a button, the function abc is called, since it is associated with the attribute OnClick. You will not notice words such as, 'script' in the aspx file because the function code is not present in a.aspx. It is located in the class zzz, which is present within the src file named b1.cs. As you must have noticed, this function resides within the class zzz.

The 'inherits' attribute makes the code, which is present in the class zzz of the file b1.cs, accessible to the aspx file. Now, the function abc does not generate any error, since it meets its match and displays 'hi' in the browser window.

This is fascinating because it demonstrates that all the code within a C# file, can now be used with ASP+. So, let us now expand our horizons about the basics of C# programming. We shall leave a.aspx untouched for a long while, and modify the file b1.cs progressively, to explain certain issues related to the C# programming language.

b1.cs public class zzz : System.Web.UI.Page { public void abc(System.Object o, System.EventArgs e) {

yyy a; } }

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

In b1.cs, we are trying to create an object 'a', that is an instance of a class yyy. But, the output displays an error, stating that C# is unaware of the class yyy.

The occurrence of this error is understandable, because C# may be well informed about, and familiar with classes such as Page and a vast number of built-in classes, but it definitely is not familiar with a user-defined class called yyy.

b1.cs public class zzz : System.Web.UI.Page { public void abc(System.Object o, System.EventArgs e) { yyy a; } } public class yyy {

You may be able to recall what we had mentioned a little while ago, that, the only way to create a class is by using the keyword 'class', followed by the class name. It cannot get simpler than this. Thus, no more errors are generated.

b1.cs public class zzz : System.Web.UI.Page { public void abc(System.Object o, System.EventArgs e) { yyy a; a.pqr(); } } public class yyy { public void pqr() { Response.Write("hell"); } }

Output

Compiler Error Message: CS0165: Use of unassigned local variable 'a'

It is not a child's play to learn a programming language, especially when it also entails deciphering cryptic errors. What does the error message 'unassigned local variable' signify? If you may recall, in chapter 2, we had created a variable i of type int, and called the ToString function off it. In a similar manner, we have now created a variable a of type yyy and have called the function pqr off it. So, why is it that an error is generated now, while it was not generated in the earlier instance?

The answer lies in the manner in which C# works internally. It divides all the classes it recognizes, into two types, i.e. value types and reference types. Classes like int, bool and string, which are called basic classes, are of value type, and all the other classes are of reference type.

A value type variable is created when we declare it. This means that i comes into existence and occupies memory space when we declare it, using the syntax 'int i'. No extra code has to be added after that, to create this.

In the case of a reference type variable, C# is first informed about the data type of the variable that we want to create, and also the variable name that we would use to reference it. This happens when we use the statement yyy a. In the next round, the keyword 'new' or a function has to be used to formerly bring the variable into existence, and then it is to be assigned a memory location, to enable it to reference members of the specified data type.

Note, that unless the second step is executed, the members in the class remain inaccessible to the object.

b1.cs public class zzz : System.Web.UI.Page { public void abc(System.Object o, System.EventArgs e)

{ yyy a; a = new yyy(); a.pqr(); } } public class yyy { public void pqr(){ } } No errors are visible any longer. It is because we have used the keyword 'new' to create an object 'a', which looks like yyy. In technical jargon, 'a' is now an instance of class yyy. Thus, the only way to create an object is, by using the keyword 'new', followed by the name of the class. Thereafter, we have to use a pair of opening and closing curly braces to encompass the actual code of the class.

The instance 'a' now stores the return value of 'new', which is a memory location. Henceforth, it can be used to refer to all the members in the class.

b1.cs public class zzz : System.Web.UI.Page { public void abc(System.Object o, System.EventArgs e) { xxx a;

a = new xxx(); a.pqr(); } } public class yyy { public void pqr() { } } public class xxx : yyy { }

In this program, we have gone a step further. The instance 'a' looks like xxx instead of yyy, and the function pqr is called from class xxx. The class xxx is derived from class yyy, following the simple rule of placing a colon first, followed by the name of the class yyy. Thus, the class xxx inherits all members of class yyy. For the moment, the class yyy has only one function called pqr, which the class xxx 'inherits'. Therefore, even though the class xxx does not contain the function pqr, the object 'a' of type xxx can call it, which is because the class xxx inherits the same from the class yyy.

We need to explore the C# programming language in greater depth to be able to fully understand what ASP.NET does with the C# code written in a .cs file. In order to steer clear of clutter, we have created a sub directory called aaa in the root where we have written the following program in a file called b1.cs.

c:\>md aaa

c:\aaa>edit b1.cs

b1.cs public class zzz { }

This program is very similar to the ones we have written earlier. The code written in a .cs file must be converted into an executable program, as the web server and the web browser are not involved here. To create an executable file, we use the command csc along with the file name. In simple terms, the command csc can be called a program which creates an executable, but in the context of the C# programming language, it is identified as the C# compiler. Thus, the command is as follows: C:\aaa>csc b1.cs

Output Microsoft (R) Visual C# Compiler Version 7.00.9254 [CLR version v1.0.2914] Copyright (C) Microsoft Corp 2000-2001. All rights reserved. error CS5001: Program 'b1.exe' does not have an entry point defined

The compiler reports an error, since there is no 'entry point' defined in the exe file. What is an entry point? Whenever a C# program begins execution, it starts execution from a base function. This base function is called an entry point function.

Here, we are getting into the details of the C# programming language, because all the code written in ASP+ is first converted into C# code and then executed.

b1.cs

public class zzz { public static void Main() { System.Console.WriteLine("hi"); } }

Output hi

Akin to the pqr function in yyy, we have introduced a function called Main within zzz in the file b1.cs. This function calls another function named System.Console.WriteLine. System.Console.WriteLine comprises of a parameter, which is a string called 'hi'. The compiler now successfully generates 'b1.exe' in the same subdirectory, without displaying any error messages. If you run this program at the command prompt, using the command 'c:\aaa>b1', the output displayed will be the word 'hi'. This proves that Main is the base function or the entry point in any C# program.

You may have noticed that the System.Console.WriteLine function in a.cs program, behaves like the Response.Write function of ASP+.

b1.cs public class zzz { public static void Main() {

System.Console.WriteLine("hi"); abc(); } public void abc() { System.Console.WriteLine("abc"); } }

Output b1.cs(6,1): error CS0120: An object reference is required for the nonstatic field, method, or property 'zzz.abc()'

Despite having reiterated this concept on numerous occasions, we shall go over it once again, that 'Only an object i.e. an instance of a class, is allowed access to the members of that class'. Thus, in the above program, we are not allowed to call the function abc, since we have still not created an instance of the class zzz.

However, there is an exception to this rule, which we shall introduce in the next program.

b1.cs public class zzz { public static void Main() {

System.Console.WriteLine("hi"); abc(); } public static void abc() { System.Console.WriteLine("abc"); } }

Output hi abc

We have added the keyword 'static' to the function abc. The keyword 'static' allows access to functions or variable, even though, an instance of the class wherein it is contained, has not been created. Hence, no error is generated. First the word 'hi' is displayed on the screen, which is followed by the word 'abc'.

We shall employ one more program to demonstrate the functionality of the keyword 'static'.

b1.cs public class zzz { public static void Main() {

System.Console.WriteLine("hi"); yyy.abc(); yyy a; a = new yyy(); a.pqr(); } } public class yyy { public static void abc() { System.Console.WriteLine("abc"); } public void pqr() { System.Console.WriteLine("pqr"); } }

Output hi abc pqr

In the class yyy, we have two functions:

The function abc, which has the static keyword. The function pqr, which is non-static.

To summon a static function, we simply use the name of the class, followed by the function name i.e. yyy.abc. Since the function abc is static, there is no need to create an object that is an instance of the class yyy. In short, a static function is associated with a class and not with an object.

In the case of the function pqr, the rules get transformed completely. Since pqr is a non-static function, we have to first create an object 'a' that is an instance of class yyy, and then use the object to call the function pqr. The syntax is as follows: a.pqr().

b1.cs public class zzz { public static void Main() { System.Console.WriteLine("hi"); yyy.abc(); yyy a; a = new yyy(); a.pqr();

} } namespace aaa { public class yyy { public static void abc() { System.Console.WriteLine("abc"); } public void pqr() { System.Console.WriteLine("pqr"); } } }

Output Microsoft (R) Visual C# Compiler Version 7.00.9254 [CLR version v1.0.2914] Copyright (C) Microsoft Corp 2000-2001. All rights reserved. b1.cs(6,1): error CS0246: The type or namespace name 'yyy' could not be found missing a using directive or an assembly reference?) b1.cs(7,1): error CS0246: The type or namespace name 'yyy' could not be found missing a using directive or an assembly reference?) (are you

(are you

b1.cs(8,1): error CS0103: The name 'a' does not exist in the class or namespace 'zzz' b1.cs(9,1): error CS0246: The type or namespace name 'a' could not be found (are you missing a using directive or an assembly reference?) On adding the words 'namespace aaa' to the program, we obtain four errors. Why does this happen? The answer reveals itself in the next program.

b1.cs public class zzz { public static void Main() { System.Console.WriteLine("hi"); aaa.yyy.abc(); aaa.yyy a; a = new aaa.yyy(); a.pqr(); } } namespace aaa { public class yyy { public static void abc() {

System.Console.WriteLine("abc"); } public void pqr() { System.Console.WriteLine("pqr"); } } }

Output hi abc pqr

The errors have disappeared. This could only be achieved by preceding the class name, i.e. yyy in Main, with the namespace aaa, and then using the dot as the delimiter. Here, aaa is called a namespace.

The concept of a namespace is very simple. Let us presume that in the .NET world, there are a million functions. A programmer will go bonkers trying to recollect the names of all these functions, along with the names of their respective classes. It surely makes more sense to tidy them up by organizing them in a systematic and logical fashion?

All printing functions can be placed in one category, while all functions that write to a file can be placed in another category. Instead of christening this type of classification as 'categories', the C#

programming language makes use of the term 'namespace'. To use a class belonging to a particular namespace, we have to use the format 'namespace.class'.

As our class yyy belongs to the aaa namespace, the full name of the class becomes aaa.yyy, and not merely yyy.

b1.cs public class zzz { public static void Main(){ System.Console.WriteLine("hi"); aaa.bbb.yyy.abc(); aaa.bbb.yyy a; a = new aaa.bbb.yyy(); a.pqr(); } } namespace aaa{ namespace bbb{ public class yyy { public static void abc() { System.Console.WriteLine("abc"); }

public void pqr() { System.Console.WriteLine("pqr"); } } } } Output hi abc pqr

We can nest namespaces to as many levels as desired. Here, we have a primary namespace called aaa containing a secondary namespace called bbb. The full name of our class yyy therefore becomes aaa.bbb.yyy, and the static function abc can be called using aaa.bbb.yyy.abc.

Whenever we read an entity in C#, we read it backwards, i.e. from right to left. We have the name of the function at the right most end. This is preceded by the name of the class, and the class name is preceded by the name of the namespace.

In the past, whenever we had derived from System.Web.UI.Page, Page was the name of the class and System.Web.UI was the name of the namespace.

Similarly, in the case of Response.Write, Response is the name of a class, while Write is a static function contained in it. In the past, we had deliberately tried to shield you from these complicated and perplexing concepts. This was for the simple reason that, we believe in divulging such intricate concepts only when the time is right for them to be appreciated.

b1.cs using aaa.bbb; public class zzz { public static void Main() { System.Console.WriteLine("hi"); yyy.abc(); yyy a; a = new yyy(); a.pqr(); } } namespace aaa { namespace bbb { public class yyy { public static void abc() { System.Console.WriteLine("abc");

} public void pqr() { System.Console.WriteLine("pqr"); } } } }

Output hi abc pqr

It shall prove to be incredibly cumbersome if we have to write aaa.bbb.yyy, every time we want to refer to the class yyy. In order to overcome this difficulty, C# offers to us a short cut in the form of a keyword called 'using'.

The keyword 'using' is followed by the namespace and terminated by a semicolon. Every time a class name appears in Main, C# replaces it with its long name, by placing the namespace in front of it. In case of any mismatch, the error message 'namespace.class not found' is generated. The keyword 'using' is similar to shorthand. It gives you the freedom to write the name of a class without actually mentioning the namespace. At the same time, the keyword 'using' can occur as many times as you want it to, in your program.

Constructors

b1.cs public class zzz { public static void Main() { yyy a; System.Console.WriteLine("hi"); a = new yyy(); } } public class yyy { public yyy() { System.Console.WriteLine("yyy"); } }

Output hi yyy

Here, we have performed something that is unusual and anomalous, that is to say, we have assigned the same name to the function as to the class, i.e. yyy. Whenever a function has the

same name as that of the class, it is treated like a special function. It is called a constructor. A constructor is automatically called, whenever an instance of the class is created.

So, the code that is to be executed when an object is created, is normally placed in the constructor. You are free to place any code in the constructor.

b1.cs public class zzz { public static void Main() { yyy a; System.Console.WriteLine("hi"); a = new yyy(); } } public class yyy { public void yyy() { System.Console.WriteLine("yyy"); } }

Output b1.cs(12,13): error CS0542: 'yyy': member names cannot be the same as their enclosing type

The syntax 'new yyy ()' creates an instance of the class yyy. This implies that, it internally allocates memory for the methods and the variables of the class yyy. The constructor is called, as the last action in this sequence.

At the time when the constructor is being executed, the object has not been created. Thus, constructors cannot return any values, because there is no object available to accept these values. The void data type signifies that there is no return value. However, in the case of constructors, there is no possibility of any value being repeated. The C# compiler assumes that yyy is a normal function because of the return type. Since a normal function cannot possess the same name as the name of the class, the above error message is generated.

An object is created only after the constructor finishes executing its code successfully.

b1.cs public class zzz { public static void Main() { yyy a; System.Console.WriteLine("hi"); a = new yyy(); a.yyy(); } }

public class yyy { public yyy() { System.Console.WriteLine("yyy"); } }

Output b1.cs(8,1): error CS0117: 'yyy' does not contain a definition for 'yyy'

A constructor is a function with only two restrictions:

The first is that it cannot return any values, as explained above.

The second is that we cannot call a constructor explicitly. It gets called automatically, only during the creation of an instance of a class.

b1.cs public class zzz {public static void Main() { yyy a; a = new yyy(); a.abc();

-5-

Database Controls
This chapter, which is based on databases, will probe into the rudiments of handling data from a database program, i.e. Microsoft's SQLServer. To ensure that the programs work as per our explanation, this database server must be installed along with the samples that are provided along with the .NET package. The details have been given in the installation section in the Introduction chapter, with the aim of assisting you in installing this product and the samples.

a.aspx <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SqlClient" %> <html> <script language="C#" runat=server> void abc(Object s, EventArgs e) { SqlConnection c = new SqlConnection("server=localhost;uid=sa;pwd=;database=pubs"); SqlDataAdapter co = new SqlDataAdapter("select * from Titles ", c); DataSet d = new DataSet(); int i = co.Fill(d, "zzz"); Response.Write(i.ToString());

l.DataSource = d.Tables["zzz"].DefaultView; l.DataBind(); } </script> <body> <form action="a.aspx" runat="server"> <asp:button type=submit text="Fetch" OnClick="abc" runat="server"/> <ASP:DataGrid id="l" runat="server"/> </form> </body> </html>

When the file a.aspx is loaded on, by providing the URL http://localhost/a.aspx, the browser displays a blank screen with only one button labeled Fetch. If you now click on the button, the same window shall get filled up with data, in a well-formatted tabular manner.

Are you astonished? Well, the best way to comprehend the output is, by analyzing the source file. In order to do so, we clicked on View-Source and found that the program that we had run on the server, and the HTML file generated, are as dissimilar as fish and fowl.

The asp:button of type 'submit', generates a submit button which calls the function abc on the server, whenever we click on it. This function first creates an object c, which is an instance of the class SqlConnection. All database handling classes either belong to the System.Data namespace or to the System.Data.SqlClient namespace.

The directive <%@ Import Namespace= is the ASP+ equivalent of the C# keyword 'using'. Since we believe in the adage that 'brevity is the soul of wit', wemake use of this directive and initialize

it to the System.Data.SqlClient and System.Data namespaces. We can include as many Import directives in the file as we want.

To create an object of type SqlConnection, the constructor with one parameter is called. This parameter is a string where we initialize some words as follows:

server to localhost uid to sa pwd to nothing database to pubs.

The class uses these values internally. The server provides relevant details about the machine on which the SQLServer database is running to SqlConnection. The relevance of these values is explained below:

Here, we have used localhost, which refers to the local machine and not to a machine on the network.

A database cannot be accessed unless we identify ourselves. In order to do so, we have to provide it with a user id and a password. So, the word uid is used, which refers to the user id, and the word pwd is used to refer to the password. SQLServer has only one pre-built user in the system called sa, which does not require a password. Hence, in this case, uid is initialized to sa and pwd is not assigned any value.

Finally, in general terms, a database is made up of tables where all data is stored. In our program, we will be constantly working with only one database called pubs. c now refers to this connection made to the pubs database, on the local disk. Observe carefully that semi-colons separate the name-value pairs in the string.

The next task in the sequence is to fetch data from the database. To accomplish this, we need to be well informed and conversant with a language that can handle a database, and also fetch the desired data. This language is called SQL or Structured Query Language. SQL is a universal language that works on all database servers and is not a trademark of any database vendor. Thus, Microsoft, Oracle or any other database vendor, do not possess the ownership rights of SQL.

In the SQL language, a Select statement fetches data from a database. As mentioned earlier, data is stored in a table within rows and columns. A row of the table is called a record and the columns are identified as fields. Further, every table has a name, and the fields in it signify the type of data that is stored within them.

The pubs database contains a table called titles. Writing an SQL command as 'Select * from titles', will fetch us all the data from the titles table. This is because the * signifies all the fields and records of a table.

As we want to display all the records from this table in the browser window, we have to use this SQL select statement in ASP+. Prior to that, we need to create one more class that understands SQL commands. This class is called SqlDataAdapter, which belongs to one of the namespaces imported in the file.

We call the constructor of SqlDataAdapter class with two parameters; the SQL statement within double quotes i.e. "select * from Titles"; and the connection object i.e. 'c'. This links up the SQL command with the database connection.

So far, we have created two objects, the first of which contains the connection details and second holds the SQL command. As we need to accommodate the data that we retrieve from the table somewhere, we need one more object that is of type DataSet. This object deals with data that comprises of multiple rows and columns.

Now, we shall get down to real work. We need to fill up the DataSet object with data. To do so, the SqlDataAdapter class provides us with a function called Fill, which accepts two parameters. The first parameter is a DataSet object 'd', and the second one is any string, zzz, which identifies

the table. This function returns an int, which informs us about the number of rows added to the DataSet object. As there are 18 rows in the titles tables, Fill stores 18 in the variable i. As before, we can use Response.Write function to display the value stored in the variable i. But, since this function requires a string, the ToString function from the int class is called to display this value in the string format.

In the aspx file, besides the asp button, we have introduced a new tag called <asp:DataGrid, having an id of l. This tag is capable of displaying data in a grid form.

In the function abc, we are initializing the DataSource property of l, i.e. a DataGrid to the data that it should display. The DataSet object 'd' has a member called 'Tables', which is assigned the value of zzz. If you recheck the program, you will find that the string zzz was provided to identify the DataSet. The DefaultView member of 'Tables', returns a view of the data. It is this series of statements that connects our DataGrid to our DataSet.

If we halt at this stage, no output will be displayed. To display data on the screen, a function called DataBind from the DataGrid class, has to be invoked. This function populates the DataGrid with data.

The DataBind function internally performs numerous tasks. The programmers who wrote the code for this function obviously possessed an extremely high IQ, since, it is no mean task to write a function that is endowed with such a high level of complexity. This function firstly ascertains the number of rows and columns in the result set. Accordingly, it creates an HTML table with the specified number of rows and columns. Thereafter, it retrieves the values from the result set and fills the table with all the data. Effortlessly, we can now view the data from a table in the database, simply by using one function.

In our opinion, the DataGrid control is extremely significant. So, we shall spend a little more time in understanding this control in greater detail, before shifting our focus to SQLServer. Since it is not our intention to confuse you any further, we shall populate the Data Grid with static data. We shall enter the data ourselves, rather than obtaining it from a database.

This DataGrid server control not only displays data in a tabular form, but also consents to perform certain basic operations on it, such as select, sort, page, edit, etc.

By default, the number of fields displayed in the control, are equal to the number of columns found in the data source. The field names appear at the top and all the values, irrespective of their data type, are rendered as text labels in a default format. a.aspx <%@ Import Namespace="System.Data" %> <html> <script language="C#" runat="server"> void Page_Load(Object s, EventArgs e) { DataTable d = new DataTable(); DataColumn c = new DataColumn("Integer", typeof(Int32)); DataColumnCollection c1 = d.Columns; c1.Add(c); d.Columns.Add(new DataColumn("Vijay", typeof(string))); d.Columns.Add(new DataColumn("Sonal", typeof(bool))); DataRow dr; dr = d.NewRow(); dr[0] = 1; dr[1] = "vijay1"; dr[2] = true; d.Rows.Add(dr); dr = d.NewRow(); dr[0] = 2;

dr[1] = "vijay2"; dr[2] = false; d.Rows.Add(dr); DataView dv = new DataView(d); l.DataSource = dv; l.DataBind(); } </script> <body> <form runat=server> <ASP:DataGrid id="l" runat="server" BorderColor="red" BorderWidth="1" GridLines="Both" CellPadding="3" CellSpacing="4" Font-Name="Verdana" Font-Size="8pt" HeaderStyleBackColor="#aaaadd" /> </form> </body> </html>

Output

As usual, the function Page_Load is called automatically. Here, we first create an object d, which is an instance of the class DataTable. Since every table has columns, a separate object c of type DataColumn class, is created to represent a column. The constructor of the DataColumn class takes two parameters:

The first is the column name i.e. Integer, enclosed within double quotes. The second is the data type of the column.

The class int is internally known as Int32. The word 'typeof' is a C# keyword, which returns an object of class Type. The syntax typeof(Int32) places an object of class Type representing the Int32 datatype, as the second parameter to the contructor.

An extremely large number of columns can be displayed in the DataGrid. Therefore, we need some mechanism to keep track of all these columns. This is where the Columns property which is available in the class DataTable, comes handy. This property returns an instance to the DataColumnCollection Object, which is stored in object c1. The Add function is called off the object c1, to store the column c.

Similarly, we can add two or more columns to our Data Table. The column named Vijay will contain data of type string, whereas, the column Sonal can only hold the data of type bool. However this time, we sidestep the DataColumnCollection statement and write these steps in one single statement. You can choose whichever method you are most comfortable with.

Once the columns have been added, we have to introduce the rows containing data for each of the column. To achieve this, we now create an object dr, which is an instance of the class DataRow, to represent a row of data. This object is then added to the DataGrid. The NewRow function creates a blank row. So, before adding it, we have to populate the three columns with some data.

The first column is represented by the variable dr[0], the second by the variable dr[1], and the third by the variable dr[2]. The square brackets are part of the syntax. Thereafter, we initialize the first column to an int value of 1, the second column to a string value of 'Vijay' and the third column to a bool value of True. Once the values are assigned to every column, the row is added to the table by calling the Add function in the Rows class of the DataTable.

We repeat the same procedure to add the second row. The DataTable object now consists of three columns and two rows.

We need one more object, which is a DataView object. The constructor of this object is provided with a DataTable object called 'd'. The DataSource property within DataGrid, accepts a DataView object and indirectly maps it to the DataTable object. Finally, DataBind is called to display the data within the table.

The DataGrid control has many more attributes, such as, foreground color, background color, spacing between columns, grid lines between columns, and so on. These options are endless. You could spend a month enhancing the look and feel of the DataGrid, however, we would advise you against spending your quality time in this manner, at this stage.

a.aspx <%@ Import Namespace="System.Data" %> <html> <script language="C#" runat="server"> void Page_Load(Object s, EventArgs e) { DataTable d = new DataTable(); DataColumn c = new DataColumn("Integer", typeof(Int32)); DataColumnCollection c1 = d.Columns; c1.Add(c); d.Columns.Add(new DataColumn("bad", typeof(double))); DataRow dr; dr = d.NewRow(); dr[0] = 11;

dr[1] = 1.234567; d.Rows.Add(dr); dr = d.NewRow(); dr[0] = 2; dr[1] = 4.3; d.Rows.Add(dr); DataView dv = new DataView(d); l.DataSource = dv; l.DataBind(); } </script> <body> <form runat=server> <ASP:DataGrid id="l" runat="server" BorderColor="black" BorderWidth="1" GridLines="Both" CellPadding="3" CellSpacing="0" AutoGenerateColumns="false"> <Columns> <asp:BoundColumn HeaderText="Price" DataField="bad" DataFormatString="{0:c}" ItemStyleHorizontalAlign="right" /> <asp:BoundColumn HeaderText="vijay" DataField="Integer" /> </Columns> </asp:DataGrid> </form> </body>

</html>

Output

Most of the code in the function Page_Load remains the same, except that we have removed one column completely and renamed the other column. This is to make the program smaller in size. The data type of the second column is 'double'. Hence, we can store values having decimal points in this column.

The <asp:DataGrid tag is given the same id of l, alongwith the other attributes of BorderColor, BorderWidth, and Autogeneratedcolumns. If you observe carefully, you will realise that the DataGrid tag does not end on the same line. The forward slash is now missing. Instead, we have closed the tag after a couple of lines, just as we did in the case of an HTML tag, using </asp:DataGrid>.

All statements inserted within the opening and the closing tag relate to the same object. One of the elements of the DataGrid object is 'property'. It is given the name Columns, which is a reserved word with a special meaning, and it ends after two lines.

Within the property tag, we have another control called <asp:BoundColumn, that represents the actual columns displayed. The new values given here, override the Column properties created in the function abc. The value given to HeaderText gets displayed as the column header, and DataField represents the column name that is to be changed. The column called 'bad' has two additional properties:

The first is DataFormatString, where we want the currency field displayed, with two decimal places. The second is ItemStyle-HorizontalAlign, which aligns the data to the right.

The control called BoundColumn influences the manner in which columns are displayed.

a.aspx <%@ Import Namespace="System.Data" %> <html> <script language="C#" runat="server"> void Page_Load(Object s, EventArgs e) { DataTable d = new DataTable(); d.Columns.Add(new DataColumn("c1", typeof(Int32))); d.Columns.Add(new DataColumn("c2", typeof(string))); DataRow dr; dr = d.NewRow(); dr[0] = 11; dr[1] = "String 1"; d.Rows.Add(dr); dr = d.NewRow(); dr[0] = 2; dr[1] = "String 2"; d.Rows.Add(dr); DataView dv = new DataView(d); l.DataSource = dv;

l.DataBind(); } </script> <body> <form runat=server> <ASP:DataGrid id="l" runat="server" GridLines="Both" AutoGenerateColumns="false"> <Columns> <asp:HyperLinkColumn HeaderText="Text of Header" DataNavigateUrlField ="c1" DataNavigateUrlFormatString ="a1.aspx?mukhi={0}" DataTextField ="c2" Target="_new" /> </Columns> </asp:DataGrid> </form> </body> </html>

a1.aspx <html> <head> <script language="C#" runat="server"> string s; void Page_Load(Object sender, EventArgs e) { s=Request.QueryString["mukhi"];

} </script> </head> <body> You selected <%= s %> </body> </html>

Output

Output : when String 1 is selected http://127.0.0.1/a1.aspx?mukhi=11 You selected 11

Output : when String 2 is selected http://127.0.0.1/a1.aspx?mukhi=2 You selected 2

In the function Page_Load, we have two columns c1 and c2, consisting of data types Int32 and string, respectively. Most of the code is similar to the earlier program, except for a few changes in the variable names and values.

We now introduce a new tag called <asp:HyperLinkColumn within the property tag. The attribute HeaderText is used to display the column heading. The most important attribute with the HyperLinkColumn control is DataTextField, which is assigned a column name. The text in this column becomes a hyperlink. DataTextField is initialized to the value of c2. Hence, String 1 and String 2 are displayed as hyperlinks on the table.

When we click on any of the hyperlinks, a URL is required for navigation. We can decide on the format of this url by initializing the attribute DataNavigateUrlFormatString to a value. In this case, we have provided the value a1.aspx?'mukhi'={0}.

ASP+ automatically adds http://localhost/ to the value and replaces {0} with the value of column c1. Thus, {0} is replaced by the contents of column c1, depending on the string that is selected. In case of String 1, the URL becomes http://localhost/a1.aspx?'mukhi'=11. Since Target is initialized to _new, it will open a new browser window to display the contents of the file.

The program a1.aspx displays the value of the parameter mukhi. This value is retrieved by using Request.QueryString with the parameter name, and then it is stored in a string called 's'. The value is then displayed on the screen using <%=.

Thus, we can use the tag HyperLinkColumn to convert values in a column of a DataGrid, into a hyperlink. Although we can use as many of such Column types as we like, however presently, as we are still learning the concept, we have restricted ourselves to only one Column type. Hence, we are not using BoundColumn in the same example. However, nothing stops you from doing so.

By clicking on the hyperlink in the file a1.aspx, we could use the value of 'mukhi' to load another series of records from a database. We can add more code to the file a1.aspx if we so desire.

a.aspx <%@ Import Namespace="System.Data" %> <html>

<script language="C#" runat="server"> void Page_Load(Object s, EventArgs e) { DataTable d = new DataTable(); d.Columns.Add(new DataColumn("c1", typeof(Int32))); d.Columns.Add(new DataColumn("c2", typeof(string))); DataRow dr; dr = d.NewRow(); dr[0] = 11; dr[1] = "String 1"; d.Rows.Add(dr); dr = d.NewRow(); dr[0] = 2; dr[1] = "String 2"; d.Rows.Add(dr); DataView dv = new DataView(d); l.DataSource = dv; l.DataBind(); } </script> <body> <form runat=server> <ASP:DataGrid id="l" runat="server" GridLines="Both" AutoGenerateColumns="true">

<Columns> <asp:BoundColumn HeaderText="Vijay" DataField="c1" /> <asp:BoundColumn HeaderText="mukhi" DataField="c2"/> </Columns> </asp:DataGrid> </form> </body> </html>

Output

Instead of two columns, we are now presented with four columns, because the property called AutoGenerateColumns is initialized to True. This modifies our DataGrid completely. We first see our Bound Columns 'Vijay' and 'mukhi', and then the columns that we have created in our DataTable, c1 and c2.

If the attributeAutoGenerateColumns is assigned the value of False, as was the case in the earlier programs, the columns originally placed in the DataTable get overridden by the new ones.

Session Variables

a.aspx <html>

<script language="C#" runat="server"> int i; void Page_Load(Object sender, EventArgs e) { i = (int)Session["mukhi"]; } </script> <body> <form runat=server> <%= i %> </form> </body> </html>

Output Server Error in '/' Application. ------------------------------------------------------------------------Value null was found where an instance of an object was required.

When the file is loaded in the browser, we get an application error. Let us understand the cause for this.

We have used a free object called Session with the [] brackets, to reference a word called 'mukhi'.The return value of this Statement is stored in the variable i. Since it has generated a null

reference error, it confirms that the word 'mukhi' does not exist in the Session object. It can safely be assumed that there is nothing wrong with our syntax.

a.aspx <html> <script language="C#" runat="server"> int i; void Page_Load(Object sender, EventArgs e) { if ( Session["mukhi"] == null) { Response.Write("one<br>"); i = 1; Session["mukhi"] = 20; } else { Response.Write("two<br>"); i = (int) Session["mukhi"] ; } } </script> <body> <form runat=server>

<%= i %> </form> </body> </html>

Output one 1

Let us try to understand this program step by step. We request you to run this program in the manner that we want you to, otherwise, our explanations may appear incomprehensible to you. When we run the aspx file in our browser, we get the output as displayed above.

The function Page_Load gets called, each time the page is sent to the browser. The earlier program failed because the value returned by Session["mukhi"], was null. Continuing on these lines, in the current program, the 'if' statement results in True, since Session["mukhi"] returns null. The Write function therefore displays one. Thereafter, the variable i is given a new value of 1, and Session["mukhi"] is initialized to 20.

Session['mukhi'] is initialized like any other variable, to a value. Since it is not a variable, this statement creates a word or a variable called 'mukhi', and links it with the running copy of your browser. <%= i %> within the form tags, displays the value of i as 1.

When you click on the Refresh Button in your browser, it will restart the procedure of requesting for the current file a.aspx from the server. Since the page is to be sent over, the function Page_Load is called once again. It is all the same, but this time, the 'if' condition with Session["mukhi"], fails. Since we have assigned it a value of 20, the session with 'mukhi' in square brackets, fetches the value of the variable 'mukhi'. Therefore, it is not null in this case. Hence, the output is as follows:

Output two 20

Since the 'else' block of 'if' statement is called, the value two is displayed, and the value of i is displayed as 20, since 'mukhi' was assigned this value earlier.

To summarize, Session["mukhi"'] creates a variable called 'mukhi' in the first round, if it doesn't already exist. By default, the value assigned to it is null, and hence, we have to initialize it to some value. In future, 'mukhi'- the session variable can be used like any normal variable.

What is so special about creating variables? Have we not created enough of them?

It is important to realise that the session variables are special. To prove this, start a fresh copy of the browser. To your utter surprise, you will see One and 1 displayed on the screen again. When you click on the Refresh button, you will see Two and 20.

This implies that ASP+ keeps track of the browser copies you are working with while accessing the same file. Each copy of the browser has a different value for 'mukhi'. Thus, 'mukhi' is a variable, but with a dash of lime. Every time we start a new copy of the browser, we get a new copy of this variable too. As a new browser starts a new session, all variables like 'mukhi' that are associated with a session, get reinitialized to their initial values.

This functionality is akin to ASP+, having a million eyes to monitor your activities, with every new copy of the browser. How it undertakes supervision of this magnitude, is yet another story!

Given below is another program designed to make the concept of sessions, more comprehensible for you.

a.aspx <html> <script language="C#" runat="server"> int i; void Page_Load(Object sender, EventArgs e) { if ( Session["mukhi"] == null) { i = 0; Session["mukhi"] = (int)i; } else { i = (int) Session["mukhi"] ; i = i + 1; Session["mukhi"] = i; } } </script> <body> <form runat=server> <%= i %>

</form> </body> </html>

Output 0

When we load the above program, we get to see the number zero in the browser window. In case you witness a value of 21, you need to start a new copy of the browser. This is because the session variable 'mukhi' already exists with the current copy of the browser.

Each time we click on the Refresh button, the number displayed is incremented by one. Once again, if you start a new copy of the browser, the value displayed will again be zero. Now, click on the Refresh Button a couple of times in the second copy, and then revert back to the first copy of the browser. Here, the browser still displays the old value. Refresh will increment this value, only by one. This confirms that there are two independent copies of 'mukhi', with their respective values associated with a particular copy of the browser.

The concept of sessions demonstrates the standalone behavior of data variables, depending upon the instance of a browser.

A Shopping Cart Example

We now apply this concept of sessions to create a shopping cart, one of the most widely used applications on the Internet.

a.aspx

<%@ Import Namespace="System.Data" %> <html> <script language="C#" runat="server"> DataTable Cart; DataView cv; void Page_Load(Object sender, EventArgs e) { if (Session["zzz"] == null) { Cart = new DataTable(); Cart.Columns.Add(new DataColumn("Item", typeof(string))); Cart.Columns.Add(new DataColumn("Price", typeof(string))); Session["zzz"] = Cart; } else { Cart = (DataTable)Session["zzz"]; } cv = new DataView(Cart); sc.DataSource = cv; sc.DataBind(); if (!IsPostBack) {

DataTable d = new DataTable(); d.Columns.Add(new DataColumn("c1", typeof(string))); d.Columns.Add(new DataColumn("c2", typeof(double))); DataRow dr; dr = d.NewRow(); dr[0] = "Product 1"; dr[1] = 11.3; d.Rows.Add(dr);

-6-

User Controls
In this chapter, you will learn a little more about C#, so that you can incorporate it while writing your own controls.

We will create our own controls in a slightly different manner than what was done earlier. To do so, we create:

a.aspx in c:\inetpub\wwwroot subdirectory. b.cs in c:\inetpub\wwwroot\bin subdirectory.

a.aspx <%@ Register TagPrefix="ttt" Namespace="nnn" Assembly="c"%> <html> <body> <form method="POST" action="s.aspx" runat=server> <ttt:zzz runat=server/> </form> </body>

</html>

b.cs using System.Web.UI; namespace nnn { public class zzz : Control { } }

You can compile the above file named b.cs, by giving the following command:

>csc /target:library /out:c.dll b.cs /r:System.Web.dll

The compiler creates a file called c.dll in the inetpub\wwwroot\bin subdirectory.

In the above C# program, we have simply created a class zzz that is derived from the class Control. The class Control belongs to the System.Web.UI namespace. We do not have any other code in our program. Thus, we see a blank screen.

The file a.aspx will remain the same for the initial programs.

b.cs

using System.Web.UI; namespace nnn { public class zzz : Control { protected override void Render(HtmlTextWriter o) { o.Write("<b>hell</b>"); } } }

We now have added a function called Render that accepts a parameter 'o', which is an instance of the class HtmlTextWriter, and its return type is void. The modifiers 'override' and 'protected', shall be explained to you, in a while. Also, we now call the Write function in the class HtmlTextWriter, and give it a string, <b>hell</b>.

When you load the aspx file, you will see 'hell' displayed in bold on your screen.

o is an instance of HtmlTextWriter. Now that we have seen some output, let us understand the working of the program.

In the file a.aspx, we have used a directive called Register (which has been explained in one of the earlier chapters), and created our own tag prefix called ttt. Along with these details, we have also declared a namespace called nnn. Our custom tag starts with the prefix ttt, followed by a colon and then the word zzz. By merely furnishing this information, we see the word 'hell' displayed in the browser window.

While executing the aspx file, when the web server comes across a custom tag, it first looks for the directory that is running the aspx file. On receiving the directory, it then looks into a subdirectory to locate another subdirectory called bin. In our case, bin is located in the c:\inetpub\wwwroot subdirectory. Thereafter, all the dlls in the bin subdirectory, are loaded into memory.

Every dll that is loaded into memory, contains information or metadata that consists of the classes and namespaces existing in it. The web server will check every file for the presence of a class named zzz (ttt: is followed by zzz) within the nnn namespace (This namespace is given with the Register directive). The file c.dll meets the match.

The Web server is programmed to call a function by the name of Render, which takes an HtmlTextWriter object as a parameter in the acquired dll. Using this object, text is rendered to the browser.

Thus, a user-defined tag is nothing but a class with the same name, but which derives from the class Control. Also, every user-defined tag must contain a function called Render.

Now, let us get back to C# and understand what the word 'protected' signifies.

z.cs public class zzz { public static void Main() { yyy a = new yyy(); a.abc(); }

} public class yyy { private void abc() { } }

Output z.cs(6,1): error CS0122: 'yyy.abc()' is inaccessible due to its protection level

If you compile the above code as

>csc z.cs

an error will be generated.

This is because the function abc is tagged with the modifier private. The private modifier allows only the members of the same class to access the function. As a result, only members of the class yyy are allowed to access the function abc. Therefore, the object 'a' of type yyy in the class zzz, is restricted any access to private members of the class yyy.

Thus, private is called an access modifier, since it prohibits access to members of a class. Private is the most restrictive access modifier, while public is the most tolerant. These access modifiers do not apply to members of the same class.

z.cs

public class zzz { public static void Main() { xxx a = new xxx(); a.abc(); } } public class yyy { } public class xxx : yyy { protected void abc() { } }

Output z.cs(6,1): error CS0122: 'xxx.abc()' is inaccessible due to its protection level

The same error gets repeated again with the protected modifier as a protected member is accessible only to a derived class object.

Had any member of class yyy tried to access the functions in class xxx, which has been derived from the class yyy, no errors would have been generated. A protected modifier signifies that only derived classes are allowed access its members. Thus, a protected modifier lies in the midst of the two extremes, private and public.

z.cs public class zzz { public static void Main() { xxx a = new xxx(); yyy b = new yyy(); xxx c = new yyy(); yyy d = new xxx(); } } public class yyy { }

public class xxx { }

Output z.cs(7,9): error CS0029: Cannot implicitly convert type 'yyy' to 'xxx' z.cs(8,9): error CS0029: Cannot implicitly convert type 'xxx' to 'yyy'

C# is extremely stern about equating different data types to each other. Thus, we cannot equate a yyy object with an xxx object. The entities on both sides of an 'equal to' sign must have the same data type, or else an error stating 'cannot covert to', is generated.

z.cs public class zzz { public static void Main() { xxx a = new xxx(); yyy b = new yyy(); xxx c = new yyy(); yyy d = new xxx(); } } public class yyy { } public class xxx : yyy {

Output z.cs(7,9): error CS0029: Cannot implicitly convert type 'yyy' to 'xxx'

Now, the error vanishes because, class xxx is derived from class yyy. As a result, class xxx now comprises of two classes, a yyy class and an xxx class. Therefore, the statement xxx c = new yyy() does not raise any error.

As class xxx derives from class yyy, we call xxx a higher class, since it contains the lower class yyy, and more. We can thus, have a higher class on the right hand side of the 'equal to' sign and a lower class on the left hand side. Technically speaking, we can use a derived class on the right hand side, and a base class on the left hand side of an 'equal to' sign.

If they are placed the other way around, that is, if the class yyy is on the right hand side and the xxx class is on the left hand side, an error is generated. A derived class cannot be made equal to a base class.

z.cs public class zzz { public static void Main() { yyy a = new xxx(); a.abc(); a.pqr(); } }

public class yyy { public virtual void abc() { System.Console.WriteLine("yyy abc"); } public virtual void pqr() { System.Console.WriteLine("yyy pqr"); } } public class xxx : yyy { public override void abc() { System.Console.WriteLine("xxx abc"); } public new void pqr() { System.Console.WriteLine("xxx pqr"); } }

Output

xxx abc yyy pqr

We have two functions in class yyy namely, abc and pqr. We have added a modifier named 'virtual' to these functions. This modifier permits the derived classes to override the functions abc and pqr. Without the word virtual, the derived classes cannot override functions in the base class.

The derived class has the option of overriding the functions of the base class, i.e. creating a new function with the same names which may or may not bear any relation to the functions of the base class.

Adding a modifier 'new' to the virtual function in the derived class, breaks all links with the function having the same name in the base class. Thus, the base class pointer has no access to the derived class functions.

The override modifier overrides the function of the base class. 'a' is a pointer to a yyy class and it is initialized to the derived class xxx. Hence, when we call a.abc(), the function abc of the derived class xxx will be called.

Thus, in the case of a virtual function, C# goes a step further and checks the run time data type of the object, and not the compile time data type. If the function in the derived class has an override modifier, as in the case of the function abc, the function gets called from the derived class. In case of new, as in the case of the function pqr, it becomes a new function. And thus, it ignores the existence of such a function in the class xxx. The only option available is to call the function from the class yyy itself.

There is a function called Render in the class Control. If we want our function Render to be called in class zzz, we have to use the override modifier. Otherwise, the function will be called from the class Control instead.

z.cs

public class zzz { public static void Main() { yyy a = new xxx(); a.abc(); } } public class yyy { public virtual void abc() { System.Console.WriteLine("yyy abc"); } } public class xxx : yyy { protected override void abc() { System.Console.WriteLine("xxx abc"); } }

Output z.cs(18,25): error CS0507: 'xxx.abc()': cannot change access modifiers when overriding 'public' inherited member 'yyy.abc()'

We get the above error because, when we override a function of the base class, we cannot change it's access modifiers. Everything, including the modifiers, must be identical to what is present in the base class. Since the function Render is marked as protected in the base class, we have to use the same access modifier in the class zzz also.

Let us get back to Controls again.

a.aspx <%@ Register TagPrefix="ttt" Namespace="nnn" Assembly="c"%> <html> <body> <form method="POST" action="S.aspx" runat=server> <ttt:zzz aa="hi" bb=100 runat=server/> </form> </body> </html>

b.cs using System.Web.UI; namespace nnn {

public class zzz : Control { public string s; public string aa { get { return s; } set { s = value; } } public int bb = 12; protected override void Render(HtmlTextWriter o) { o.Write("hell " + bb + " " + aa); } } }

Output

hell 100 hi

A property can either consist of a getset accessor or it can contain a simple instance variable. Also, it can be used in place of a variable. In the case of a property, source code can be executed. However, the user of the tag will never be exposed to the internal workings of a property and its implementation in a tag.

The set accessor is called before the function Render gets executed. This enforces the situation where all the properties have to be initialized first, and only then the Render function can be executed.

a.aspx <%@ Register TagPrefix="ttt" Namespace="nnn" Assembly="c"%> <html> <body> <form method="POST" action="S.aspx" runat=server> <ttt:zzz aa-bb="hi" aa-cc=100 runat=server/> </form> </body> </html>

b.cs using System; using System.Web; using System.Web.UI; namespace nnn

{ public class yyy { public string bb = "no"; public int cc = 200; } public class zzz : Control { yyy a = new yyy(); public yyy aa { get { return a; } } protected override void Render(HtmlTextWriter o) { o.Write(aa.bb + " " + aa.cc); } } }

Output hi 100

We look at the .cs file first. In the class zzz, we have created an object a, that is an instance of the class yyy. This class is created in the same namespace nnn as given along with the aspx Register directive. aa is a property that returns a yyy object in its get accessor. Class yyy also has two members named bb and cc, which are initialized to 'no' and 200, respectively. Once a yyy object is created, using the dot syntax, we can access these members individually. In an aspx file, a minus sign is used instead of a dot, to access the members. Hence, to access the bb member in yyy, we use the statement 'aa-bb'.

The only difference here is in the choice of the separator, between the name of the property and the name of the member, belonging to the object that the property returns.

Now, we return back to C#.

z.cs public class zzz { public static void Main() { int [] a; int i; a = new int[3]; a[0] = 1; a[2] = 8;

a[0]++; System.Console.WriteLine(a[0]); i = 0; System.Console.WriteLine(a[i]); i = 2; System.Console.WriteLine(a[i]); } }

Output 2 2 8

Whenever we want to store multiple items of the same type, we use a data type called an array. An array stores similar items together. Here, 'a' is an array that is declared, using a pair of square brackets []. We now proceed to create an array of ints. To do so, the keyword 'new' is used along with the size of the array, which in our case is 3. The array size cannot be specified at the time of creation of the array. It must be specified along with 'new'.

To access the members of the array, we use the name of the array, followed by a pair of square brackets which enclose the index of the specific array variable. Thus, the first variable is a[0], the second is a[1], and so on. The counting for the array index begins with zero and not from 1.

An array variable can be easily used in place of a normal variable. The advantage in using arrays is that it makes the code concise. For example, when we use the form a[i], i is an integer variable

holding values ranging from 0 to 2. When the value of i is 0, the name of the variable becomes a[0]. When we change the value of i to 1, the name of the variable now becomes a[1]. Thus, by changing the value of one variable, we are able to change the name of another variable, and thus, access a different value.

It is this feature of arrays, which makes them very useful. We are guilty of the crime of having used arrays earlier in this book, without explaining them in detail.

z.cs public class zzz { public static void Main() { int [] a; int i; a = new int[3]; for ( i = 0; i<=2; i++) a[i] = i*2; System.Console.WriteLine(a.Length); for ( i = 0; i< a.Length; i++) System.Console.Write(a[i]); } }

Output 3 024

Arrays are ideal in a looping construct. In the first 'for' loop, we initialize the variable a[0] to 0, a[1] to 2 and a[2] to 4. Every array type has a member called Length, that returns the size of the array. In our case, the array size is 3. We can use this fact to iterate through all the members of the array.

z.cs public class zzz { public static void Main() { string [] a; a = new string[]{"hi","bye"}; foreach ( string s in a) System.Console.WriteLine(s); } }

Output hi bye

We can create an array of any data type. Earlier, we created an array of type int. In this program, we have created an array of type string. We are also allowed to initialize the array members at the time of creation, by using the square brackets.

We can use the 'foreach' statement to iterate through the array. During each iteration, the string 's' will sequentially hold the string values in the array. Thus, in the first iteration, 's' will contain the string 'hi', and in the next iteration, it will contain the string 'bye'.

The 'foreach' construct is a more convenient way of iterating through an array, though we could even have used a 'for' construct. You are free to choose from any of these constructs, as per your requirement.

z.cs public class zzz { public static void Main() { yyy a = new yyy(); a[2] = "hi"; System.Console.WriteLine(a[2]); } } public class yyy { public string a;

public string this[int i] { get { System.Console.WriteLine("get " + i); return a; } set { System.Console.WriteLine("set " + value + " " + i); a = value; } } }

Output set hi 2 get 2 hi

Although, we have not created any array in the above program, we are still using the array syntax. We first create an object 'a' of type yyy. Then we use the syntax a[2] = "hi". When the program reaches this statement, C# stops for a while and looks for an indexer in our program.

An indexer is a property with a special name called 'this'. Since we have created such a property, C# calls the set accessor of this property and assigns a value of 2 to the parameter i. As the return type of the property is a string, the hidden variable named 'value' contains the string 'hi'. We are supposed to simulate an array within the property. Since this has not been done, the indexer simulates an array that does not exist.

Let us get back to ASP+.

a.aspx <%@ Register TagPrefix="ttt" Namespace="nnn" assembly="c"%> <html> <body> <form method="POST" action="a.aspx" runat=server> <ttt:zzz runat=server> vijay mukhi </ttt:zzz> </form> </body> </html>

b.cs using System; using System.Web; using System.Web.UI; namespace nnn

{ public class zzz : Control { protected override void Render(HtmlTextWriter o) { if ( HasControls() ) o.Write("True <br>"); LiteralControl l = (LiteralControl) Controls[0]; o.Write(l.Text); } } }

Output True vijay mukhi

In the aspx file, we have inserted the text 'vijay mukhi' within ttt, which is a newly created tag. We would like to display this text in the browser.

To do so, we call a function called HasControls in the Render function, which does not take any parameter.

Since this function is not present in our class zzz, it is taken from the Control class. The return value of true or false depends upon the presence of controls in our web page. If the page has controls, HasControls shows true, or else, it shows false.

The class Control has a property called Controls that returns a ControlCollection object. This class has an indexer that returns a Control object. Thus, the use of Controls[0] will return the first control on our page.

In our program, Controls[0] returns a LiteralControl, which is a class derived from Control. Hence, the cast operator is required.

The Text property in this control, displays the text given within the tag.

a.aspx <%@ Register TagPrefix="ttt" Namespace="nnn" assembly="c"%> <html> <body> <form method="POST" action="a.aspx" runat=server> <ttt:zzz id="hi" runat=server> vijay mukhi </ttt:zzz> <asp:Button id="bye" runat=server> </asp:Button> </form> </body> </html>

b.cs using System; using System.Web; using System.Web.UI; namespace nnn { public class zzz : Control { protected override void Render(HtmlTextWriter o) { int j = Controls.Count; o.Write(j + "<br>"); for( int i = 0; i< j; i++) { if ( Controls[i] is LiteralControl ) { LiteralControl l = (LiteralControl) Controls[i]; o.Write(l.Text + " " + l.ClientID); } } } }

Output 1

vijay mukhi ctrl1

The class ControlCollection has a member called Count, which contains a count of the number of Controls that are present on our page. The value held in this member is 1, which indicates that the Button control used outside the ttt tag, has not got added to our collection.

A 'for' loop is used to iterate through the collection. A check is performed for a LiteralControl; thereafter, two members of this control, Text and ClientID, are displayed. The member ClientID shows crtl1, even though it has been assigned an id of 'hi'. These controls are called child controls.

Composite Controls

a.aspx <%@ Register TagPrefix="ttt" Namespace="nnn" assembly="c"%> <html> <script language="C#" runat=server> void abc(Object sender, EventArgs e) { hi.aa++; }

</script> <body> <form method="POST" action="a.aspx" runat=server> <ttt:zzz id="hi" runat=server/> <asp:button text="Add" OnClick="abc" runat=server/> </form> </body> </html>

b.cs using System; using System.Web; using System.Web.UI; using System.Web.UI.WebControls

-7-

CGI Programming
This chapter concentrates on the basics of the Internet. By the time you reach the end of this chapter, you will be comprehensibly conversant with the role of a web server, a web browser and ASP.Net. You will also be in a position to appreciate the indispensability of ASP.Net, in writing powerful business applications.

Understanding the samples provided by Microsoft, is akin to viewing ASP from a height of 10000 miles.

At the outset, you are required to create a file called a.cs in the sub-directory c:\inetpub\scripts. We will explain the relevance of this subdirectory in due course of time.

a.cs public class zzz { public static void Main() { System.Console.WriteLine("<b>hi"); } }

The above is a short and sweet C# program! Now, compile this program using the csc command, as in csc a.cs. Then, run the executable and your dos screen will simply display 'hi' with the bold tag in front of it.

To run this exe file from our browser, we key in the following URL in the browser.

http://localhost/scripts/a.exe

This URL seems logical, since we have placed the file a.exe in the scripts sub-directory. But, we do not seem to get anything right the first time. This is evident from the following errors that have been generated:

Output CGI Error The specified CGI application misbehaved by not returning a complete set of HTTP headers. The headers it did return are: hi

The first line indicates that we have written a CGI application. CGI stands for Common Gateway Interface. And we have not adhered to the rules pertaining to a CGI application. The web browser expects a complete set of headers, which we have not provided. Subsequently, we see 'hi' displayed in bold.

Before moving into the details about the rules, headers etc. of CGI programming, we shall send a header across.

a.cs public class zzz { public static void Main() { System.Console.WriteLine("Content-Type:text/html"); System.Console.WriteLine("<b>hi"); } }

We compiled the above program as before and provided the same URL in the browser. It is preferable to load the browser again and provide the URL. You could even click on the refresh icon instead. Whichever method you follow, the same error is generated again.

In future, we will not repeat these steps, but we do expect you to follow them, so that your output matches with ours. Writing one more WriteLine function makes no difference at all.

a.cs public class zzz { public static void Main() { System.Console.WriteLine("Content-Type:text/html\n"); System.Console.WriteLine("<b>hi"); }

Output hi

The mere inclusion of an 'enter', represented by '\n', results in elimination of all the errors. We now see the word 'hi' displayed in bold in our window. Before we explain as to why everything suddenly starts working fine, let us make a small modification in the above program.

a.cs public class zzz { public static void Main() { System.Console.WriteLine("Content-Type:text/plain\n"); System.Console.WriteLine("<b>hi"); } }

Output <b>hi

Now, it is time for us to demystify this mystery.

The web or the HTTP protocol is very simple to understand if you follow certain rules. When the browser requests for a file from the web server, depending upon the extension given to the file, the Web Server does one of the following:

It picks the file up from its local hard disk and sends it across OR

It executes the executable file which has been requested for, from the disk which generates this file and sends it over.

In the case of a file with a .exe extension, the server executes the file or program on its machine. This program is not restricted to producing an HTML file only. It can create a file of any type. If it were restricted to generating only HTML files, it would have made the web very restrictive.

The contents of every file vary depending on the file type. For example, an HTML file will contain tags; a .jpg file will contain images, and so on. The browser must display the files in the right format, on receiving them.

To inform the browser about the file coming across, the exe file or program creates a header that signifies the file type or the content type. A header is nothing but a word that is given some value and which ends with a colon. Thus, the phrase 'Content-Type' is a header since it ends in a colon, and the value assigned to it is 'text/plain'.

The rules of CGI state that all headers must end with an Enter or '\n' symbol. This is so because a file can have multiple headers. An 'enter' symbol, when placed by itself on a line, signifies the end of all the headers. It also marks the start of the content. The Web server is free to add its own headers to the list of headers generated by the program. This composite data is then transferred to the browser.

Since the headers were not specified in the first program, an error was generated. The presence of a Content-Type header in a sense is mandatory for any file that has to be transferred from the server to the browser. The second error was reported because we had omitted the 'enter' symbol all by itself, on a separate line, to mark the end of all headers. Thus, more headers were expected from the server. When this did not happen, the browser generated an error. The WriteLine function adds an 'enter' symbol by default, but an additional \n is required all by itself, to indicate an end to the Header values.

The browser uses the header named Content-Type, to determine the type of data sent by the web server. Accordingly, it displays the file in the right format.

The type text/html refers to a text file containing html tags. Thus, 'hi' was displayed in bold. However, the header value of text/plain informs the browser that plain text content is being sent over, and hence, the tags are not parsed.

a.cs class zzz { public static void Main() { string s; System.Console.WriteLine("Content-Type:text/html\n"); s=System.Environment.GetEnvironmentVariable("PATH"); System.Console.WriteLine(s); } }

Output
C:\Program Files\Microsoft.Net\FrameworkSDK\Bin\;C:\WINNT\Microsoft.NET\Framewor k\v1.0.2204\;C:\WINNT\system32;C:\WINNT;C:\WINNT\System32\Wbem;C:\Program Files\Microsoft SQL Server\80\Tools\BINN

An environmental variable is a word stored by the operating system. In the world of Windows 2000, if we give the command >set in the dos box, a list containing a number of words with their corresponding values is displayed.

At the command prompt, if we give the command >set aa=hi, it creates an environmental variable named 'aa' and assigns it a value of 'hi' for the current dos session. On issuing the same set command again, this recently created variable and its value, get displayed along with the other environmental values.

The namespace System.Environment has a static function called GetEnvironmentVariable. This function accepts an environmental variable name and returns its value. In our program, we ask the function to display the value of the environmental variable named PATH.

These variables are created and maintained by the operating system. The web server too can ask the operating system to create some variables, before it executes a program.

a.cs class zzz { public static void Main() { System.Collections.IDictionary i; i=System.Environment.GetEnvironmentVariables(); System.Collections.IDictionaryEnumerator d; d=i.GetEnumerator ();

System.Console.WriteLine("Content-Type:text/html\n"); System.Console.WriteLine(i.Count + "<br>"); while (d.MoveNext()) { System.Console.WriteLine("{0}={1}<br>",d.Key,d.Value); } } }

The above program shows 46 environmental variables in the browser. An object named i of datatype IDictionary is defined. It is initialized to the return value of the static function called GetEnvironmentVariables.

This function returns an object that contains all the environmental variables. We need a constant way of retrieving data that is similar, but which has multiple occurrences. To do so, the designers of the C# programming language have given us an enumeration object which enables us to list the multiples values. We use the GetEnumerator function from the object 'i', and store its return value in the enumeration object named 'd'. The object named MoveNext iterates through the list of values. The object contains two members called Key and Value. Basically, the format is Key=Value. Thus, Key stands for the variable name and Value is the value contained in the Key.

In the WriteLine function, {0} displays the first parameter, {1} displays the second variable, and so on. The Count member of IDictonary returns the count of the environmental variables.

Some of the variables are created by the Operating System while it starts execution. The others are created by the IIS WebServer. We searched the world over, but could not find a variable named Query_String.

This program will be used in the future. So we want you to make a copy of it and name it as b.exe: >copy a.exe b.exe

a.html <html> <body> <form action=http://localhost/scripts/a.exe> <input type = text name = aa> <input type = text name = bb> <input type = submit value = click> </form> </body> </html>

The above HTML file is placed in the wwwroot sub-directory and loaded as http://localhost/a.html. This file shows two textboxes and a button labeled 'Click'. After entering the words 'hi' and 'bye' in these textboxes, click on the button. You will be surprised to see the browser displaying the same output as shown in the earlier program. But observe that the count now displays the number 48, and the address bar now contains the new URL http://localhost/scripts/a.exe?aa=hi&bb=bye. One of the newly added name-value pair is :

QUERY_STRING=aa=hi&bb=bye

On receiving the new URL from the web browser, the server simply creates an environmental variable called QUERY_STRING and initializes it with the values that are contained in the URL after the ? symbol. Thereafter, it calls the program named a.exe given in the URL, from the relevant directory.

The program on the server can easily identify as to what the user has entered in the textboxes. It simply has to use the Request class or parse the QUERY_STRING variable.

Cookies

Before taking a leap into this section, we would like you to set a few options in your browser. First, go to menu option 'Tools' and select the last option named 'Internet Options'. Select the Security tab. Ensure that you have selected the Local Intranet option and click on Custom level. Scroll down the list box until you see the heading 'Cookies'. For both the sub options, select the 'Prompt' radio button. The default is 'Enable'. Restart the browser after making the changes. Now, run the program given below in your browser.

a.cs class zzz { public static void Main() { System.Console.WriteLine("Content-Type:text/html\nSet-Cookie:aa=vijay\n"); System.Console.WriteLine("hi"); } }

To our utter surprise, we see a dialog box titled 'Security Alert', asking us whether we would be interested in saving a temporary file sent by the WebServer on our hard disk. This file is termed as cookie.

Firstly, we click on the button labeled 'More Info'. This extends the dialog box to give us more information about the cookie. Notice that the cookie is named as aa, and along with other information, it reveals that the data in this cookie is vijay. Click on 'yes' and you will see 'hi' in the browser. Subsequently, if you run b.exe in the browser, it will display all our environmental variables as before. But now, an additional environmental variable called HTTP_COOKIE is created with the value of aa=vijay.

Before we go further, let us first run the following ASP program in the browser using:

http://localhost/a.aspx?aa=hi&bb=bye

a.aspx <html> <%@ language="C#" %> <body> <% Request.SaveAs("c:\\z.txt",true); %> </body> </html>

z.txt GET /a.aspx?aa=hi&bb=bye HTTP/1.1 Connection: Keep-Alive Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, */*

Accept-Encoding: gzip, deflate Accept-Language: en-us Host: localhost User-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0; COM+ 1.0.2204)

For the ones who came in late, whenever we click on a button of type submit, a new URL is generated. The Web browser calls on the WebServer again, and sends it a packet of data.

To view the contents of this packet, the Request property is used. This property returns an HttpRequest object. SaveAs is one of the functions in the object that takes two parameters:

The filename in which it can save the request. A bool value of true or false. If the value is true, the header is also saved in the file.

Any packet sent by the browser has two parts to it. It starts with the word GET, followed by the URL that is to be fetched. The name of the computer, localhost, is removed from the URL, as the browser connects to it. Following it is the data, as entered in the browser window.

All this is part of the HTTP protocol. The protocol states that the URL is to be followed by the http version number.

When the web server sends data to the browser, the packet starts with the headers, followed by a blank line, and finally, followed by the rest of the HTML file. On the other hand, in the packet sent from the browser, the URL is stated first, followed by the data and finally, there are the headers. This is exactly the reverse of what happens in the case of the web server!

At first, we run the executable from the browser as http://localhost/scripts/a.exe and accept the cookie. Thereafter, the file a.aspx is copied from c:\inetpub\wwwroot to c:\inetpub\scripts and loaded as http://localhost/scripts/a.aspx. The file named z.txt, is shown below.

z.txt GET /scripts/a.aspx HTTP/1.1 Connection: Keep-Alive Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, */* Accept-Encoding: gzip, deflate Accept-Language: en-us Cookie: aa=vijay Host: localhost User-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0; COM+ 1.0.2204)

A cookie has a header named Set-Cookie, which is sent by the server to the client. A point to be noted here is that the server initiates a cookie, and not a client.

There is a program that runs on the server, which directs the server to send a cookie, which has a specific name and value. When the client browser, which could be Netscape, IE or any other browser, sees a header named Set-Cookie, it checks for the cookie-option values. If the prompt is set on, the browser will display a message, thereby, requesting for permission to accept or reject the cookie.

If the reply is 'yes', then whenever the client connects to the server, it will contain a header named Cookie, which it will send to the server. Thus, we see the header Cookie: aa=vijay in the file z.txt. The text 'Set-' is removed from the Header.

Thus, a cookie is basically a header-value that is sent by the server, and which is returned by the browser.

These cookies remain in existence only until the browser is alive. If you close the current copy of the browser and reload it again with the file a.aspx, the cookie header will not be seen.

System.Console.WriteLine("Content-Type:text/html\nSet-Cookie:aa=vijay; path=/aa\n");

A cookie header, along with the name-value, has a path that decides on the sub-directories that the cookie can be sent to. On running a.exe from the scripts sub-directory, the path parameter in the cookie dialog box shows the path as /scripts/.

Therefore, if you load a.aspx from the inetpub\wwwroot sub-directory, it will not show the Cookie: header in the file z.txt. This is because the browser not only stores the domain name or name of the computer, but also the URL or sub-directories that the cookie should be sent to. As the path is /scripts, the browser will only send a Cookie: header to the URLs that access files in the /scripts sub-directory.

Now, we shall see how our cookies can be made eternal, so that they never say die.

a.cs class zzz { public static void Main() {

System.Console.WriteLine("Content-Type:text/html\nSet-Cookie:aa=Vijay; expires=Tuesday, 03-04-2002 12:12:23\n "); System.Console.WriteLine("hi"); } }

After leaving a space after the semicolon, we have simply added the word 'expires'. This is initialized to a date in a certain format, followed by time in hours, minutes and seconds. The cookie dialog box( that had earlier displayed the Expires as 'end of session), now displays a specific date.

Upto this date, each time we connect to a certain path on the server called localhost, the browser will send this cookie. The earlier cookies were termed as 'session cookies', since their life span extended only till the end of the session. The cookies where 'expires' is mentioned, are called 'non session cookies'. If we disable the cookies, the browser does not send the Cookie: header to the server.

Let us now understand the Response and Request objects in ASP.Net, which are introduced when they are derived from the Page class.

The Request Object

The property Request in the Page class, is of type HttpRequest, and it contains code that handles the data sent by the browser.

This makes it easier for our aspx program to parse the output sent to us by the browser.

a.aspx

<html> <%@ language="C#" %> <body> <% String[] s = Request.AcceptTypes; Response.Write(s.Length.ToString()); for (int i = 0; i < s.Length; i++) { Response.Write(s[i] + "<br>"); } %> </body> </html>

Output 8image/gif image/x-xbitmap image/jpeg image/pjpeg application/vnd.ms-powerpoint application/vnd.ms-excel application/msword */*

The web server sends the header Content-Type to signify the type of content that is to follow. The type given after Content-Type is also called the 'MIME type'. The client, i.e. the browser too sends across the types it supports, by using a header called Accept.

This header is sent as follows:

Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, */*

Thus, the MIME type starts with the name of a family, such as image, text, application etc. This is followed by a slash /, after which we specify the different types within the family. The symbol */* indicates that the browser supports all MIME types.

The Request object has a property called AccessTypes, which returns an array of strings. We simply display them using a 'for' loop. The Length property gives us the number of members present in the array.

a.aspx <%@ language="C#" %> <% Response.Write(Request.ApplicationPath); %>

Output /

The property ApplicationPath displays the virtual path to the currently running server application. Even if you copy the file in the scripts sub-directory and change the URL to http://localhost/scripts/a.aspx, the result will still be a slash i.e. /.

a.aspx <%@ language="C#" %> <% HttpBrowserCapabilities b = Request.Browser; Response.Write("Type = " + b.Type + "<br>"); Response.Write("Name = " + b.Browser + "<br>"); Response.Write("Version = " + b.Version + "<br>"); Response.Write("Major Version = " + b.MajorVersion + "<br>"); Response.Write("Minor Version = " + b.MinorVersion + "<br>"); Response.Write("Platform = " + b.Platform + "<br>"); Response.Write("Is Beta = " + b.Beta + "<br>"); Response.Write("Is Crawler = " + b.Crawler + "<br>"); Response.Write("Is AOL = " + b.AOL + "<br>"); Response.Write("Is Win16 = " + b.Win16 + "<br>"); Response.Write("Is Win32 = " + b.Win32 + "<br>"); Response.Write("Supports Frames = " + b.Frames + "<br>"); Response.Write("Supports Tables = " + b.Tables + "<br>"); Response.Write("Supports Cookies = " + b.Cookies + "<br>"); Response.Write("Supports VB Script = " + b.VBScript + "<br>"); Response.Write("Supports Java Script = " + b.JavaScript + "<br>");

Response.Write("Supports Java Applets = " + b.JavaApplets + "<br>"); Response.Write("Supports ActiveX Controls = " + b.ActiveXControls + "<br>"); Response.Write("CDF = " + b.CDF + "<br>"); %>

Output Type = IE5 Name = IE Version = 5.5 Major Version = 5 Minor Version = 0.5 Platform = WinNT Is Beta = False Is Crawler = False Is AOL = False Is Win16 = False Is Win32 = True Supports Frames = True Supports Tables = True Supports Cookies = True Supports VB Script = True Supports Java Script = True Supports Java Applets = True

Supports ActiveX Controls = True CDF = False

The Browser property in the Request Object returns an object of type HttpBrowserCapabilities. Thus, an object b of this type is created and it stores the return value of this property. We then display all the members of this class, which consist of the features of the browser that just connected to the server.

Depending upon the values that are supported and returned by the browser, the aspx file can be made generic, to enable it to handle the differences among browsers.

The type member returns the name of the browser along with its version number, whereas, the Browser property returns only the name. The version number is displayed as 5.5. We can even display the major and the minor version numbers separately. It is mandatory to have the Version of the Explorer greater than 5.0, otherwise, the .Net framework does not reveal the right values. The property named 'Platform' informs us about the Operating System that the browser is running on. If the browser is currently running on Windows 2000, the platform property still displays the value as WinNT. Our version of IE is the final copy, and not the beta version, hence, the value of the property named beta is shown as false.

Search engines crawl all over, looking for websites. Since ours is a simple browser, the property named IsCrawler is shown as false. America Online is the largest on-line service in the world and it has its own branded browser. Since we are using IE from Microsoft, the property named AOL has a value of false.

Earlier, Microsoft had a 16 bit operating system called Windows 3.1. As we are presently running their 32 bit Operating system, the property Win16 is false, while the property Win32 is true. An HTML page is divided into smaller parts by frames. Today, all browsers support frames. Thus, the Frames property has a value of true.

Earlier some browsers could not display tables. Thus, the tables property was introduced in the object. Today, all the browsers fully support tables. However, not every browser can run Java applets within the browser. In our case, since IE can do so, the JavaApplets property is true.

All browsers support cookies, since it is a standard created by Netscape. We have two main client side scripting languages, VBScript from Microsoft and Javascript from Netscape. Since our browser supports both, their properties are true. And since ActiveX was invented by Microsoft, this property also has a value of true.

Finally, if we want to webcast something, there is a new format called Channel Definition Format or CDF, which has to be used. For some reason, IE does not support it.

a.aspx <%@ language="C#" %> <% Encoding e = Request.ContentEncoding; Response.Write(e.EncodingName); %> Output Unicode (UTF-8)

The Request.ContentEncoding property returns an Encoding object. This object also has a large number of properties and methods. One of them is called EncodingName, which reveals the Character Set that the browser uses to transfer data to and fro.

a.cs class zzz {

public static void Main() { System.Console.WriteLine("Content-Type:text/html"); System.Console.WriteLine("Set-Cookie:aa=vijay0; expires=Tuesday, 09-09-2001 12:12:23"); System.Console.WriteLine("Set-Cookie:a1=vijay1; expires=Tuesday, 09-09-2001 12:12:23"); System.Console.WriteLine("Set-Cookie:a2=vijay2; expires=Wednesday, 10-10-2001 12:12:23\n"); System.Console.WriteLine("hi"); } }

We first loaded the following C# executable from the script sub-directory:

http://localhost/scripts/a.exe

This sets three cookies for the browser session, which is currently active.

Then, we ran the aspx program (as given below) from the scripts sub-directory, using:

http://localhost/scripts/a.aspx

a.aspx <%@ language="C#" %> <%

HttpCookieCollection cc; cc = Request.Cookies; Response.Write(cc.Count.ToString() + "<br>"); for (int i = 0; i < cc.Count; i++) { HttpCookie c = cc[i]; Response.Write(c.Name + "=" + c.Value + "<br>"); } %>

Output 4 aa=vijay0 a1=vijay1 a2=vijay2 ASP.NET_SessionId=wnyumy5544u3tj55tdrp0u45

Request.Cookies returns an HttpCookieCollection object that is stored in the object cc. This object named cc has a member named count, which returns a count of the number of cookies present in the collection. We have 4 cookies, and hence, the 'for' loop is repeated four times.

HttpCookieCollection has an indexer that allows access to the individual cookies. Thus, cc[0] refers to the first HttpCookie object, and so on. The HttpCookie class in turn, has two important members, i.e. Name and Value, which display the name of the cookie and its value, respectively.

a.aspx <%@ language="C#" %> <% HttpCookieCollection cc; cc = Request.Cookies; HttpCookie c = cc["a1"]; Response.Write(c.Name + "=" + c.Value + "<br>"); %>

Output a1=vijay1

The indexer in the HttpCookieCollection object can also accept a string, which is the name of the cookie. It returns a cookie object that represents that cookie. The Value member will display the value contained in the cookie. This will retrieve only a single cookie.

a.aspx <%@ language="C#" %> <% HttpCookieCollection cc; HttpCookie c; cc = Request.Cookies; String[] s = cc.AllKeys;

for (int i = 0; i < s.Length; i++) { Response.Write(s[i] + "<br>"); } for (int i = 0; i < s.Length; i++) { c = cc[s[i]]; Response.Write("Cookie: " + c.Name + " "); Response.Write("Expires: " +c.Expires + " "); Response.Write ("Secure:" + c.Secure + " "); String[] s1 = c.Values.AllKeys; for (int j = 0; j < s1.Length; j++) { Response.Write("Value" + j + ": " + s1[j] + "<br>"); } } %>

Output
aa a1 a2 langpref ASP.NET_SessionId

Cookie: aa Expires: 1/1/0001 12:00:00 AM Secure:False Value0: Cookie: a1 Expires: 1/1/0001 12:00:00 AM Secure:False Value0: Cookie: a2 Expires: 1/1/0001 12:00:00 AM Secure:False Value0: Cookie: langpref Expires: 1/1/0001 12:00:00 AM Secure:False Value0: Cookie: ASP.NET_SessionId Expires: 1/1/0001 12:00:00 AM Secure:False Value0:

Just as there are many ways to skin a cat, there are also numerous ways of displaying a cookie. The HttpCookiecollection class has a member called AllKeys that returns an array of strings, which represent the names of the cookies or its keys. Thus, in one stroke, we can figure out all the names of the cookies.

After displaying the individual names of the Cookie in the 'for' loop, the same name is used in the indexer, to access the individual cookie object. The 'expires' property inexplicably, does not display the correct date and time. Further, the Values object must be used in place of the Value property, because a cookie can have multiple values. Thus, c.Values.AllKeys returns an array of strings. Since in the present case, every cookie has only a single value, the 'for' loop executes only once.

a.aspx <%@ language="C#" %> <% Response.Write(Request.FilePath); %>

Output /a.aspx

The property named FilePath returns the virtual path of the request. The output reflected is /aspx, because we are loading this file from the wwwroot sub-directory. If you run the file from the scripts sub-directory, the output will display /scripts/a.aspx

a.aspx <%@ language="C#" %> <% NameValueCollection c; c=Request.Headers; String[] s = c.AllKeys; for (int i = 0; i < s.Length; i++) { Response.Write("Key: " + s[i] + " "); String[] s1=c.GetValues(s[i]); for (int j = 0; j<s1.Length; j++) { Response.Write("Value " + j + ": " + s1[j] + "<br>"); } } %>

Output Key: Connection Value 0: Keep-Alive Key: Accept Value 0: */*

Key: Accept-Encoding Value 0: gzip, deflate Key: Accept-Language Value 0: en-us Key: Cookie Value 0: langpref=C#; ASP.NET_SessionId=abksbkrxdgjmmj45hasiffzx Key: Host Value 0: localhost Key: User-Agent Value 0: Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0; .NET CLR 1.0.2914)

The Headers property returns a NameValueCollection object that represents all the headers. The rules for handling headers are common for all headers. The rules are all in the form of name=value. The object c has an AllKeys property, which returns a list of keys. As before, we use a loop and call the function GetValues, which returns an array of strings when it is supplied with a key value. Most of the time, we only have a single value. Hence, our array s1 has a length of one.

a.aspx <%@ language="C#" %> <% NameValueCollection c; c=Request.Headers; String[] s = c.AllKeys; for (int i = 0; i < s.Length; i++) { Response.Write("Key: " + c[i] + " "); String s1=c.Get(s[i]); String s2=c.Get(i); Response.Write("Value " + s1 + " " + s2 + "<br>");

} %>

Output Key: Keep-Alive Value Keep-Alive Keep-Alive Key: */* Value */* */* Key: gzip, deflate Value gzip, deflate gzip, deflate Key: en-us Value en-us en-us Key: langpref=C#; ASP.NET_SessionId=abksbkrxdgjmmj45hasiffzx Value langpref=C#; ASP.NET_SessionId=abksbkrxdgjmmj45hasiffzx langpref=C#; ASP.NET_SessionId=abksbkrxdgjmmj45hasiffzx Key: localhost Value localhost localhost Key: Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0; .NET CLR 1.0.2914) Value Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0; .NET CLR 1.0.2914) Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0; .NET CLR 1.0.2914)

The output is the same as before, but it is easier to comprehend now, since a function called Get is used, which returns a single string value. Every value is displayed twice, because we have used both the forms of the Get function, i.e. passing it a string and then, passing it a number. It is the browser that sends these headers. You can easily verify this by inspecting the file z.txt, which has been created earlier.

Let us first create a simple aspx file that merely writes out the value of a property called HttpMethod.

a.aspx <%@ language="C#" %>

<% Response.Write(Request.HttpMethod); %>

a.html <html> <body> <form action=http://localhost/a.aspx METHOD=GET> <input type = text name = aa> <input type = text name = bb> <input type = submit value = click> </form> </body> </html> In the above HTML file, we have added an attribute called 'METHOD=GET' to the form tag. When we click on the 'click' button, browser screen loads on, with the address containing the action value of http://localhost/a.aspx, followed by the ? symbol and the name value pairs. The word GET is also displayed in the browser window.

Now, we make a small modification in the HTML file. We replace the words GET with POST. When we load the file, everything remains the same. When we click on the button, the browser now displays POST. Further, the URL contained in the address bar does not contain either the question mark or the name-value pairs.

The difference between a GET and POST method is that, in a POST, the data is transmitted as a separate packet, whereas, in a GET, it is sent as part of the URL. In Get, there is a limit to the amount of data that can be sent as part of the URL. Passwords and other important information must always be sent using the POST method and not the GET method.

a.aspx <%@ language="C#" %> <% Response.Write(Request.IsAuthenticated + "<br>"); Response.Write(Request.IsSecureConnection + "<br>"); %>

Output False False

We have neither authenticated our connection, nor have we been using a secure connection. A secure connection begins with 'https', instead of 'http'.

a.aspx <%@ language="C#" %> <% Response.Write(Request.Path); %>

Output /a.aspx

This property displays the virtual path of the current request.

a.aspx <%@ language="C#" %> <% Response.Write(Request.PhysicalApplicationPath); %>

Output c:\inetpub\wwwroot\

The Web Server can be installed anywhere on the hard disk. The default directory selected by IIS is C:\inetpub\wwwroot. As we have used the defaults, the property PhysicalApplicationPath reveals the same path. The PhysicalApplicationPath is called the home directory or the root directory of IIS. Whenever a file is to be referred to on the hard disk, this value is added to the filename. Further, the slash symbol /, which represents the virtual directory, finally gets converted into this physical path, while it is locating or sending files to the browser.

a.aspx <%@ language="C#" %> <% Response.Write(Request.PhysicalPath); %>

Output c:\inetpub\wwwroot\a.aspx

In this program, we go a step further and ask for the full path name or the physical filename of our aspx file.

For the next program, we write the following URL in the browser:

http://localhost/a.aspx?aa=hi&bb=bye&aa=no

a.aspx <%@ language="C#" %> <% NameValueCollection c=Request.QueryString; String[] s = c.AllKeys; for (int i = 0; i < s.Length; i++) { Response.Write(s[i] + " "); String[] s1 = c.GetValues(s[i]); for (int j = 0; j < s1.Length; j++) { Response.Write("Value " + j + ": " + s1[j] + " "); } Response.Write("<br>"); }

%>

Output aa Value 0: hi Value 1: no bb Value 0: bye

The QueryString property returns a NameValueCollection. The AllKeys property of this object returns only two keys, which is because we have repeated the parameter name aa twice. We are permitted to repeat names in HTML.

The 'for' loop is repeated twice for the two keys. The GetValues function returns an array consisting of two members for aa, which is because it contains two values i.e. 'hi' and 'no'. The second 'for' loop displays these values.

Working with ASP+ is a pleasure, since there is an inbuilt code for handling multiple values.

If we run the earlier HTML file with the method as Post, we shall not receive any output, because the environmental variable QueryString holds values only with the Get method.

a.aspx <%@ language="C#" %> <% Response.Write(Request.RawUrl); %>

Output

/a.aspx

The RawUrl displays the URL in its most primitive form.

a.aspx <%@ language="C#" %> <% NameValueCollection c; c=Request.ServerVariables; String [] s = c.AllKeys; for (int i = 0; i < s.Length; i++) { Response.Write(s[i] + "="); String [] s1 =c.GetValues(s[i]); for (int j = 0; j < s1.Length; j++) { Response.Write(s1[j] + " "); } Response.Write("<br>"); } %>

Output

ALL_HTTP=HTTP_CONNECTION:Keep-Alive HTTP_ACCEPT:*/* HTTP_ACCEPT_ENCODING:gzip, deflate HTTP_ACCEPT_LANGUAGE:en-us HTTP_COOKIE:langpref=C#; ASP.NET_SessionId=abksbkrxdgjmmj45hasiffzx HTTP_HOST:localhost HTTP_USER_AGENT:Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0; .NET CLR 1.0.2914) ALL_RAW=Connection: Keep-Alive Accept: */* Accept-Encoding: gzip, deflate AcceptLanguage: en-us Cookie: langpref=C#; ASP.NET_SessionId=abksbkrxdgjmmj45hasiffzx Host: localhost User-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0; .NET CLR 1.0.2914) APPL_MD_PATH=/LM/W3SVC/1/ROOT APPL_PHYSICAL_PATH=c:\inetpub\wwwroot\ CONTENT_LENGTH=0 CONTENT_TYPE= GATEWAY_INTERFACE=CGI/1.1 HTTPS=off INSTANCE_ID=1 INSTANCE_META_PATH=/LM/W3SVC/1 LOCAL_ADDR=127.0.0.1 PATH_INFO=/a.aspx PATH_TRANSLATED=c:\inetpub\wwwroot\a.aspx QUERY_STRING= REMOTE_ADDR=127.0.0.1 REMOTE_HOST=127.0.0.1 REQUEST_METHOD=GET SCRIPT_NAME=/a.aspx SERVER_NAME=localhost SERVER_PORT=80

SERVER_PORT_SECURE=0 SERVER_PROTOCOL=HTTP/1.1 SERVER_SOFTWARE=Microsoft-IIS/5.0 URL=/a.aspx HTTP_CONNECTION=Keep-Alive HTTP_ACCEPT=*/* HTTP_ACCEPT_ENCODING=gzip, deflate HTTP_ACCEPT_LANGUAGE=en-us HTTP_COOKIE=langpref=C#; ASP.NET_SessionId=abksbkrxdgjmmj45hasiffzx HTTP_HOST=localhost HTTP_USER_AGENT=Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0; .NET CLR 1.0.2914)

The server creates a large number of variables. They are too numerous to be displayed. Here, we are only displaying the variables that have values.

a.aspx <%@ language="C#" %> <% Uri o = Request.Url; Response.Write("URL Port: " + o.Port + "<br>"); Response.Write("URL Protocol: " + o.Scheme + "<br>"); Response.Write("URL Host: " + o.Host + "<br>"); Response.Write("URL PathAndQuery: " + o.PathAndQuery + "<br>");

Response.Write("URL Query: " + o.Query + "<br>"); %> Output URL Port: 80 URL Protocol: http URL Host: localhost URL PathAndQuery: /a.aspx?aa=hi&bb=bye URL Query: ?aa=hi&bb=bye

The Url property in the Request object, returns an HttpUrl object. This object has many properties, which break up the URL into different components. The port number is related to the protocol used.

Every packet on the Internet is tagged with a number that signifies the protocol that carries it. For e.g., the http protocol has the port no. 80, E-Mail read is 25, FTP is 21, etc. Thus, the Port shows a value of 80 because the URL that has been entered, starts with the syntax http:. Similarly, the protocol used is http.

Host is the name of our computer. PathAndQuery contains the name of the requested file along with the querystring.

a.aspx <%@ language="C#" %> <% Response.Write(Request.UserAgent); %>

Output Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0; .NET CLR 1.0.2914)

A user agent is another name for the browser. The internal name for Netscape was Mozilla. So, IE initially referred to itself by the same name. Many of the websites performed a check on the browser that was requesting for the file. If it matched IE, the page was not sent across. However, today it is IE that has eventually won the browser war. We shall talk about it later, since it is too long an account to be related to you right away.

a.aspx <%@ language="C#" %> <% Response.Write(Request.UserHostAddress); %>

Output 127.0.0.1

Every computer on the Internet is known by a number, which is technically called an IP address. It is of a long data type. This implies that it consists 4 numbers, each ranging from 0 to 255. These numbers are separated by dots. This format is known as the decimal dotted notation.

As every machine is known as localhost and it is given an IP address 127.0.0.1. Thus, when we write localhost in the IE address bar, it gets converted to 127.0.0.1.

a.aspx <%@ language="C#" %> <% String[] s = Request.UserLanguages; for (int i = 0; i < s.Length; i++) { Response.Write(s[i] + "<br>"); } %>

Output en-us

The property UserLanguages returns the languages that the browser supports. In our case, the browser supports the English language, or more precisely, 'en-us', which stands for American English and not for British English.

a.aspx <%@ language="C#" %> <% String s = Request.MapPath("/quickstart"); Response.Write(s); %>

Output C:\Program Files\Microsoft.Net\FrameworkSDK\Samples\QuickStart

When the .Net sdk installs itself, it creates virtual directories in IIS. Thus, when we write http://localhost/quickstart, it converts the virtual directory named quickstart to the path displayed above. The MapPath function in the Request Object, converts a virtual directory to an absolute path on your hard disk.

The Response Object

a.aspx <%@ language="C#" %> <% Response.Write(Response.BufferOutput.ToString()); %>

Output True

The first property we delve upon in the HttpResponse class is BufferOutput. This property returns a logical value of either a True or False. In doing so, it keeps us posted on whether the output sent to the browser will be buffered or not.

While using the Write function from the Response class, the data doesn't have to be sent to the browser at once, as this will result in too many small packets being sent across. Therefore, on grounds of efficiency, the text is collected and sent only when a critical mass is reached. By

default, the buffering option is on. Unless you are equipped with a valid reason, you should not turn it off.

a.aspx <%@ language="C#" %> <% Response.ContentType = "Text/plain"; Response.Write("<b>hi"); %> Output <b> hi

The web server sends a series of headers to the browser. It then follows it up with the actual content. As explained to you earlier, the most important header is Content-Type. If we avoid creating this header in our file, IIS defaults to the type value as text/html. Here, we have changed the Content-Type property in Response to text/plain. Thus, the <b> tag is treated as text and not a HTML tag.

a.aspx <%@ language="C#" %> <% Response.Write(Response.IsClientConnected.ToString()); %>

Output

True

This function simply returns true or false, depending on whether the client is connected or not. This is one check that is to be performed before we send the file to the browser.

a.aspx <%@ language="C#" %> <% System.IO.FileStream f; long s; f = new System.IO.FileStream("c:\\inetpub\\wwwroot\\a.html", System.IO.FileMode.Open); byte[] b = new byte[(int)f.Length]; f.Read(b, 0, (int)f.Length); Response.Write("<b>Start a.spx</b>"); Response.BinaryWrite(b); Response.Write("<b>End a.spx</b>"); %>

Output

In the System.IO namespace, there is a class called FileStream, which has members that can handle file activity. While creating an object 'f' in the constructor, we state the full path of the file and also the mode in which the file is to be opened. We then allocate a byte array, depending upon the size of the file. The file size is acquired using the property called Length in the FileStream object.

The read function is employed next, to read the file into the byte buffer. Therefore, the first parameter specified is 'b'. The second parameter is the starting position in the file, the position from where the reading should begin. And the last parameter is the number of bytes to be read, from thereon. As we want to read from the beginning of the file, and we also want to read the entire file in one go, we specify zero as the second parameter and the length of the file is the third parameter.

Now that the file is available in the byte array, the BinaryWriter function is used to add these bytes into a stream and subsequently, send them to the browser. As the browser receives an HTML file, it parses through the file and displays the textboxes. The Write functions before and after the BinaryWrite, work as normal.

a.aspx <%@ language="C#" %> <% Response.Write("<b>Start"); Response.ContentType = "Text/plain"; Response.Clear(); Response.Write("<b>End"); %>

Output <b>End

The Response.ContentType function initially changes the Content-Type header after writing Start in bold. Thereafter, the Clear function in Response, clears all HTML output, since its job is to clear the Buffer. So, the output displayed in the browser is that of the final Write. Even though the documentation states that headers are reset, it does not happen in the case of our copy.

a.aspx <%@ language="C#" %> <% Response.Write("<b>Start"); Response.ContentType = "Text/plain"; Response.ClearHeaders(); Response.Write("<b>End"); %>

Output StartEnd

However, the function ClearHeaders, resets all the headers created in the scriptlet. Thus, the default Content-type header is sent across, before the contents in the buffer are handed over to the browser. As a result, we see StartEnd displayed in bold.

a.aspx <%@ language="C#" %> <% Response.Write("<b>Start");

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

Output Start

The End function states 'enough is enough', and it sends across the HTML file and the headers immediately. Thereafter, it closes the connection. Thus, all future output to be sent to the browser, is conveniently ignored.

a.aspx <%@ language="C#" %> <% Response.Write("<b>Start"); Response.Redirect("a1.aspx"); Response.Write("<b>End"); %>

a1.aspx <%@ language="C#" %> <% Response.Write("<b>a1.aspx");

%>

Output a1.aspx

The redirect function merely stops executing the current file, a.aspx, and starts executing the file to which it has been redirected. Thus, in case of a Redirect function, any Write function that follows the Redirect command, is completely ignored. Also, if you observe the address bar, the URL does not change in the browser. It remaines as a.aspx.

a.aspx <%@ language="C#" %> <% Response.Write("a.aspx <br>"); Response.WriteFile("a.html"); %>

The output is similar to one of the earlier programs. The WriteFile function writes the file contents into the http stream and sends it to the browser.

Cookies Revisited

a.aspx <%@ language="C#" %> <%

HttpCookie c = new HttpCookie("vijay","mukhi"); Response.AppendCookie(c); %>

One of the simplest things to do in ASP+, is to send a cookie across. Object 'c' of type HttpCookie is created by calling the constructor with the name of the cookie vijay, having a value of mukhi.

Since the cookie option has been set to prompt in the browser, you will see Alert box for the cookie. Please note that the constructor does not send the cookie across. It is the function AppendCookie that does so.

a.aspx <%@ language="C#" %> <% HttpCookie c = new HttpCookie("vijay","mukhi"); Response.AppendCookie(c); HttpCookie c1 = new HttpCookie("vijay1","mukhi1"); Response.AppendCookie(c1); c = new HttpCookie("vijay1","mukhi2"); Response.AppendCookie(c); %>

By default, the browser sends a cookie for the ASP+ session. In the above program, even though three cookies have been sent, we see only two boxes, since the second and the third cookies share the same name. Thus, the cookie with the names of vijay1 and value mukhi2 is not sent

across separately. The point to be considered here is that you are free to send as many cookies as you like.

a.aspx <%@ language="C#" %> <% HttpCookie c = new HttpCookie("vijay"); c.Values.Add("sonal","wife"); c.Values.Add("zzz","yyy"); Response.AppendCookie(c); %>

Output Value in cookie dialog box sonal=wife&zzz=yyy

a1.aspx <%@ language="C#" %> <% HttpCookieCollection cc; HttpCookie c; cc = Request.Cookies; int i = cc.Count; for (int k = 0; k < i; k++)

{ c = cc[k]; Response.Write("Cookie: " + c.Name + "<br>"); String[] s1 = c.Values.AllKeys; for (int j = 0; j < s1.Length; j++) { Response.Write("Value" + j + ": " + s1[j] + "<br>"); } } %>

Output Cookie: vijay Value0: sonal Value1: zzz Cookie: ASP.NET_SessionId Value0:

Cookies can be made as complex as we like. We create one cookie named vijay, and then use the Add function in the Values property of the cookie, to initialize the subnames and values for the cookie.

The cookie is transferred as one entity, with the key-value pairs within it. The different pairs are separated by a & sign. a1.aspx simply displays all the cookies. For a cookie named vijay, the last 'for' loop gets executed twice as it holds two values.

a1.aspx <%@ language="C#" %> <% HttpCookieCollection cc; HttpCookie c; cc = Request.Cookies; c = cc["vijay"]; Response.Write("Cookie: " + c.Name + "<br>"); Response.Write(c.Values["sonal"] + "<br>"); Response.Write(c.Values["zzz"]); %>

Output Cookie: vijay wife yyy

Rewrite a1.aspx with the code given above. This program first fetches the cookie named vijay and stores it in 'c'. The Values property, which returns a NameValueCollection, has an indexer that is supplied with the name of the sub key. Consequently, this indexer returns the value of the sub key.

a.aspx <html>

Sonal Mukhi <a href="a1.aspx">Click here</a> </html>

a1.aspx <html> <script language="C#" runat="server"> void Page_Load(Object sender, EventArgs E) { if (!IsPostBack) { Response.Write(Request.Headers["Referer"]); ViewState["zzz"] = Request.Headers["Referer"]; } } void abc(Object sender, EventArgs E) { Response.Redirect(ViewState["zzz"].ToString()); } </script> <form runat="server"> <input type="submit" OnServerClick="abc" Value="Click" runat="server"/> </form> </body> </html>

Output Sonal Mukhi Click here

http://localhost/a.aspx

The file a.aspx has an anchor tag <a href> that takes us to page a1.aspx, whenever we click on it.

The ASP+ program a1.aspx displays a button with the label 'click'. Prior to this, the function Page_Load is called. This function uses the Request object to access the indexer called Header. The Header is passed a string called Referer, which informs it about the file of its origin. As a.aspx was responsible for leading us to a1.aspx from a.aspx, the URL displays the file name a.aspx.

The WebServer normally keeps a log of the files that lead a user to its site. This value is then stored in a state variable called zzz. As we are now aware of the site that brought us to the current one, by clicking on the button, we can Redirect ourselves to the page we came from.

Thus, the above code is generic and goes into a circular loop.

We shall now consider a practical example to demonstrate the utility of cookies.

a.aspx <html>

<script language="C#" runat="server"> void Page_Load(Object sender, EventArgs E) { if (Request.Cookies["vijay"] == null) { HttpCookie c = new HttpCookie("vijay"); c.Values.Add("Size","8pt"); c.Values.Add("Name","Verdana"); Response.AppendCookie(c); } } public String abc(String k) { HttpCookie c = Request.Cookies["vijay"]; if (c != null) { if ( k == "FontSize") return c.Values["Size"]; else return c.Values["Name"]; } return ""; }

</script> <style> body { font: <%=abc("FontSize")%> <%=abc("FontName")%> } </style> Sonal Mukhi <a href="a1.aspx">Click here</a> </body> </html>

a1.aspx <html> <script language="C#" runat="server"> void Page_Load(Object sender, EventArgs E) { if (!IsPostBack) ViewState["zzz"] = Request.Headers["Referer"]; } void abc(Object sender, EventArgs E) { HttpCookie c = new HttpCookie("vijay");

c.Values.Add("Size",s1.Value); c.Values.Add("Name",s2.Value); Response.AppendCookie(c); Response.Redirect(ViewState["zzz"].ToString()); } </script> <form runat="server"> <select id="s1" runat="server"> <option>8pt</option> <option>10pt</option> <option>12pt</option> <option>44pt</option> </select> <select id="s2" runat="server"> <option>verdana</option> <option>tahoma</option> <option>arial</option> <option>times</option> </select> <input type="submit" OnServerClick="abc" Value="Click" runat="server"/> </form> </body> </html>

Output Sonal Mukhi Click here

Sonal Mukhi Click here

The above example displays the text 'Sonal Mukhi' and a hyperlink labelled as 'Click Here'. If we click on the hyper link, we are transported to a new page called a1.aspx. This page contains two dropdown listboxes and a button. The first listbox displays the font point size and the second offers the font face name. By default, the values in these text boxes are 8pt for the font size and Verdana for the font face name, respectively. At this stage, if you modify the font size to 12 and the font face name to Tahoma, and then click on the button, you will be taken back to the original file named a.aspx. In this file, the text and the Hyperlink will now be displayed in the newly selected font and size. Having unravelled the output, let us now shift the spot-light to the internal working of this program.

The Page_Load function in a.aspx verifies the existence of a cookie named 'vijay'. Since this page has just been loaded afresh, the cookie is not available at the moment. This condition results in true only when the client returns the cookie sent by the server, while transmitting the user data.

Since the Cookies collection returns a null, a cookie named 'vijay' is created with two sub keys of Size and Name. These sub keys are given the values of 8 pt and Verdana, respectively, which correspond to the font size and the font face name. This cookie is sent over along with the page generated by a.aspx.

The code enclosed within the style and /style tags calls the function abc, to adjust the font size and name as specified by the cookie. Since 'c' has not been currently initialized, the current text is not displayed in the font and the size specified in the cookie. Depending upon the value of the

parameter 'k', the value of the key Size or Name, as specified in the Cookie 'Vijay', will be put into service. Thus, the keys in the cookie named 'Vijay' will decide the format of the text displayed on the page.

If we click on the hyper-link, it will result in a call to a1.aspx. By using the Referer parameter in the Header's Indexer, the name a.aspx of the aspx file is stored in the state variable named zzz. When the user clicks on the button, the font name and font size selected by the user, get stored in the listbox ids of s1 and s2 respectively.

This results in a call to the code in the function abc, where a cookie called 'Vijay' is created. Its sub keys are initialized to values obtained from the listbox. This cookie is sent over. Thereafter, using the state variable zzz, we revert back to a.aspx.

In the file a.aspx, since the cookie 'vijay' now contains specific values, we use these values to set the font size and the name. As a consequence, the text is displayed in accordance with the values selected by the user in the listbox, which are now accessible from the cookie. Thus, we can conclude that the system takes into account the choices that we make, and each time we load the file a.aspx, the text displayed on the page is formatted as per the pre-selected font face and size.

This is the mechanism to display a customized web page. Since by default the page does not retain these values when the browser is closed, the 'expires' attribute has to be initialized to a value specified in terms of time or a date. This indicates the duration for which the cookie is to remain alive. Alternatively, we can store such a value in DateTime.MaxValue, so that the cookie never expires.

You can verify the retention of pre-set values between different browser sessions by closing the browser and re-starting it. The browser would have retained the settings specified by you earlier.

Cookies are employed to enable data to persist between the client and the server. A cookie is usually stored on the Clients hard disk. In the case of Netscape Navigator, a file called cookies.txt is created by the browser to store the cookies. The minimum size per cookie is 4096 bytes.

State Management with Global.asax

a.aspx <html> <script language="C#" runat="server"> int p1=0; void Page_Load(Object sender, EventArgs e) { p1++; Response.Write("Page_Load() " + p1.ToString() + "<br>"); } void abc(Object sender, EventArgs e) { Session.Abandon(); //Response.Redirect("a.aspx"); } </script> <body> <form runat="server"> <input type="submit" Value="Refresh" runat="server"/> <input type="submit" OnServerClick="abc" Value="End Session" runat="server"/> </form> </body>

</html>

global.asax <script language="C#" runat="server"> int r1 =0, r2=0, s1=0,s2=0,a1=0,a2=0; void Application_Start(Object sender, EventArgs E) { a1++; } void Application_End(Object sender, EventArgs E) { a2++; } void Session_Start(Object sender, EventArgs E) { s1++; Response.Write("Session_Start " + s1.ToString()+ "<br>"); } void Session_End(Object sender, EventArgs E) { s2++; Response.Write("Session_End " + s2.ToString()+ "<br>"); }

void Application_BeginRequest (Object sender, EventArgs E) { r1++; Response.Write("Request_Start " + r1.ToString()+ " Application start " + a1.ToString() + "<br>"); } void Application_EndRequest (Object sender, EventArgs E) { r2++; Response.Write("Request_End "+ r2.ToString()+ " Application end " + a2.ToString() + "<br>"); } </script>

Output Request_Start 1 Application start 0 Session_Start 1 Page_Load() 1

Request_End 1 Application end 0

In the above program, we have created two files in the directory c:\inetpub\wwwroot. The file a.aspx can be christened by any name of our choice, but the second file must be named as

global.asax. Prior to loading a.aspx in the browser, ASP.Net checks for the presence of a file named global.asax. If it exists in the current directory, a DLL is created with a class called global.asax. This class holds all the code entered in the asax file. The class resembles the following:

public class global_asax : System.Web.HttpApplication , System.Web.SessionState.IRequiresSessionState {

We discovered this by consciously committing an error in C#.

There are six functions with pre-defined names that are added to global.asax. They are:

Application_Start Application_End Session_Start Session_End Application_BeginRequest Application_EndRequest

We have also created six different variables in this special file and initialized all of them to 0. Each of these six functions increments one variable each by a value of 1. This signifies the frequency with which the functions get called. A similar action is repeated in the Page_Load function within the aspx file.

When we load the file a.aspx, it calls some functions from the file global.asax. But, each of them gets called only once. The order is as follows: Application_BeginRequest, Session_Start, Page_Load.

Thereafter, the buttons in the aspx file are displayed. Lastly, Application_EndRequest is displayed on the screen.

Please note that there is no Write function in Application_Start and Application_End, because the Response object is neither available, nor has it been created so far. By adding a function, an error is generated, that gives us information about the global_asax class in the dll.

When we click on Refresh, no code gets called, because it simply results in a post back to the server.

Output Request_Start 2 Application start 0 Page_Load() 1

Request_End 2 Application end 0

The order of calling the various functions is as follows:

First, function Application_BeginRequest with variable r1 as 2, Then, function Page_Load with variable p1 as 1 Finally, function Request_End with variable r2 as 2.

The output proves that the Page_Load function is not called on clicking on the refresh button. Also, no new session is created. Hence, the Session_Start function is not called.

Now, if you click repeatedly on the 'End Session' button, you will see the following output:

Output Request_Start 10 Application start 0 Session_Start 8 Page_Load() 1

Request_End 10 Application end 0

The Session_Start function is called once and the Request_Start is called twice.

If we comment out the Response.Redirect function in the file a.aspx, we obtain the same number of functions as before, but the Request functions get called only once. What we are trying to convey here is that, generous amount of code gets called before and after Page_Load. We can take advantage of these functions and the frequency of their occurrence to execute certain code at specified intervals.

For the moment, the code in global.asax does not deal with User Interface calls. These calls handle a much higher level of event handling, where it deals with application events. We can create our own events in the form of Application_EventName(signature).

We would also like to clarify that the file, global.asax, need not be restricted to the wwwroot sub-directory alone. The only salient feature to be kept in mind is that it should be placed in the same sub-directory as the aspx file.

The .Net framework creates a class derived from HttpApplication and places our code in it. Any modifications made to these files automatically calls for recompiling of the class. We cannot use a direct URL request to fetch the file, since we are not permitted to view the code written in it.

If you consider yourself to be a maverick, you may attempt to do so. But beware, you will then have to deal with the error number 404.

a.aspx <html> <script language="C#" runat="server"> void abc(Object sender, EventArgs e) { throw new Exception(); } </script> <body> <form runat="server"> <input type="submit" OnServerClick="abc" Value="Exception" runat="server"/> </form> </body> </html>

Output

In the above program, An exception of type System.Exception was thrown. The above program is extremely simple. It displays a button labelled 'Exception'. If we click on this button, an exception is thrown.

An exception is a synonym for an error. The class, when derived from exception, becomes an exception class. Functions in today's world throw exceptions rather than errors. We get an ugly yellow coloured screen containing the exception message.

Now, let us endeavour to execute our own code, whenever an exception is thrown.

We first create a file called web.config in c:\inetpub\wwwroot as follows:

web.config <configuration> <system.web> <customErrors mode="On" defaultRedirect="a.htm" /> </system.web> </configuration>

a.htm hi

This file, which is used to customize the default workings of ASP.Net, is read each time by the ASP+ framework. By giving the above tags in the file, we can direct the framework to load a file named a.htm, whenever an error occurs. The URL, however, changes to the following in the browser address bar:

http://localhost/a.htm?aspxerrorpath=/a.aspx

a.aspx <%@ Import Namespace="System.Data" %> <html> <script language="C#" runat="server"> void Page_Load(Object Src, EventArgs E ) { DataView s = (DataView)(Application["sss"]); s1.InnerHtml = s.Table.TableName; l.DataSource = s; l.DataBind(); } </script> <body> <span runat="server" id="s1"/></font> <ASP:DataGrid id="l" runat="server"/> </body> </html>

global.asax <%@ Import Namespace="System.Data" %>

<%@ Import Namespace="System.IO" %> <script language="C#" runat="server"> void Application_Start(Object sender, EventArgs e) { DataSet d = new DataSet(); FileStream f = new FileStream(Server.MapPath("s.xml"),FileMode.Open,FileAccess.Read); StreamReader r = new StreamReader(f); d.ReadXml(r); f.Close(); DataView v = new DataView(d.Tables[0]); Application["sss"] = v; } </script> s.xml <root> <schema id="DocumentElement" targetNamespace="" xmlns="http://www.w3.org/2001/XMLSchema" xmlns:xdo="urn:schemas-microsoft-com:xmlxdo" xdo:DataSetName="DocumentElement"> <element name="Products"> <complexType> <all> <element name="ProductID" type="int"></element> <element name="CategoryID" minOccurs="0" type="int"></element> </all>

</complexType> </element> </schema> <DocumentElement> <Products> <ProductID>2002</ProductID> <CategoryID>2</CategoryID> </Products> <Products> <ProductID>2003</ProductID> <CategoryID>2</CategoryID> </Products> </DocumentElement> </root>

Output Products

In the file a.aspx, we begin with the assumption that a DataView object has already been created. Then, we initialize a span member named InnerHtml to a Table name that is picked up from the DataView.

This explains the display of Products in the browser window. Then, the DataSource property of the DataGrid named l, is initialized to the DataView object named 's'. Finally, the function DataBind display the records in a Tabular format. Now, let us cover up the loopholes in the explanation of the above program.

In the global.asax file, we have added adequate amount of code in the Application_Start function. A DataSet object named 'd' is created to hold the data. Also, a FileStream object named 'f' is given a reference to an XML file named s.xml, which is opened for reading purpose only. The file s.xml resides in the same directory. The StreamReader object named 'r' is given the FileStream parameter in its constructor, to enable it to read this file. d.Readxml will finally read the contents of the xml file in its dataset. We are not going into the explanation of s.xml, since it remains the same as before.

After closing the file, a DataView object 'v' is created. Application variables are similar to State variables, in the sense that, they are valid only while the application is on. The Application is an indexer. Hence, we provide a string named 'sss' to hold the DataView object. The variable 'sss' is now an Application variable.

The Application variable sss, containing the DataView object, is used in the Page_Load function. It supplies the data contained in the DataSet. The functions Page_Load and Application_Start are called only once, i.e. when the page is initially loaded. Both perform one-time actions. Thus, all resource intensive actions, such as, initializing the DataView, which is a one-time effort, are placed in this function.

There can always be a situation where multiple threads would like to access both, an application and its objects, concurrently. So, the data that does not change very often, must be stored with an Application scope. Data that needs to be initialized just once and then it is required to be only read, is an ideal example of such data.

In the above example, only the first request is resource intensive, and will incur a performance overhead while creating the DataView. All the other requests will be executed at lightning speed.

Sessions

a.aspx <html> <script language="C#" runat="server"> String abc(String k) { return Session[k].ToString(); } </script> <style> body { font: <%=abc("Size")%> <%=abc("Name")%> } </style> Sonal Mukhi <a href="a1.aspx">Click here</a> </body> </html>

a1.aspx <html> <script language="C#" runat="server">

void Page_Load(Object sender, EventArgs E) { if (!Page.IsPostBack) ViewState["zzz"] = Request.Headers["Referer"]; } void abc(Object sender, EventArgs E) { Session["Size"] = s1.Value; Session["Name"] = s2.Value; Response.Redirect(ViewState["zzz"].ToString()); } </script> <body> <form runat="server"> <select id="s1" runat="server"> <option>8pt</option> <option>10pt</option> <option>12pt</option> <option>44pt</option> </select> <select id="s2" runat="server"> <option>verdana</option> <option>tahoma</option>

<option>arial</option> <option>times</option> </select> <input type="submit" OnServerClick="abc" Value="Click" runat="server"/> </form> </body> </html>

global.asax <script language="C#" runat="server"> void Session_Start(Object sender, EventArgs e) { Session["Size"] = "8pt"; Session["Name"] = "verdana"; } </script>

The above example conducts itself in the same manner as the earlier Cookies' example. However, this one is much simpler. It is next to impossible for the user to detect the method used to obtain the above output by merely looking at the end result.

Let us start with the file named a.aspx.

The code in a.aspx remains the same, except for modifications made in the function abc. The Session indexer is used to retrieve the value of a variable that is created in the global.asax file. In

the global.asax file, we have created two variables named Size and Name to store the font size and the font name respectively. You may have noticed that this code is placed in the function named Session_Start.

When we click on the button in the file a1.aspx, the Sessions variables get re-initialized with the values selected in the listboxes. Thereafter, there is a redirection to the original page named a.aspx.

If we replace Cookies with Session, the entire picture would be more transparent and lucid.

We can configure the state of the session object by using the sessionstate section in the file named web.config. Adding the line <sessionState timeout="40" /> will increase the default timeout from 20 minutes to 40 minutes. The timeout parameter ends the session either in 40 minutes or when you close the browser, whichever occurs first.

We now add the following line to the file named web.config

web.config <configuration> <system.web> <sessionState cookieless="true" /> </system.web> </configuration>

We have selected the cookie option named 'prompt', and in config.web, we have disallowed the use of a cookie to keep track of sessions. Thus, the web server has no choice but to use the URL to keep track of sessions. As a result, the new URL looks like the following:

http://localhost/(ybp3byicimzjix3s0veyjb55)/a.aspx

This method is termed as URL rewriting.

ViewState

The illustration given below may be a large program, but it is deceptively simple to understand.

a.aspx <html> <script language="C#" runat="server"> void Page_Load(Object Src, EventArgs E ) { if (!IsPostBack) ViewState["zzz"] = 0; } void a1(Object Src, EventArgs E ) { String pid = "P" + ViewState["zzz"].ToString(); ViewState["zzz"] = (int)ViewState["zzz"] + 1; String Id = "P" + ViewState["zzz"].ToString(); Panel p = (Panel)FindControl(Id); p.Visible=true;

p = (Panel)FindControl(pid); p.Visible=false; } void a2(Object Src, EventArgs E ) { String Id = "P" + ViewState["zzz"].ToString(); ViewState["zzz"] = (int)ViewState["zzz"] - 1; String pid = "P" + ViewState["zzz"].ToString(); Panel p = (Panel)FindControl(Id); p.Visible=false; p = (Panel)FindControl(pid); p.Visible=true; } void a3(Object Src, EventArgs E ) { String s = "P" + ViewState["zzz"].ToString(); Panel p = (Panel)FindControl(s); p.Visible=false; l.Text += "Name: " + na.Value + "<br>"; l.Text += "Address: " + a.Value + "<br>"; l.Text += "Card : " + n.Value + "<br>"; } </script>

<body"> <form runat="server"> <ASP:Panel id="P0" Visible="true" runat="server"> Name: <input id="na" type="text" runat="server"> <br> <input type="submit" Value=" Next >> " OnServerClick="a1" runat="server"> </ASP:Panel> <ASP:Panel id="P1" Visible="false" runat="server"> Address: <input id="a" type="text" runat="server"> <input type="submit" Value=" << Back " OnServerClick="a2" runat="server"> <input type="submit" Value=" Next >> " OnServerClick="a1" runat="server"> </ASP:Panel> <ASP:Panel id="P2" Visible="false" runat="server"> Card Number: <input id="n" type="text" runat="server"/> <input type="submit" Value=" << Back " OnServerClick="a2" runat="server"> <input type="submit" Value=" Finish " OnServerClick="a3" runat="server"> </ASP:Panel> </form> <asp:Label id="l" runat="server"/> </body> </html>

Output

We start our explanation with the code following the script tag, where we have three predefined Panel controls having the ids P0, P1 and P2. A Panel tag is simply a container for other HTML controls.

The Visible property for the first panel is set to true, whereas, for the other two, it is set to false. Thus, only the first panel P0 is displayed, and not the others.

The first panel contains a TextBox called 'na' and a button of type submit and label 'Next >>', which calls the function a1 when it is clicked.

The Page_Load function creates a ViewState variable named zzz and assigns it a value of 0. In a1, pid is assigned a value after concatenating "P" to the string value returned by ViewState["zzz"]. The statement ViewState["zzz"] = (int)ViewState["zzz"] + 1; increases the value by 1, thereby, making it 1.

A new string is then created with this new value of zzz. Thus, the value in the variable id becomes P1. The function FindControl, when supplied with the name of the control, returns a control. We cast it to a Panel, because we want to store this value in a Panel object named 'p'. The Panel object 'p' currently represents the hidden Panel P1.

We change the visible property of p, i.e. Panel P1, to true. As a result, the second panel is displayed on the screen. Subsequently, we use the same function named FindControl to find the Panel P0 and to change its Visible property to false. Thus, the only panel that is displayed at this stage is P1.

The second panel contains one textbox and two buttons. The button labeled 'Next >>' calls the function a1, whereas, the one labeled '<< Back' calls the function a2. The function a1 increments the value of zzz by 1, thereby, taking us to the next panel. On the other hand the function a2 decreases the value of zzz by 1, thereby, taking us to the previous panel. Accordingly, the current panel is hidden and the new panel is made visible.

In the last panel P3, the function a3 gets called by the button labeled 'Finish'. This function simply displays the values of the textboxes in the label field.

The user is given the impression that he is moving from one page to the other, but in reality, a single aspx file is executing certain sections of its code.

The property named ViewState is an instance of the StateBag class, which gives us a dictionary like interface. It stores objects associated with a key. Create the b.cs file in the c:\inetpub\wwwroot\bin sub directory.

b.cs using System.Web; namespace nnn { public class zzz : IHttpHandler { public void ProcessRequest(HttpContext c) {

c.Response.Write("Hell"); } public bool IsReusable { get { return true; } } } }

Compile b.cs as >csc /target:library /out:c.dll b.cs /R:system.web.dll

Create a file by the name of web.config in c:\inetpub\wwwroot to appear as depicted below:

web.config <configuration> <system.web> <httpHandlers> <add verb="*" path="a1.aspx" type="nnn.zzz,c" /> </httpHandlers> </system.web> </configuration>

Now, load the following URL in the browser http://localhost/a1.aspx

Output Hell

We first create a simple program named b.cs in the c:\inetpub\wwwroot\bin sub-directory. The class zzz in this file is derived from the interface IhttpHandler. It contains only two functions named ProcessRequest and IsReusable.

The IsReusable function is called to find out whether the same instance of the class can be recycled and used for another request, or if a fresh instance of the object needs to be created. Since the function returns true, the same object is used.

The ProcessRequest function creates the HTML output that is to be sent across to the browser. It accepts an object 'c' of type HttpContext as a parameter. This object has a function called Write, which helps the browser in writing output to the screen. Hence, we see 'Hell' displayed in the browser window.

What if we want to call our own function, instead of the ones supplied by IIS, when we are working on certain files?

To synchronously process HTTP web requests, the first requirement is that, the class must derive from IHttpHandler. This interface must be implemented, because it defines a contract and allows custom URL execution.

ASP.Net provides us with a low-level request and response API (a set of rules), which uses classes in order to service incoming requests. Thus, the above program is called a handler. Handlers are used when we want to customize certain features if we are not satisfied with the methods adopted by the framework that handles web requests.

The interface IHttpHandlerFactory decides on the class that will handle the http request. ASP.Net is shipped with three factory classes that handle requests. These are:

PageHandlerFactory RestrictedResourceFactory WebServiceHandlerFactory

We can either use any one of these three classes or create our own set of classes. If we create our own classes, we have to register them with the framework and handle the resolution issues. To change the default behaviour in the .Net world, code has to be placed in the config.web file. This is a plain and simple text file, which follows the rules of XML. This file has to be placed in the inetpub\wwwroot sub-directory or the directory of your application.

We can place our options within a tag called <configuration>. Following this, we have to initially place a tag called system.web which will contain another tag called <httpHandlers>. This tag accepts the name of a file or a file pattern. This pattern calls our handler when the value assigned to the property called path, is invoked. HttpHandler also requires the type attribute containing the namespace name and the class to handle the request. The name of the dll is also to be specified with the type. Thus, we use a comma as a separator, and then give 'c'. The c.dll must be present in the bin sub-directory. These settings are inherited by sub-directories also, implying that the sub-directories are also checked for controls, handlers etc.

Each time we request for a file named a1.aspx, the request for this particular file is not processed by the web server. Instead, it is handed over to our class named zzz. The class zzz then decides on the data to be sent over, under the file name of a1.aspx

Thus, handlers and factories are the backbone of the framework, because we are at liberty to decide on how the HTTP request should be handled. The factory picks up the request and decides on the handler that is to be called. These handlers are available in the web.config file. The code for the handlers normally resides in the bin sub-directory. Since the file is placed in the

default root directory, it is picked up by default, hence we request you to delete this file after having tried the example.

Tracing

a.aspx <%@ Page Trace="true" language="C#"%> hi <% Response.Write("bye"); %>

Output hi bye

Request Details
dufldc55vabqbd45xof13m55 Session Id: Request Type: GET 200 Time of Request: 9/26/2001 6:15:55 PM Status Code: Request Encoding: Unicode (UTF-8) Response Encoding: Unicode (UTF-8)

Trace Information
Category aspx.page aspx.page aspx.page aspx.page aspx.page aspx.page aspx.page aspx.page Message Begin Init End Init Begin PreRender End PreRender Begin SaveViewState End SaveViewState Begin Render End Render From First(s) 0.000184 0.000928 0.001095 0.001462 0.001617 0.001757 0.002250 From Last(s) 0.000184 0.000744 0.000168 0.000367 0.000154 0.000141 0.000493

Control Tree
Control Render Size Bytes (including Viewstate Size Bytes (excluding Type Id children) children) __PAGE _ASP.a_aspx9 0

Cookies Collection

Name ASP.NET_SessionId

Value dufldc55vabqbd45xof13m55

Size 42

Headers Collection
Name Connection Accept AcceptEncoding AcceptLanguage Host User-Agent Value Keep-Alive image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.mspowerpoint, application/vnd.ms-excel, application/msword, */* gzip, deflate en-us 127.0.0.1 Mozilla/4.0 (compatible; MSIE 6.0b; Windows NT 5.0; .NET CLR 1.0.2914) Name Value HTTP_CONNECTION:Keep-Alive HTTP_ACCEPT:image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, */* HTTP_ACCEPT_ENCODING:gzip, deflate HTTP_ACCEPT_LANGUAGE:en-us HTTP_HOST:127.0.0.1 HTTP_USER_AGENT:Mozilla/4.0 (compatible; MSIE 6.0b; Windows NT 5.0; .NET CLR 1.0.2914) Connection: Keep-Alive Accept: image/gif, image/xxbitmap, image/jpeg, image/pjpeg, application/vnd.mspowerpoint, application/vnd.ms-excel, application/msword, */* Accept-Encoding: gzip, deflate Accept-Language: en-us Host: 127.0.0.1 User-Agent: Mozilla/4.0 (compatible; MSIE 6.0b; Windows NT 5.0; .NET CLR 1.0.2914) /LM/W3SVC/1/ROOT c:\inetpub\wwwroot\

Server Variables

ALL_HTTP

ALL_RAW

APPL_MD_PATH APPL_PHYSICAL_PATH AUTH_TYPE AUTH_USER AUTH_PASSWORD LOGON_USER REMOTE_USER CERT_COOKIE CERT_FLAGS CERT_ISSUER CERT_KEYSIZE CERT_SECRETKEYSIZE CERT_SERIALNUMBER CERT_SERVER_ISSUER CERT_SERVER_SUBJECT CERT_SUBJECT

CONTENT_LENGTH CONTENT_TYPE GATEWAY_INTERFACE HTTPS HTTPS_KEYSIZE HTTPS_SECRETKEYSIZE HTTPS_SERVER_ISSUER HTTPS_SERVER_SUBJECT INSTANCE_ID INSTANCE_META_PATH LOCAL_ADDR PATH_INFO PATH_TRANSLATED QUERY_STRING REMOTE_ADDR REMOTE_HOST REQUEST_METHOD SCRIPT_NAME SERVER_NAME SERVER_PORT SERVER_PORT_SECURE SERVER_PROTOCOL SERVER_SOFTWARE URL HTTP_CONNECTION

0 CGI/1.1 off

1 /LM/W3SVC/1 127.0.0.1 /a.aspx c:\inetpub\wwwroot\a.aspx

127.0.0.1 127.0.0.1 GET /a.aspx 127.0.0.1 80 0 HTTP/1.1 Microsoft-IIS/5.0 /a.aspx Keep-Alive image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, HTTP_ACCEPT application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, */* HTTP_ACCEPT_ENCODING gzip, deflate HTTP_ACCEPT_LANGUAGEen-us HTTP_HOST 127.0.0.1 Mozilla/4.0 (compatible; MSIE 6.0b; Windows NT 5.0; HTTP_USER_AGENT .NET CLR 1.0.2914)

In a.aspx, we simply added an attribute called Trace and assigned it a value of true. This resulted in a page full of very useful information. First 'hi' and 'bye' were displayed, and then, we saw a table where the information was categorized into different sections.

The first section is the Request Information where the session id is displayed in the form of a very long number. It changes with every new browser session. Then, the datetime of the file request is displayed. The request type can either be GET or POST. Since we have not explicitly specified the type, it has the default value of GET.

The last is the success/error code. If all goes well, like it has in this case, the code sent to the browser should be 200. In the case of an error, the error code or error number is reported. For example, if a file is not found, error number 404 is returned.

We are fully aware that a large number of functions get called from our page. But it is challenging to figure out as to which functions have been called, and the order in which they have been executed. The trace gives us a ready rejoinder for this. At first, the Init functions are called. They are followed by the functions PreRender, SaveState and Render, in that order. A trace output augments our understanding of ASP+.

In the current file, we have no controls on our page, but if we did have them, they would all have been displayed.

The next category encompasses the Session State. All the session variables that we create, are listed here, along with their values. A cookie that expires when the browser session is closed, is called a session variable.

Following the Session State is the Cookies Collection. Even though our program has not sent any cookies, ASP+ sends over a cookie to maintain state. All cookies are listed with their names and values. Following these categories are the details about the Headers, followed by details about the Server variables.

The trace output assists in debugging code. When you run the samples provided by Microsoft, you will witness a large number of functions that are called by the framework, to handle a database request. We could have added one more property called TraceMode, which specifies the trace statements. The default behaviour of SortByTime can also be changed to TraceMode="SortByCategory".

There is a Page-level tracing that writes debugging statements directly to the output of a page. If tracing is on, it also executes code.

a.aspx <%@ Page Trace="true" TraceMode="SortByCategory" %> <html> <script language="C#" runat="server"> public void Page_Load(Object sender, EventArgs E) { Trace.Warn("aaa","bbb"); if (Trace.IsEnabled) Trace.Write("ccc","vijay"); } public void abc(Object sender, EventArgs E) { Trace.Write("ddd","mukhi"); Trace.Warn("eee","sonal"); } </script> <body> <form runat="server"> <input type="Submit" OnServerClick="abc" Value="hi" runat="server"/> </form> </body> </html>

We have a property called Trace of type TraceContext, which executes the functions Warn and Write. Both these functions display the parameters that are passed to them in red and normal colour, respectively. This output is placed under the Trace Information. Here, two parameters are required. The first parameter will get displayed in the column Category and the second, under the heading Message.

The function Page_Load is called once. It looks for the value contained in the Trace property. This value is of type Boolean. Hence, it will return true when trace is on, and false, when trace is off. We can execute trace code only if tracing is enabled.

When we click on the button, the trace output shows plenty of code that has been called, and it also displays the order in which the functions are being executed. Notice that the Trace statements in the function Page_Load confirm the fact that Page_Load gets called each time that we go back to the server.

public void Page_Load(Object sender, EventArgs E) { if (!IsPostBack) { Trace.Warn("aaa","bbb"); if (Trace.IsEnabled) Trace.Write("ccc","vijay"); } }

We have now added an 'if' statement to the Page_Load function to verify whether IsPostBack has a value of false for the first time or not.

Now, the trace statements will be displayed only once, because when we click on the button, these statements are not displayed again. This substantiates the point that we are trying to make. Thus, we advise you to keep the trace on, if you want to figure out the order of execution of functions.

Application level tracing is turned-on by adding the following line in the web.config file:

web.config <configuration> <system.web> <trace enabled="false" requestLimit="0" pageOutput="false" traceMode="SortByTime" /> </system.web> </configuration>

In order to see the tracing output, load a file called trace.asx using http://localhost/trace.asx . This will first show us the individual requests. Then, we can drill down to the actual tracing data.

Caching

Hard disks are always slower than memory, since they are mechanical devices. The Internet is much slower compared to your hard disk. So, it obviously takes much longer for a file to be displayed in a browser, if it has to travel across the Internet. Retrieving the same file from our hard disk is a relatively faster process. Caching is a technique used in computers, which helps in increasing the speed of access. This is done by storing that portion of the data in memory, which is required to be accessed very often. Thereby, it can be accessed much more quickly.

In the web world, caching has a different meaning. The performance of our web server would drastically improve, if we held onto the web page between web requests, so that we do not have to recreate them.

ASP.Net offers us two kinds of caching, namely, Output Caching and Data Caching.

In Output Caching, the html file created by the aspx application is cached or stored, instead of sending it across immediately. In Data Cache, an object is stored programmatically. ASP.Net provides a full-featured cache engine. This allows us to hold on to or store an object in such a way that we can re-use it across http requests.

We use Output Caching whenever the entire page can be cached. A web site that has a large number of visitors can experience substantial performance gains, if it can cache a frequently accessed page even for a single minute. Thus, page caching implies that in the case of an http request, the page is served from the cache. It is not recreated by executing the code that it contains.

It is not always practical to cache an entire page at a time. Hence, an alternative is to cache only a portion or some objects on that page. Thus, those objects of a page that take a long time to be created, should be cached for a longer period.

How does one decide as to when, and for how long an object should be cached? This is not an easy decision to make. The data might get refreshed at regular intervals, or it may be valid for a specified time period only. We are allowed to associate an expiration period with an item in the cache. On doing so, ASP.Net will remove the item from the cache only when the specified expiration period has elapsed. Thus, a program will first look for data in the cache. Only if it cannot find the item there, will it re-create it.

In ASP+, the concept of caching is quite advanced. A cache item can depend upon an external file or another cache item. Thus, if one cache item expires, all the other cache items that are dependent on it, also expire. Some items may expire when their data source is modified.

a.aspx <%@ OutputCache Duration="60" VaryByParam="none" %> <html> <script language="C#" runat="server"> void Page_Load(Object sender, EventArgs e) { l.Text = DateTime.Now.ToString("r"); } </script> <body> <asp:label id="l" runat="server"/> </body> </html>

The above example displays the current data and time, since the value is displayed off the DateTime object. Open the same file in a Browser, and the time remains the same. This happens because of the directive OutputCache, where the duration property is set to 60 seconds. The first time One access the aspx program, it is kept in the cache for Sixty seconds. Thus, when we open the file in a new browser, the value present in the cache is picked up. Then, after sixty seconds have elapsed, the file gets re-executed. Thus, output caching is a very powerful technique meant for increasing the performance of the server. Items are placed in memory and not reloaded from the disk, over and over again. Accessing the hard disk slows down the program.

The output is cached only when the above directive is employed. In the first round, a valid GET or HEAD response is sent to the server. So, a cache entry is created internally. Then, for future requests, the cache is read, until it expires.

The cache also checks the entire URL, including the parameters passed to it. If any of the parameters passed, or the QueryString is different, the cache is ignored and the value is fetched from the server. This is known as a Cache Miss.

a.aspx <%@ OutputCache Duration="15" VaryByParam="none"%> <html> <script language="C#" runat="server"> void Page_Load(Object sender, EventArgs e) { l.Text = DateTime.Now.ToString("r") + "<br>"; } </script> <body> <form action=a.aspx> <asp:label id="l" runat="server"/> <input type=text name=aa> <input type=submit value="hi"> </body> </html>

Output

To explain the above principle, we have a textbox and a button that calls the same form again. You can enter any text in the textbox and click on the button to submit the value. Since the page gets reloaded, we see a different date time value. Open a new copy of the browser before 15 minutes are elapsed and youll notice that the time does not get updated as the value stored in the cache is reloaded.

However, if another copy of the browser is loaded after 15 seconds have elaplsed, we see the current time on the screen.

The output cache maintains the sanctity of the duration specified for which you want the data to be cached. Under no circumstance will the data be removed from the cache earlier than the specified duration. This is because, the framework cannot, on its own, comprehend the reason why you need to place something in the cache for the specified duration. When a page is valid in the cache for a specified duration of time, it is known as an absolute expiration policy. The server can also send http headers to the client, which include the duration for which a page is to remain valid on the browser's side.

VaryByParam can take only three values, namely none, * or parameters. DateTime.Now.ToString contains the alphabet r as a parameter. This refers to a certain format in which the date and time are to be displayed. Change the value to G and the output will vary accordingly.

Data Caching

a.aspx <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SqlClient" %>

<html> <script language="C#" runat="server"> void Page_Load(Object Src, EventArgs E) { DataView s; s = (DataView)Cache["yyy"];

if (s == null) { SqlConnection c = new SqlConnection("server=localhost;uid=sa;pwd=;database=NorthWind"); SqlDataAdapter co = new SqlDataAdapter("select * from Products", c); DataSet ds = new DataSet(); co.Fill(ds, "zzz"); s = new DataView(ds.Tables["zzz"]); Cache["yyy"] = s; i.Text = "Dataset created "; } else { i.Text = "Dataset retrieved from cache"; } l.DataSource=s; l.DataBind();

} </script> <body> <form method="GET" runat="server"> <asp:label id="i" runat="server"/></i> <ASP:DataGrid id="l" runat="server"/> </form> </body> </html>

Output Dataset created

ASP.Net offers us a caching engine that has all the bells and whistles we will ever need. It lets us store and retrieve any type of arbitrary objects in the cache, across http requests. These objects are stored in the memory and not on the disk. They are private to each application. Fortunately, we are provided with a simple dictionary interface, like the ViewState and Session objects, that let us store some object and equate it with a value.

In the above example, we are using the cache indexer and checking for a variable called yyy. Since any object can be stored in a cache, we cast it to a DataView object. s returns a value of null, since we have not placed anything in the cache yet. We populate the DataView with data from the database. We store the view object that represents the SQL data, into the Cache property, using the name yyy.

Henceforth, any access made to this page, will result in a non-null value for 's'. Thus, data is read from the cache without executing the SQL statements. This also works across sessions or browser instances. Imagine the boost in the performance that results, from not having to go back to the SQL server.

a.aspx <%@ Import Namespace="System.IO" %> <%@ Import Namespace="System.Data" %> <html> <script language="C#" runat="server"> void Page_Load(Object Src, EventArgs E ) { if(!IsPostBack) { xyz(); } } void abc(Object sender, EventArgs E) { DataSet ds = new DataSet(); FileStream fs = new FileStream(Server.MapPath("c.xml"),FileMode.Open, FileAccess.Read, FileShare.ReadWrite); StreamReader r = new StreamReader(fs); ds.ReadXml(r); fs.Close();

DataRow n = ds.Tables[0].NewRow(); n["auid"] = i.Text; n["name"] = name.Text; ds.Tables[0].Rows.Add(n); fs = new FileStream(Server.MapPath("c.xml"), FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite); TextWriter w = new StreamWriter(fs); w = TextWriter.Synchronized(w); ds.WriteXml(w); w.Close(); xyz(); } void pqr(Object sender, EventArgs e) { xyz(); } void xyz() { DataView s = (DataView)Cache["yyy"]; if(s == null) { DataSet ds = new DataSet(); FileStream fs = new FileStream(Server.MapPath("c.xml"), FileMode.Open,FileAccess.Read); StreamReader r = new StreamReader(fs);

ds.ReadXml(r); fs.Close(); s = new DataView(ds.Tables[0]); Cache.Insert("yyy", s, new CacheDependency(Server.MapPath("c.xml"))); c.Text = "Dataset created explicitly"; } else { c.Text = "Dataset retrieved from cache"; } l.DataSource = s; l.DataBind(); } </script> <body> <form runat="server"> <ASP:DataGrid id="l" runat="server"/> Id: <ASP:TextBox id=i Text="1" runat=server/> Last Name: <ASP:TextBox id=name Text="Mukhi" runat=server/> <asp:button Text="Add " OnClick="abc" runat=server/> <asp:button Text="Refresh " OnClick="pqr" runat=server/>

<asp:label id="c" runat="server"/></i></p> </form> </body> </html>

c.xml <DocumentElement> <xsd:schema id="DocumentElement" targetNamespace="" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoftcom:xml-msdata"> <xsd:element name="Table"> <xsd:complexType> <xsd:all> <xsd:element name="auid" type="xsd:string"/> <xsd:element name="name" type="xsd:string"/> </xsd:all> </xsd:complexType> </xsd:element> <xsd:element name="DocumentElement" msdata:IsDataSet="true"> <xsd:complexType> <xsd:choice maxOccurs="unbounded"> <xsd:element ref="Table"/> </xsd:choice> </xsd:complexType>

</xsd:element> </xsd:schema> <Table> <auid>1</auid> <name>vijay</name> </Table> </DocumentElement>

Output when clicked on Refresh

This program shows us how we can update the data in the cache, if a file has been updated.

Loading a.aspx in the browser, results in a call to the function xyz. This function can be called from multiple places. It simply populates the DataGrid control, which has the id of l, with data from the file c.xml. The xml file must reside in the same directory as a.aspx.

Initially, verification is done to confirm the existence of yyy in the Cache object. The first time around, it will obviously not be present, and hence, the 'if' statement gets called.

Within the 'if' block, a new DataSet object is created. Using the static function MapPath from the Server class, the full physical path name of c.xml is retrieved. The xml file is then read, and a new DataView object named 's' is created.

We not only use the Insert function to associate the words yyy with the DataView object 's', but also to create a CacheDependency object, whose constructor is passed a full path or a file named c.xml. Thus, whenever this file is modified, the Cache object will remove yyy from the cache, and its return value will be null. All this happens internally, without any interference from our side.

Each time we click on the refresh button, the function pqr is called. This function in turn calls the function xyz. The function xyz notices that the cache object has a valid DataView object, and hence, it does not read the xml file. The label displays whether we have picked up anything from the cache or not.

When we click on the add button, a record gets added to the xml file through the function abc.

To add a record, a new DataSet is created, followed by a FileStream. Then the XML data is read. The file is closed thereafter. In addition to this, a DataRow object having two fields named auid and name, is created and filled up, using the indexer n. The TextWriter class writes this newly created row to the file. The function xyz, when called, observes that the xml file has changed. Hence, it reloads the file. Thus, the new data gets displayed. Any change to the XML file invalidates the yyy object, and hence, it is removed from the cache.

ASP.Net actually supports three types of caching:

The Scavenging Method: Scavenging is a process that vultures are adept at. Items that are not needed must be removed. We cannot let the cache grow too big, since on doing so, we would use up memory, which is a valuable resource. Thus, items that are not accessed very often, are removed from the cache. We can associate a cost with each item, thus, providing the framework with a criterion to decide as to which items are to be removed.

The Expiration Method: This method has already been explained earlier. In this method, the lifetime of an item is explicitly stated. We can either state an explicit value, such as midnight

today, or a number that is relative to the time when the item was last accessed, such as 10 minutes after the item was last accessed. There are innumerable choices available.

The File and Key Dependencies Method: If a dependency changes, the item in the cache is invalidated and removed. The above example invalidates the cache item yyy, when the xml file changes. Thus, the moment the file changes, its data is retrieved again, and the Dataview is updated with the new changes. The Insert function can take many more parameters that specify the time duration for which the item is to remain in the cache. This can be specified as an absolute time or a time period relative to the instance when it was last accessed.

Web.Config

Let us go deeper into the world of configuration. As mentioned a couple of times in the past, the XML file config.web stores all the details of how the web server will behave.

a.aspx <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SqlClient" %> <html> <script language="C#" runat="server"> void Page_Load(Object Src, EventArgs E ) { String d = (String) ((NameValueCollection) Context.GetConfig("system.web/dsnstore"))["yyy"]; SqlConnection c = new SqlConnection(d); SqlDataAdapter ma = new SqlDataAdapter(); ma.SelectCommand = new SqlCommand(); ma.SelectCommand.Connection = new SqlConnection(d);

ma.SelectCommand.CommandText = "select * from Products"; DataSet ds = new DataSet(); ma.Fill(ds, "zzz"); l.DataSource=new DataView(ds.Tables[0]); l.DataBind(); } </script> <body> <ASP:DataGrid id="l" runat="server"/> </body> </html>

web.config <configuration> <configSections> <sectionGroup name="system.web"> <section name="dsnstore" type="System.Configuration.NameValueSectionHandler,System" /> </sectionGroup> </configSections> <system.web> <compilation debug="true" /> <dsnstore> <add key="yyy" value="server=(local)\NetSDK;database=northwind;Trusted_Connection=yes" />

</dsnstore> </system.web> </configuration>

In the above example, we are simply retrieving data from a database and putting it into a DataGrid named l. The difference here is that we have used a string 's' as the connection string and have not hard coded the values, unlike what we had done earlier.

This string 's' gets its value from a function named GetConfig, which in turn, uses the system.web/dsnstore. If you look at web.config, it has a section name initialized to dsnstore within the configSections tags. Also, the name of the class that will handle this section, System.Configuration.NameValueSectionHandler is specified.

The same tag called dsnstore is used to add a key named yyy. The value assigned to this key is our connection string that refers to the northwind database on SQLServer. The indexer is then used to access the value of this key.

The web.config file stores strings that can be retrieved by the programmer later. Those items that are used by everyone, can be stored in a configuration file. If there is a change in any of these items, it has to be incorporated in just one place i.e. the configuration file, and thereafter, the change is displayed to everyone who accesses the page thereafter.

Security

We had considered explaining the security concepts to you with a slightly different approach. There are a large number of samples available from Microsoft called the Quickstart tutorials. We have borrowed a considerably large number of these samples from there, and have also added a sizeable number of our own. By default, all the samples that run, are written in VBscript and not in C#.

To be able to execute the first security example, we need to write the following URL:

http://localhost/quickstart/aspplus/samples/security/WindowsAuth/CS/windowsauth.aspx

Using Windows Authentication

If you search for a directory called quickstart, you will not be able to trace it. This is because quickstart is a virtual directory that begins at

C:\Program Files\Microsoft.Net\FrameworkSDK\Samples\QuickStart.

You can verify this by clicking on Start, Programs, Administrative Tools, Internet Services Manager and then, on the Default web site. If you click on the plus sign for this option, you will see the word 'quickstart' listed there. Thus, the file windowsauth.aspx starts at the following location:

C:\PROGRA~1\Microsoft.NET\FrameworkSDK\Samples\quickstart \aspplus\samples\security\windowsauth\cs

Now that we are aware of where our code resides, we will move into this sub-directory and copy the file windowsauth.aspx as a1.aspx. This will keep the original code intact, and at the same time, allow us to add our own file. Enter the program given below and provide the URL as follows:

http://localhost/quickstart/aspplus/samples/security/WindowsAuth/CS/a.aspx

a.apsx <html> <script language="C#" runat=server> void Page_Load(Object Src, EventArgs E ) { Response.Write(User.Identity.Name + " " + User.Identity.AuthenticationType); } </script> <body> </body> </html>

Output VMCI\Administrator Negotiate

ASP+ needs to identify who we are. This is the first level of security in ASP.Net. We logged into Windows 2000 as a user called Administrator. Our computer was named as VMCI. Hence, the above output was displayed.

Next, we go one sub-directory higher and then move down into the sub-directory cookieauth\cs. Here, we copy the file default.aspx as a.aspx, and write the URL in the browser window as follows:

http://localhost/quickstart/aspplus/samples/security/CookieAuth/CS/a.aspx

a.aspx <%@ Import Namespace="System.Web.Security " %> <html> <script language="C#" runat=server> void Page_Load(Object Src, EventArgs E ) { Response.Write("Hell, " + User.Identity.Name); } void abc(Object sender, EventArgs E) { FormsAuthentication.SignOut(); Response.Redirect("login.aspx"); } </script> <body> <form runat=server> <asp:button text="Signout" OnClick="abc" runat=server/> </form> </body> </html>

Output

Instead of the file a.aspx being displayed, we are redirected to a file called login.aspx. How did this happen?

The URL that gets generated in the browser's address bar, is as follows:

http://localhost/quickstart/aspplus/samples/security/CookieAuth/CS/login.aspx?ReturnUrl=http% 3a%2f%2flocalhost%2fquickstart%2faspplus %2fsamples%2fsecurity%2fCookieAuth%2fCS%2fa.aspx

All characters such as a / symbol, get converted to the ASCII codes displayed in hex. Here, %2f stands for a / symbol. The parameter ReturnUrl has a value of a.aspx.

The URL changes due to the settings present in the web.config file in the same Directory. These are definitely worth taking a look at.

web.config <configuration> <system.web>

<authentication mode="Forms"> <forms name=".ASPXUSERDEMO" loginUrl="login.aspx" protection="All" timeout="60" /> </authentication> <authorization> <deny users="?" /> </authorization> <globalization requestEncoding="UTF-8" responseEncoding="UTF-8" /> </system.web> </configuration> In this file, the authentication tag has a mode that involves the use of Forms. The Form tag specifies a file called login.aspx. We have not been authenticated by the framework to load any file, unless we login. Hence, the file login.aspx is displayed. Thus, any aspx file in this subdirectory will not get loaded, unless the user logs in through the login.aspx file. We shall now explore the contents of this file.

Login.aspx <%@ Import Namespace="System.Web.Security " %> <html> <script language="C#" runat=server> void abc(Object sender, EventArgs E) { if ((name.Value == "vijay") && (pwd.Value == "mukhi")) { FormsAuthentication.RedirectFromLoginPage (name.Value,Cookie.Checked); } else

{ l.Text = "Invalid password mutt Please try again"; } } </script> <body> <form runat=server> User Name: <input id="name" type="text" runat=server/> <p> Password: <input id="pwd" type=password runat=server/> <p> <ASP:RequiredFieldValidator ControlToValidate="pwd" Display="Static" ErrorMessage="*" runat=server/></td> Persistent Cookie: <ASP:CheckBox id=Cookie runat="server" /> <p> <asp:button text="Login" OnClick="abc" runat=server/> <asp:Label id="l" ForeColor="red" Font-Name="Verdana" Font-Size="10" runat=server /> </form> </body> </html> In login.aspx, we have a textbox called name, where the user is expected to type in his name. Then, an input box called pwd, of the type password, is provided. This ensures that the password

keyed in the textbox, is displayed as a series of asterix. If the user does not enter anything, the required field validator gets activated and displays an asterix.

If you click on the button labeled 'Login', the function abc gets called, which determines whether the name is 'vijay' and password is 'mukhi', or otherwise. If it is, a static function called RedirectFromLoginPage from the FormsAuthentication.class is called, which loads the original file of a.aspx. Moreover, a cookie with the funny name ..ASPXUSERDEMO, is also sent across. This name can be seen in the file config.web. You can verify this by changing the cookie options to the 'prompt' mode.

The second parameter to the RedirectFromLoginPage function decides whether the cookie should be made persistent, i.e., saved on the user's hard disk, so that it can be sent across each time. The default type of cookie is a session cookie.

Thereafter, we reach the original file named a.aspx. When we click on the button in this file, the function abc gets called again. This function in turn, calls the SignOut function from the class FormsAuthentication which kills the cookie. Hence, we are redirected back to the login page.

Thus, implementation of security issues is much more straightforward and clear-cut in ASP.NET. If we have not been authenticated, a default file gets called. On valid authentication, we are directed back to the original file that we had requested for. Once the user is authenticated, a set of rules can be applied to restrict accessibility to certain features. This also helps in customization of the interface.

In the web.config file, the authorization tag can be used with the word 'deny', initialized to those users who are to be permanently denied access. The ? value signifies anonymous users, and it forbids all anonymous users from logging into the site.

web.config <configuration> <system.web>

<authentication mode="Forms"> <forms name=".ASPXUSERDEMO" loginUrl="login.aspx" protection="All" timeout="60" /> </authentication> <authorization> <deny users="vijay" /> </authorization> <globalization requestEncoding="UTF-8" responseEncoding="UTF-8" /> </system.web> </configuration>

In the authorization tag, if the 'deny users' is initialized to vijay, then any user who logs in as 'vijay'is denied access. Thus, 'vijay' is not permitted to view a.aspx. There is no way to bypass the login page, even though we have keyed in the right password. Thus, we first need to get authenticated and thereafter, we need to have the relevant authorization to put our intentions into practice.

-8-

Web Services
The .Net framework recognizes and acknowledges files with an extension of asmx as a Web Service. Therefore, in order to cater to the prerequisites of .Net framework, we design a file called a.asmx, with a class named zzz.

a.asmx public class zzz { public int abc(int i) { return i*2; } }

Output Parser Error Message: The page must have a <%@ webservice class="MyNamespace.MyClass" ... %> directive

The class zzz has a function called abc, that accepts an int as a parameter and returns a value, after multiplying the parameter by 2. No class can be more uncomplicated and clear-cut than the one we have written. Yet, we get an error when the file is loaded as http://localhost/a.asmx in the browser. This is because, a Web service is a special file, and the framework is required to handle this exceptional file, a little differently. So, we need to supplement this file by making some more additions, as shown below.

a.asmx <%@ WebService Language="C#" Class="zzz" %> public class zzz { public int abc(int i) { return i*2; } }

In the previous program, since the directive named WebService was missing, an error was reported. The directive WebService is followed by the name of the language which has been initialized to C#, because we will be writing the Web Service, using the C# programming language. An asmx file may contain a numerous classes, but only one of them represents the Web Service. Thus, the class property is made equal to zzz. We spot the following output in the browser:

Output zzz WebService

zzz

The following operations are supported. For a formal definition, please review the Service Description.

---------------------------------------------------------------------------This web service is using http://tempuri.org/ as its default namespace. Recommendation: Change the default namespace before the web service is made public. Each web service needs a unique namespace to identify it so that client applications can distinguish it from other .............. ...................... For more details on XML namespaces, see the W3C recommendation on Namespaces in XML. For more details on WSDL, see the WSDL Specification. For more details on URIs, see RFC 2396.

The class zzz is now acknowledged as a Web Service. For the moment, there are no web methods exposed by our class. A Web Service permits others to execute code in our class. We want the function abc to be called with a number, so that it can majestically return the numbers twice over, than it had been served with.

No web methods are shown, since at this point in time, the function abc is inaccessible.

a.asmx <%@ WebService Language="C#" Class="zzz" %> using System.Web.Services; public class zzz { [WebMethod]

public int abc(int i) { return i*2; } }

Output zzz

The following operations are supported. For a formal definition, please review the Service Description.

abc

Click on abc and the screen changes to accept values in a text box

Click here for a complete list of operations.

abc

Test To test, click the 'Invoke' button.

Parameter Value i:

SOAP

The following is a sample SOAP request and response. The placeholders shown need to be replaced with actual values.

POST /a.asmx HTTP/1.1 Host: localhost Content-Type: text/xml; charset=utf-8 Content-Length: length SOAPAction: "http://tempuri.org/abc"

<?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <abc xmlns="http://tempuri.org/"> <i>int</i> </abc> </soap:Body> </soap:Envelope>

HTTP/1.1 200 OK Content-Type: text/xml; charset=utf-8 Content-Length: length

<?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <abcResponse xmlns="http://tempuri.org/"> <abcResult>int</abcResult> </abcResponse> </soap:Body> </soap:Envelope>

HTTP GET The following is a sample HTTP GET request and response. The placeholders shown need to be replaced with actual values.

GET /a.asmx/abc?i=string HTTP/1.1 Host: localhost

HTTP/1.1 200 OK Content-Type: text/xml; charset=utf-8 Content-Length: length

<?xml version="1.0" encoding="utf-8"?> <int xmlns="http://tempuri.org/">int</int>

HTTP POST The following is a sample HTTP POST request and response. The placeholders shown need to be replaced with actual values.

POST /a.asmx/abc HTTP/1.1 Host: localhost Content-Type: application/x-www-form-urlencoded Content-Length: length

i=string HTTP/1.1 200 OK Content-Type: text/xml; charset=utf-8 Content-Length: length

<?xml version="1.0" encoding="utf-8"?> <int xmlns="http://tempuri.org/">int</int>

To convert a function into a web method, we have to add an attribute named WebMethod from the namespace System.Web.Services. When the asmx file is now loaded, the screen is flashed with the name of the function, its parameter names and their data types. In addition, we get an input box to enter a number. This number becomes the value of the parameter i. When we keyed

in the number 12 and clicked on the Invoke button, to our utter amazement, we saw the number 24 displayed, as shown below.

Output <?xml version="1.0" encoding="utf-8" ?> <int xmlns="http://tempuri.org/">24</int>

This happens to be an xml file. Since the return value of our function is an int, the number 24 is enclosed within the int tag. The html file that we had taken notice of, and had attended to, was honestly, all smokes and mirrors.

Whenever the framework stumbles upon a file with an asmx extension, it treats it very differently from an aspx file. It finds out all the functions in the Web Service class that are tagged with an attribute of WebMethod. It then creates an HTML file. Clicking on the invoke button results in the execution of a URL by passing it parameters.

Next, we are interested in calling the function abc, with a parameter i, which has a value of 23. However, when we actually call the function abc, which has to be summoned from the Web Service zzz in the file a.asmx, the following URL has to be entered in the IE address bar: http://localhost/a.asmx/abc?i=23

The output window displays the following:

Output <?xml version="1.0" ?> <int xmlns="http://tempuri.org/">46</int>

Thus, if we are aware about the existence of a Web Service and are responsive towards its nuts and bolts, we can easily call the code from it, using a URL. The parameters to the functions are passed as HTML parameters. Assuming that we had two parameters named i and j in the function abc, we would enter the URL as follows: http://localhost/a.asmx/abc?i=12&j=10.

On placing an error in the above C# program, we noticed that our Web Service is actually a dll. No extra code is added to the Web Service file, unlike in a control. Also, a Web Service does not derive from any other class. A Web Service internally uses SOAP, or the Simple Object Access Protocol, to bring this magic into being!

One more thing that you should be well conversant with, is the Service Description (WSDL file). If you click on the Service Description link, you will see an XML file that has obviously not been written by us. Let us now try to appreciate, what goes into this file.

WSDL file <?xml version="1.0" encoding="utf-8" ?> - <definitions xmlns:s="http://www.w3.org/2001/XMLSchema" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" xmlns:tm="http://microsoft.com/wsdl/mime/textMatching/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:s0="http://tempuri.org/" targetNamespace="http://tempuri.org/" xmlns="http://schemas.xmlsoap.org/wsdl/"> - <types> - <s:schema attributeFormDefault="qualified" elementFormDefault="qualified" targetNamespace="http://tempuri.org/"> - <s:element name="abc"> - <s:complexType> - <s:sequence> <s:element minOccurs="1" maxOccurs="1" name="i" type="s:int" /> </s:sequence>

</s:complexType> </s:element> - <s:element name="abcResponse"> - <s:complexType> - <s:sequence> <s:element minOccurs="1" maxOccurs="1" name="abcResult" type="s:int" /> </s:sequence> </s:complexType> </s:element> <s:element name="int" type="s:int" /> </s:schema> </types> - <message name="abcSoapIn"> <part name="parameters" element="s0:abc" /> </message> - <message name="abcSoapOut"> <part name="parameters" element="s0:abcResponse" /> </message> - <message name="abcHttpGetIn"> <part name="i" type="s:string" /> </message> - <message name="abcHttpGetOut"> <part name="Body" element="s0:int" />

</message> - <message name="abcHttpPostIn"> <part name="i" type="s:string" /> </message> - <message name="abcHttpPostOut"> <part name="Body" element="s0:int" /> </message> - <portType name="zzzSoap"> - <operation name="abc"> <input message="s0:abcSoapIn" /> <output message="s0:abcSoapOut" /> </operation> </portType> - <portType name="zzzHttpGet"> - <operation name="abc"> <input message="s0:abcHttpGetIn" /> <output message="s0:abcHttpGetOut" /> </operation> </portType> - <portType name="zzzHttpPost"> - <operation name="abc"> <input message="s0:abcHttpPostIn" /> <output message="s0:abcHttpPostOut" />

</operation> </portType> - <binding name="zzzSoap" type="s0:zzzSoap"> <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document" /> - <operation name="abc"> <soap:operation soapAction="http://tempuri.org/abc" style="document" /> - <input> <soap:body use="literal" /> </input> - <output> <soap:body use="literal" /> </output> </operation> </binding> - <binding name="zzzHttpGet" type="s0:zzzHttpGet"> <http:binding verb="GET" /> - <operation name="abc"> <http:operation location="/abc" /> - <input> <http:urlEncoded /> </input> - <output> <mime:mimeXml part="Body" />

</output> </operation> </binding> - <binding name="zzzHttpPost" type="s0:zzzHttpPost"> <http:binding verb="POST" /> - <operation name="abc"> <http:operation location="/abc" /> - <input> <mime:content type="application/x-www-form-urlencoded" /> </input> - <output> <mime:mimeXml part="Body" /> </output> </operation> </binding> - <service name="zzz"> - <port name="zzzSoap" binding="s0:zzzSoap"> <soap:address location="http://localhost/a.asmx" /> </port> - <port name="zzzHttpGet" binding="s0:zzzHttpGet"> <http:address location="http://localhost/a.asmx" /> </port> - <port name="zzzHttpPost" binding="s0:zzzHttpPost">

<http:address location="http://localhost/a.asmx" /> </port> </service> </definitions>

This XML file gives us all the details about the Web Service. It represents the Web Service, but without the code.

Let us explain the how's and why's of it. A WSDL document defines services as collections of network endpoints, or ports. The tag called definition describes the Web Service, but in a non-programming manner. All Web Services are based on SOAP.

A Service Definition Language is made up of six major elements:

types, which provides data type definitions used to describe the messages exchanged.

message, which represents an abstract definition of the data being transmitted. A message consists of logical parts, each of which is associated with a definition within some type system. portType, which is a set of abstract operations. Each operation refers to an input message and output messages. binding, which specifies concrete protocol and data format specifications for the operations and messages defined by a particular portType. port, which specifies an address for a binding, thus defining a single communication endpoint. service, which is used to aggregate a set of related ports.

The WSDL file that has been generated, helps us to figure out the number of functions in the Web Service. The parameters, their data types and the return value are also specified along with the function names. This description is sufficient to execute a function. Observe that there is no sign of any code in the asmx file. Thus, the WSDL file is not concerned about whether the code is in Java or C# or in any other language. Since the file is machine generated, we will not spend more time deciphering it.

Let us now summon the Web Service from our program, which is written in C#.

a.asmx <%@ WebService Language="C#" Class="zzz" %> using System.Web.Services; public class zzz { [WebMethod] public int abc(int i) { return i*2; } }

Firstly, we write the following URL and click on the Service Description link, and then copy whatever file is displayed in the file named, a.wsdl in the c:\inetpub\wwwroot\bin sub-directory.

We now want some program to generate a C# program, which can act like our Web Service. The program that we shall be running, using the command laid down below, is called WebServiceUtil. Very soon, we shall be explaining as to what the various options in this command signify.

>wsdl.exe /l:CS /n:nnn a.wsdl

This will create a file called zzz.cs, since our Web Service class was called zzz. /n:nnn adds namespace nnn to the class. In case you receive any errors, you should ensure that the first line, <?xml version="1.0" ?>, begins at the first column, and the file thereafter starts with a tag on every line. Also if you have selected and copied the file from your browser, you will have to remove the - sign preceeding every line.

The contents of zzz.cs are as follows:

zzz.cs //-------------------------------------------------------------------------// <autogenerated> // // // // // Changes to this file may cause incorrect behavior and will be lost if the code is regenerated. This code was generated by a tool. Runtime Version: 1.0.2914.16

// </autogenerated> //-------------------------------------------------------------------------// // This source code was auto-generated by wsdl, Version=1.0.2914.16. namespace nnn { using System.Diagnostics;

using System.Xml.Serialization; using System; using System.Web.Services.Protocols; using System.Web.Services;

[System.Web.Services.WebServiceBindingAttribute(Name="zzzSoap", Namespace="http://tempuri.org/")] public class zzz : System.Web.Services.Protocols.SoapHttpClientProtocol {

[System.Diagnostics.DebuggerStepThroughAttribute()] public zzz() { this.Url = "http://localhost/a.asmx"; }

[System.Diagnostics.DebuggerStepThroughAttribute()] [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/abc",
Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]

public int abc(int i) { object[] results = this.Invoke("abc", new object[] { i}); return ((int)(results[0])); }

[System.Diagnostics.DebuggerStepThroughAttribute()]

public System.IAsyncResult Beginabc(int i, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("abc", new object[] { i}, callback, asyncState); }

[System.Diagnostics.DebuggerStepThroughAttribute()] public int Endabc(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((int)(results[0])); } } } This program has been generated by the wsdl program. The name of the class is given as zzz, which is derived from System.Web.Services.Protocols.SoapHttpClientProtocol. The function abc accepts one parameter i.e. int i. Before we go on to explain how this code gets generated, let us first convert this machine generated code into a library zzz.dll, with the help of the following csc command:

>csc /t:library /r:system.web.services.dll zzz.cs

Next, we have to call code from our Web Service. For this, we create a file a.aspx in the inetpub/wwwroot sub-directory.

a.aspx <%@ Import Namespace="nnn" %>

<%@ language=C# %> <form action="a.aspx" method="post" runat="server"> <script language="C#" runat=server> void abc(Object a1, EventArgs e) { zzz a = new zzz(); int i = a.abc(Int32.Parse(aaa.Text)); Response.Write(i.ToString()); } </script> <asp:textbox id="aaa" runat="server"/> <asp:button type=submit text="Click" OnClick="abc" runat="server"/> </form>

The framework looks into the bin sub-directory for the code of the objects. On sighting it, the code gets executed.

The above program will generate a compilation error, if zzz.dll is not present in the bin subdirectory or if there are more dlls in the directory. This is because, the code for the class zzz resides in the zzz.dll, moreover, the compiler is not informed about the location and the name of the dll name. This can be done using the /R: option.

To solve the mystery of locating the dll, we take the assistance of the web.config file.

web.config <configuration> <system.web> <compilation debug="false"> <assemblies> <add assembly="zzz"/> </assemblies> </compilation> </system.web> </configuration>

To change the default behavior of anything in the ASP.Net world, we have to turn to the configuration file. The 'add assembly' option adds the dll that has been assigned to it, to the csc compiler. To be precise, it appends the dll with the /r: option to the compiler, while compiling any cs file. This assembly can be present anywhere on our hard disk. The /bin sub-directory is a special directory, which is checked only for our business objects. This is how the framework can be customized to work with our files.

Now, if you load the aspx file using http://localhost/a.aspx, you will notice a button and a textbox. If you type in the number 12 and click on the button, the abc function in the aspx file will be called. In the function abc, a new zzz object called a, is created, and the function abc is called off it. This function is supplied with a parameter, which is the text entered in the TextBox, after converting it into an int. The return value of this function is displayed through the Write function. Any number that we enter is multiplied by 2, and then the value is returned.

Note that the code for the multiplication is not present in the zzz class. To further prove this point, we merely open the asmx file and multiply by 3, instead of 2. Now, if we click on the button, we will observe the numbers being multiplied by 3. Are you feeling perplexed already? If so, it would be sensible for you to revise the above text, before proceeding any further.

We are doing the following to prove to you that, you can easily change the way ASP+ looks at the world.

The VB sample in the documentation derives from the WebService class, while, the C# sample does not.

a.asmx <%@ WebService Language="C#" Class="zzz" %> using System; using System.Web.Services; public enum yyy { b1 = 10, b2 = 20 } public class xxx { public int i1; public double d1; } public class zzz { [WebMethod]

public String a1() { return "vijay"; } [WebMethod] public int[] a2() { int[] a = new int[2]; a[0] = 10; a[1] = 20; return a; } [WebMethod] public yyy a3() { return yyy.b1; } [WebMethod] public xxx a4() { xxx x = new xxx(); x.i1=10; x.d1 = 10.1;

return x; } [WebMethod] public xxx[] a5() { xxx [] x = new xxx[2]; x[0] = new xxx(); x[0].i1=3; x[0].d1=3.1; x[1] = new xxx(); x[1].i1=9; x[1].d1 = 9.1; return x; } }

We have created 5 functions named a1 to a5 in our Web Service. The display order may not be in the order of creation. The point we are making here is that, we are allowed to return any data types that we like. Let us start by clicking on each function and understanding the output. The first function, a1, simply returns a string.

Output <?xml version="1.0" encoding="utf-8" ?> <string xmlns="http://tempuri.org/">vijay</string>

The value 'vijay' is placed within a tag called string, since our function returns a string. The next function, a2, returns an array of ints.

Output <?xml version="1.0" encoding="utf-8" ?> <ArrayOfInt xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/"> <int>10</int> <int>20</int> </ArrayOfInt>

The individual ints are tagged with the int tag, and the entire array is enclosed in an ArrayOfInt tag. Thus, we can also return an array of any data type.

The next click will call function a3, which returns the value of an enum. An enum is a class that contains names that represent values.

Output <?xml version="1.0" encoding="utf-8" ?> <yyy xmlns="http://tempuri.org/">b1</yyy>

The enum member that is returned, is placed in a tag, that is the name of the enum class yyy.

Function a4 returns an object of a class xxx. This class has two members, i1 and d1. Hence, the output is displayed as follows:

Output <?xml version="1.0" encoding="utf-8" ?> <xxx xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/"> <i1>10</i1> <d1>10.1</d1> </xxx>

The last function, a5 is like the one above, but it returns an array of xxx objects.

Output <?xml version="1.0" encoding="utf-8" ?> <ArrayOfXxx xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/"> <xxx> <i1>3</i1> <d1>3.1</d1> </xxx> <xxx> <i1>9</i1> <d1>9.1</d1> </xxx> </ArrayOfXxx>

The tag, ArrayOfXxx encloses the entire output. Each member of the array is placed within the tag xxx, and the individual members are placed within their own tags. By making use of a Web Service, we are at a liberty to pass any data types, as return values or as parameters. Thus, there are no restrictions. We will leave it as an exercise for you to run the same Web Service from an aspx file.

a.asmx <%@ WebService Language="C#" Class="zzz" %> using System; using System.Data; using System.Data.SqlClient; using System.Web.Services; public class zzz { [WebMethod] public DataSet abc() { SqlConnection c = new SqlConnection("server=localhost;uid=sa;pwd=;database=NorthWind"); SqlDataAdapter co = new SqlDataAdapter("select productid,productname from Products where productid='1'",c); SqlDataAdapter co1 = new SqlDataAdapter("select customerid,companyname from Customers where customerid='BOLID'", c); DataSet ds = new DataSet(); co.Fill(ds, "zzz"); co1.Fill(ds, "yyy"); return ds;

} }

Output <?xml version="1.0" encoding="utf-8" ?> <DataSet xmlns="http://tempuri.org/"> <xsd:schema id="NewDataSet" targetNamespace="" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoftcom:xml-msdata"> <xsd:element name="NewDataSet" msdata:IsDataSet="true"> <xsd:complexType> <xsd:choice maxOccurs="unbounded"> <xsd:element name="zzz"> <xsd:complexType> <xsd:sequence> <xsd:element name="productid" type="xsd:int" minOccurs="0" /> <xsd:element name="productname" type="xsd:string" minOccurs="0" /> </xsd:sequence> </xsd:complexType> </xsd:element> <xsd:element name="yyy"> <xsd:complexType> <xsd:sequence> <xsd:element name="customerid" type="xsd:string" minOccurs="0" />

<xsd:element name="companyname" type="xsd:string" minOccurs="0" /> </xsd:sequence> </xsd:complexType> </xsd:element> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema> <diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1"> <NewDataSet xmlns=""> <zzz diffgr:id="zzz1" msdata:rowOrder="0"> <productid>1</productid> <productname>Chai</productname> </zzz> <yyy diffgr:id="yyy1" msdata:rowOrder="0"> <customerid>BOLID</customerid> <companyname>Blido Comidas preparadas</companyname> </yyy> </NewDataSet> </diffgr:diffgram> </DataSet>

One thing that is very evident is that, Microsoft is in love with XML and finds it irresistable. Hence, we see XML popping out of everywhere.

In the above Web Service, we are connecting to the database NorthWind and creating two SQL statements that will return one record each, from two separate tables. These select statements are added to our dataset object and the object is then returned. The output is in the form of an appealingly formatted XML file.

Let us try to understand this file now. As usual, the XML file starts with the xml version number. It is then followed by a tag called DataSet. DataSet informs us that the data given within it is from a database. The first dataset with the name zzz, becomes the name of our element. This is succeeded by the field names or the schema.

The same procedure is repeated for the second table in the data set. Then, we have a tag called NewDataSet, followed by the name of the first dataset zzz, in a tag form. Then, we have the values from the database enclosed by the field names, once again in tags. The same process is reiterated for the other table too.

a.asmx <%@ WebService Language="C#" Class="zzz" %> using System; using System.Web.Services; public class zzz : WebService { [WebMethod(EnableSession=true)] public String abc() {

if (Session["aa"] == null) { Session["aa"] = 1; } else { Session["aa"] = ((int) Session["aa"]) + 1; } return "Session " + Session["aa"].ToString() + " times."; } [WebMethod(EnableSession=false)] public String pqr() { if (Application["aa"] == null) { Application["aa"] = 1; } else { Application["aa"] = ((int) Application["aa"]) + 1; } return "Application " + Application["aa"].ToString() + " times."; }

In the above Web Service, we use two functions, named abc and pqr. The function abc has a parameter called EnableSession=true, added to the WebMethod. This parameter switches on the session tracking. The function pqr is similar to this, with an exception of the session tracking being disabled. Thereafter, a Session Variable aa, is created in the function abc and an Application Variable by the same name aa is created in pqr to store a value. This value is incremented by 1, each time, and is finally returned as a string.

The Application and Session objects are framework intrinsic. To understand the above example, select the 'prompt' radio button for the cookie. Now, each time we click on abc, a cookie is received by the browser. However, such is not the case with the Application.

Now, close all instances of the browser and open only one browser copy. Rewrite the same URL in the address bar and click on abc. The session count begins from 1. If you click on pqr, you will notice that the application remembers its last count, which, it now increments by 1. By disabling the session support for a particular web function, the web server now has less work to do. Thus, the web method will be served up faster.

We first start with the WSDL file named a.wsdl in the c:\inetpub\wwwroot\bin sub-directory.

a.wsdl <?xml version="1.0"?> <definitions xmlns:s="http://www.w3.org/1999/XMLSchema" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:s0="http://tempuri.org/" targetNamespace="http://tempuri.org/" xmlns="http://schemas.xmlsoap.org/wsdl/"> <types> <s:schema targetNamespace="http://tempuri.org/"

attributeFormDefault="qualified" elementFormDefault="qualified"> <s:element name="abc"> <s:complexType derivedBy="restriction"/> </s:element> <s:element name="abcResult"> <s:complexType derivedBy="restriction"> <s:all> <s:element name="result" type="s:string" nullable="true"/> </s:all> </s:complexType> </s:element> <s:element name="string" type="s:string" nullable="true"/> </s:schema> </types> <message name="abcHttpGetIn"/> <message name="abcHttpGetOut"> <part name="Body" element="s0:string"/> </message> <portType name="zzzHttpGet"> <operation name="abc"> <input message="s0:abcHttpGetIn"/> <output message="s0:abcHttpGetOut"/> </operation>

</portType> <binding name="zzzHttpGet" type="s0:zzzHttpGet"> <http:binding verb="GET"/> <operation name="abc"> <http:operation location="/a.html"/> <input> <http:urlEncoded/> </input> <output> <text xmlns="http://microsoft.com/wsdl/mime/textMatching/"> <match name='Title' pattern='TITLE&gt;(.*?)&lt;'/> <match name='Vijay' pattern='&gt;(.*?)&lt;'/> </text> </output> </operation> </binding> <service name="zzz"> <port name="zzzHttpGet" binding="s0:zzzHttpGet"> <http:address location="http://localhost" /> </port> </service> </definitions>

a.html <HTML> <HEAD> <TITLE>Hello!</TITLE> </HEAD> <BODY> <Vijay>Mukhi</Vijay> </BODY> </HTML>

We then run the following two commands:

>wsdl /l:CSharp /n:nnn a.wsdl

The above command creates a file called zzz.cs for us.

>csc /t:library zzz.cs

This creates a file by the name of zzz.dll in the bin sub directory.

zzz.cs //---------------------------------------------------------------------// <autogenerated>

// // // // //

This code was generated by a tool. Runtime Version: 1.0.2914.16

Changes to this file may cause incorrect behavior and will be lost if the code is regenerated.

// </autogenerated> //---------------------------------------------------------------------// // This source code was auto-generated by wsdl, Version=1.0.2914.16. // namespace nnn { using System.Diagnostics; using System.Xml.Serialization; using System; using System.Web.Services.Protocols; using System.Web.Services; public class zzz : System.Web.Services.Protocols.HttpGetClientProtocol {

[System.Diagnostics.DebuggerStepThroughAttribute()] public zzz() { this.Url = "http://localhost/a.html"; } [System.Diagnostics.DebuggerStepThroughAttribute()]

[System.Web.Services.Protocols.HttpMethodA ttribute(typeof(System.Web.Services.Protocols.TextReturnReader), typeof(System.Web.Services.Protocols.UrlParameterWriter))] public abcMatches abc() { return ((abcMatches)(this.Invoke("abc", (this.Url + "/QuickStart/aspplus/samples/services/TextMatching/CS/MatchServer.html"), new object[0]))); } [System.Diagnostics.DebuggerStepThroughAttribute()] public System.IAsyncResult Beginabc(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("abc", (this.Url + "/QuickStart/aspplus/samples/services/TextMatching/CS/MatchServer.html"), new object[0], callback, asyncState); } [System.Diagnostics.DebuggerStepThroughAttribute()] public abcMatches Endabc(System.IAsyncResult asyncResult) { return ((abcMatches)(this.EndInvoke(asyncResult))); } } public class abcMatches { [System.Web.Services.Protocols.MatchAttribute("TITLE>(.*?)<")] public string Title; [System.Web.Services.Protocols.MatchAttribute(">(.*?)<")] public string Vijay; }

a.aspx <%@ Import Namespace="nnn" %> <html> <script language="C#" runat="server"> public void Abc(Object Src, EventArgs E) { zzz m= new zzz(); abcMatches ma = m.abc(); ma.Vijay = "mukhi"; Response.Write(ma.Title + "." + ma.Vijay); } </script> <body> <form runat="server"> <input type="submit" OnServerClick="Abc" runat="server"/> </form> </body> </html>

Output

After clicking on the button: Hello!.mukhi

For the first time, we are creating a WSDL file manually.

<operation name="abc"> <http:operation location="/a.html"/>

We have a tag called operation that sets the name property to the function abc and the http operation location is set to a file named a.html.

The text tag encloses two occurrence of another tag called 'match'. The name 'property' is set to 'Title' and 'Vijay', respectively. Moreover, a pattern or wild card is specified for each of them. It specifies a certain pattern or a rule.

Now, the question that vexes our wits, is : From where will the value of 'Title' be obtained?

The value lies in the html file. The value of 'Hello', which is enclosed in the Title tag in the HTML file, is picked up and assigned to the 'Title' variable in a.aspx. The same procedure is followed for 'Vijay'. The tag name match is a special tag. It is available as a class called abcMatches, in the aspx file.

In the .cs file that is generated, the constructor saves the URL in a variable called Url, for future reference. The function abc returns an instance of the abcMatches class. The class abcMatches created in zzz.cs, contains two instance variables, 'Title' and 'Vijay', with or without the pattern.

In the aspx file, when a button is clicked, the function Abc is called. In this function, we create a new zzz instance, and then call the function abc from it. The output is an abcMatches object which we store in an object named ma. Thereafter, the value in 'Vijay' is initialized to 'mukhi'. Finally, both the variables are displayed, using the Write function. Thus, without creating any asmx file, using our code, we have been able to read data within tags in an HTML file. We are thus, doing things in a way that is a drastic departure from what we have been doing so far.

As we reiterated many times in the past, you are allowed to configure everything in case of ASP+. The main web.config file informs the framework about the aspx file that handles a Web Service, or a file with an asmx extension.

-9-

The Class Browser


In this chapter, we have picked up one of the Microsoft samples called the Class Browser and presented it to you in a straightforward and uncomplicated format, stripped of all its convolutions. This sample displays the following:

all the namespaces the classes within each namespace the functions within each class the parameters of each function, and so on.

It is a considerably large program, and hence appears intimidating. As is customary, we shall first partition this program into smaller programs and after deciphering every small part, we shall coalesce them together to form one composite program.

At the end of this explanation, you would not only be in a position to write complex ASP.Net code, but you would also have unraveled the mysteries of the Reflection API, which is a technique used to determine the contents of a class.

We have retained the function names and variable names as given in the original code, with the anticipation that sooner or later, you would be motivated enough to read the source code written by the programmers at Microsoft. Our example will work as effectively, sans the comely appearance of the original code.

Our first program displays a series of namespaces in a single column. These names are displayed as hyperlinks. Before we dive headlong into the program, we first need to create the file named web.config in the sub-directory c:\inetpub\wwwroot.

web.config <configuration> <configSections> <sectionGroup name="system.web"> <section name="ClassBrowser" type="System.Configuration.NameValueSectionHandler,System"/> </sectionGroup> </configSections> <system.web> <compilation debug="true"/> <ClassBrowser> <add key="Data Library" value="System.Data" /> <add key="ASP.NET Class Library" value="System.Web" /> <add key=".NET Framework class Library" value="mscorlib" /> </ClassBrowser> </system.web> </configuration>

a.aspx <%@ Import NameSpace="System.Collections" %> <%@ Import NameSpace="System.Collections.Specialized" %> <%@ Import NameSpace="System.Reflection" %> <html> <head> <script runat="server" language="C#"> ArrayList ModuleName = new ArrayList(); void Page_Load(Object Sender, EventArgs e) { NameValueCollection ConfigSettings; ConfigSettings = (NameValueCollection)Context.GetConfig("system.web/ClassBrowser"); Response.Write(ConfigSettings.Count.ToString() + "<br>"); for (int i = 0; i < ConfigSettings.Count; i++) { Response.Write(ConfigSettings[i].ToString() + "<br>"); ModuleName.Add(ConfigSettings[i].ToString()); } DisplayNamespaces(); } void DisplayNamespaces() {

ArrayList NameSpaceList = new ArrayList(); Hashtable NameSpaceHash = new Hashtable(); Response.Write(ModuleName.Count.ToString() + "<br>"); for (int y = 0; y < ModuleName.Count; y++) { Assembly a = Assembly.Load(ModuleName[y].ToString()); Module[] CorRuntime = a.GetModules(); Type[] CorClasses = CorRuntime[0].GetTypes(); Response.Write(ModuleName[y].ToString() + " Modules:" + CorRuntime.Length.ToString() + " Type:" + CorClasses.Length.ToString() + "<br>" );

for( int x=0; x < CorClasses.Length; x++ ) { if ( CorClasses[x].Namespace != null ) { if (!NameSpaceHash.ContainsKey(CorClasses[x].Namespace) && CorClasses[x].IsPublic) { NameSpaceHash.Add(CorClasses[x].Namespace,""); NameSpaceList.Add(CorClasses[x].Namespace); } } } } NameSpaceList.Sort();

Namespace1.DataSource = NameSpaceList; Namespace1.DataBind(); } </script> </head> <body> <form runat="server"> <asp:DataList runat=server id="Namespace1" RepeatLayOut="flow"> <headertemplate> Namespaces <br> </headertemplate> <itemtemplate> <asp:HyperLink runat="server" text=<%# Container.DataItem %> NavigateUrl=<%# "a.aspx?namespace=" + Container.DataItem %> /> </itemtemplate> <selecteditemtemplate> <b><asp:HyperLink runat=server text=<%# Container.DataItem %>/></b> </selecteditemtemplate> </asp:DataList> </form> </body> </html>

Output

3 System.Data System.Web mscorlib 3 System.Data Modules:1 Type:427 System.Web Modules:1 Type:663 mscorlib Modules:1 Type:1410

Namespaces

Microsoft.Win32 System System.Collections System.Configuration.Assemblies System.Data System.Data.Common System.Data.OleDb System.Data.SqlClient System.Data.SqlTypes System.Diagnostics System.Diagnostics.SymbolStore System.Globalization

System.IO System.IO.IsolatedStorage System.Reflection System.Reflection.Emit System.Resources System.Runtime.CompilerServices System.Runtime.CompilerServices.CSharp System.Runtime.InteropServices System.Runtime.InteropServices.Expando System.Runtime.Remoting System.Runtime.Remoting.Activation System.Runtime.Remoting.Channels System.Runtime.Remoting.Contexts System.Runtime.Remoting.Lifetime System.Runtime.Remoting.Messaging System.Runtime.Remoting.Metadata System.Runtime.Remoting.Metadata.W3cXsd2001 System.Runtime.Remoting.Proxies System.Runtime.Remoting.Services System.Runtime.Serialization System.Runtime.Serialization.Formatters System.Runtime.Serialization.Formatters.Binary System.Security

System.Security.Cryptography System.Security.Cryptography.X509Certificates System.Security.Permissions System.Security.Policy System.Security.Principal System.Text System.Threading System.Web System.Web.Caching System.Web.Configuration System.Web.Handlers System.Web.Hosting System.Web.Mail System.Web.Security System.Web.SessionState System.Web.UI System.Web.UI.HtmlControls System.Web.UI.WebControls System.Web.Util System.Xml

In the web.config file, within the configSections tags, we have added the name ClassBrowser and specified the type of information that it will contain. Thereafter, all the data is inserted within the ClassBrowser tag. The data within this tag is in the key-value pair format. It is always

a good idea to store all the data in a file, and then read this file at runtime. How we exploit these key-value pairs, will be substantiated in the ASP+ program, whose explanation follows.

In a.aspx, we commence with the usual suspect, the import namespaces command. An instance variable named ModuleName of type ArrayList is initially created outside all the functions. It is done to enable apportioning and sharing of this type ArrayList by all functions. In our example, this ArrayList will store strings.

In the function Page_Load that gets called at the server end, initially a variable named ConfigSettings is created, which is an instance of a NameValueCollection class. A NameValueCollection class stores the key-value pairs in an efficient way, so that retrieval of the values is more rapid compared to an ArrayList. The principal advantage of this is that we can effectively figure out whether a key-value pair entry already exists or not.

In the aspx file, it is our intention to access all the key-value pairs that are defined within the ClassBrowser tag in the configuration file. The Context property in the Page class, returns an HttpContext object. This Object has a function called GetConfig, whose only task is to return the configuration of the name supplied as a parameter. The Object returned by this function is then cast into a NameValueCollection.

In order to verify that the values have been actually placed, we display the Count member of the NameValueCollection object. We see a value of 3, since we have 3 key-value pairs in the ClassBrowser tag, within the web.config file.

<add key="Data Library" value="System.Data" /> <add key="ASP.NET Class Library" value="System.Web" /> <add key=".NET Framework class Library" value="mscorlib" />

To display the values contained in the web.config file, the for loop is used thrice, to iterate through all the 3 values.

In the loop, we add the variable ModuleName to the ArrayList, with the values retrieved from the web.config file. At the conclusion of the execution of the for loop, the ArrayList contains the names of the 3 modules or dll's, whose details are to be displayed. These details include the namespaces contained in them, the classes in the namespaces, et al. You may recall that, the System.Web.dll contains all the Web classes that we have been working on.

The ArrayList now holds the three module names. Hence, the for loop iterates thrice. The class called Assembly in the namespace System.Reflection has a static function named Load, which accepts the name of a module and loads it into memory. The module gets loaded into the address space of the program that is running this function, and returns an Assembly object that represents the assembly. The function GetModules in the assembly class returns an array of modules that are currently present in the assembly.

In our program, CorRuntime, which is an array variable of type Module, contains the modules in the assembly. An assembly can easily contain more than one module, the first module being the most significant, at the moment. This module object returns the number of types using the GetTypes function. We store the types in the CorClasses array variable of type Types. Thus, the hierarchy is assembly, modules and then, types.

The output very unambiguously conveys to us the following:

System.Web assembly has 1 module and 663 types. System.Data assembly has 1 module and 427 types. mscorlib has 1 module and 1410 types.

Within the for loop, we add one more for loop for every type, because we intend to include all the unique namespaces from the assemblies in the ArrayList called NameSpaceList. The crucial word in the above statement is 'unique'. The Add function in HashTable and ArrayList is used to add the namespace in NameSpaceHash and the NameSpaceList object respectively. If we stop at this stage, the list will contain duplicate Namespaces. Hence, we first employ the ContainsKey function to check whether the namespace is already added or not. If it does, then the namespaces are not added again. ContainsKey returns true if a name already exists. The property IsPublic is employed to discover whether the type of the namespace is public or not.

Thus, namespaces marked public in the assembly, are added only if they don't already exist in the list. The Type class has a member called Namespace that returns the namespace that the type belongs to. A type is a synonym for a class or interface, etc.

The array list is then sorted and assigned to the DataSource member of the DataList called Namespace1. Finally, using the DataBind function, a list of namespaces is displayed.

In our presentation logic, our DataList Namespace1 now contains a list of namespaces. The template is executed for each item in the DataList. However, the template named headertemplate is executed only once, thereby, showing the word Namespaces only once in the window. It is the template named itemtemplate that is called thrice. The HyperLink tag displays the namespaces like a URL. A URL is generated each time we click on a link. This URL is decided by the NavigateUrl property and looks like http://localhost/a.aspx?namespace=Microsoft.Win32 . This is so because the Container.DataItem contains the namespace name that we clicked on, and the ?namespace is given as a literal. The Text property displays the name of the namespace. Also, the items that we have selected in the past, will be displayed as per the template named selecteditemtemplate. This template displays the namespace name in a bold tag.

Let us proceed to the next example, where we propose to display a list of classes belonging to the namespace.

a.aspx <%@ Import NameSpace="System.Collections" %> <%@ Import NameSpace="System.Reflection" %> <html> <head> <script runat="server" language="C#"> public String SelectedNameSpace; public ArrayList ModuleName = new ArrayList();

void Page_Load(Object Sender, EventArgs e) { NameValueCollection ConfigSettings = new NameValueCollection(); ConfigSettings = (NameValueCollection)Context.GetConfig("system.web/ClassBrowser");

for (int i = 0; i < ConfigSettings.Count; i++) { ModuleName.Add(ConfigSettings[i].ToString()); } DisplayNamespaces(); if (Request.QueryString["namespace"] == null) SelectedNameSpace = "System"; else SelectedNameSpace = Request.QueryString["namespace"]; if (Request.QueryString["class"] != null) DisplayClass(Request.QueryString["class"]); else DisplayClassList(SelectedNameSpace); } private void DisplayNamespaces() { ArrayList NameSpaceList = new ArrayList(); Hashtable NameSpaceHash = new Hashtable();

for (int y = 0; y < ModuleName.Count; y++) { Module[] CorRuntime = Assembly.Load(ModuleName[y].ToString()).GetModules(); Type[] CorClasses = CorRuntime[0].GetTypes(); for( int x=0; x < CorClasses.Length; x++ ) { if ( CorClasses[x].Namespace != null ) { if (!NameSpaceHash.ContainsKey(CorClasses[x].Namespace) && CorClasses[x].IsPublic ) { NameSpaceHash.Add(CorClasses[x].Namespace,""); NameSpaceList.Add(CorClasses[x].Namespace); } } } } NameSpaceList.Sort(); Namespace1.DataSource = NameSpaceList; Namespace1.DataBind(); } private void DisplayClassList (String CurrentNameSpace) { ArrayList ClassList = new ArrayList();

ArrayList InterfaceList = new ArrayList(); for( int y=0; y < ModuleName.Count; y++ ) { Module[] CorRuntime = Assembly.Load(ModuleName[y].ToString()).GetModules();

Type[] CorClasses = CorRuntime[0].GetTypes(); for (int x=0; x < CorClasses.Length; x++ ) { if ( CorClasses[x].Namespace == CurrentNameSpace && CorClasses[x].IsPublic) { if ( CorClasses[x].IsInterface ) InterfaceList.Add(CorClasses[x].Name); else ClassList.Add(CorClasses[x].Name); } } } if (InterfaceList.Count > 0) IHeader.Visible = true; if (ClassList.Count > 0) CHeader.Visible = true; ClassList.Sort(); Classes.DataSource = ClassList; Classes.DataBind(); InterfaceList.Sort(); Interfaces.DataSource = InterfaceList; Interfaces.DataBind(); } private void DisplayClass(String className) {

} public String GetUrl(Hashtable table) { return "a.aspx?namespace=" + table["Namespace"] + "&class=" + table["GetType"]; } </script> </head> <body> <form runat="server"> <table> <td width=25% bgcolor=#CCCCFF valign=top > <br> <asp:DataList runat=server id="Namespace1" RepeatLayOut="flow"> <headertemplate> Namespaces <br> </headertemplate> <itemtemplate> <asp:HyperLink runat="server" text=<%# Container.DataItem %> NavigateUrl=<%# "a.aspx?namespace=" + Container.DataItem %> /> </itemtemplate> <selecteditemtemplate> <b> <asp:HyperLink runat=server text=<%# Container.DataItem %>/> </b> </selecteditemtemplate>

</asp:DataList> <p> <td valign=top > <span runat=server id="CHeader" visible="false" style="text-indent:8"> <b> <font size=4 color=#000666>Classes in <%= SelectedNameSpace %> </b> </font> </span> <asp:DataList EnableViewState="false" runat=server id="Classes" RepeatColumns="3" Gridlines=None borderstyle=none borderwidth=0 > <itemtemplate> <asp:HyperLink runat=server text=<%# Container.DataItem %> NavigateUrl=<%# "a.aspx?namespace=" + SelectedNameSpace + "&class=" + Container.DataItem %> /> </itemtemplate> </asp:DataList> <span runat=server id="IHeader" visible="false" style="text-indent:8"> <b> <font size=4 color=#000666>Interfaces in <%= SelectedNameSpace %> </font> </b> </span> <asp:DataList EnableViewState="false" runat=server id="Interfaces" RepeatColumns="4" Gridlines=None borderstyle=none borderwidth=0 > <itemtemplate>

<asp:HyperLink runat=server text=<%# Container.DataItem %> NavigateUrl=<%# "a.aspx?namespace=" + SelectedNameSpace + "&class=" + Container.DataItem %>/> </itemtemplate> </asp:DataList> </form> </body> </html>

In the above program, two panes are displayed. The pane on the left hand side has a list of namespaces, while the pane on the right hand side contains a list of classes in the Systems namespace. If you click on any of the namespaces, the classes displayed in the right pane will change correspondingly. The URL generated reads as follows: http://localhost/a.aspx?namespace=Microsoft.Win32.

We shall only explain the extra lines of code that have been added to the program, to display in the right pane, only those classes that are contained in a specific namespace.

The DisplayNamespaces function has not been altered. It displays the namespaces contained in the three dlls. Thereafter, we verify if the namespace variable contains any value. Similar to the functioning of Request.QueryString, here also it is assumed that the form is reloaded with the namespace variable containing a value. Since we have loaded the file for the first time, the namespace parameter does not come into existence. Hence, the string variable named SelectedNameSpace is initialized to System. It is for this reason that we see the classes belonging to the System namespace, at startup.

Since we do not have a parameter called class with our URL, the next function to be called is DisplayClassList. This function displays a list of classes belonging to the namespace name, which is currently stored in SelectedNamespace.

In the DisplayClassList function, two ArrayList objects named ClassList and InterfaceList are created. ClassList holds the list of classes and InterfaceList holds the list of interfaces. As

always, we go through the rigmarole of fetching each and every type, just as we did earlier, and then checking whether the class or type belongs to the namespace specified in the parameter named CurrentNameSpace. If it is so, then using the IsInterface property, we determine whether the type is a class or an interface, as follows:

If the IsInterface property returns a value of true, it means that the type is an interface. Hence, it gets added to the InterfaceList. If the IsInterface property returns a value of false, it means that the type is a class. Hence, it gets added to the ClassList.

Once the ArrayLists have been filled up, we determine the number of entries in them, using their Count member. If the value returned by Count in the Interface List is greater than zero, the visible property of a span IHeader is set to true. In this situation, the static text 'Interfaces in' is displayed, followed by the name of the namespace, in a bold format. The same procedure is repeated for the ClassList also. A span is useful when many items have to be placed together, because all of them can be manipulated as a single item.

Finally, we have two more DataList objects named Classes and Interfaces. Their DataSource members are initialized to the list of classes and interfaces stored in the two ArrayList objects named ClassList and InterfaceList, respectively.

Thus, as you can see in the above program, we have created an ArrayList and filled it up with data. Then, we request the DataSource property of some DataList to display it.

The output in the browser should show the namespaces and the list of classes, concurrently. This can be accomplished only by means of a table. So, we have a table tag containing two table columns.

The first table column called td has a background color and occupies 25% of the table width. This ensures that the first DataList is in one column.

In the next td, the names of the classes and the interfaces are displayed side by side.

The template itemtemplate is repeated for all the classes in the DataSource. Each class name is displayed as a hyperlink, and the URL that is required to navigate to it, contains the following:

the file name a.aspx. the name of the namespace. the name of the class given to parameters namespace and class.

http://localhost/a.aspx?namespace=System.Collections&class=ArrayList

The same process is repeated for the interfaces.

Let us now attempt to display the list of functions in a class.

a.aspx <%@ Import NameSpace="ClassInfo" %> <%@ Import NameSpace="System.Collections" %> <%@ Import NameSpace="System.Collections.Specialized" %> <%@ Import NameSpace="System.Reflection" %> <html> <head> <script runat="server" language="C#">

public String SelectedAssembly; public String SelectedNameSpace; public ArrayList ModuleName = new ArrayList(); protected void Page_Load(Object Sender, EventArgs e) { NameValueCollection ConfigSettings = (NameValueCollection)Context.GetConfig("system.web/ClassBrowser"); for (int i = 0; i < ConfigSettings.Count; i++) ModuleName.Add(ConfigSettings[i].ToString()); DisplayNamespaces(); if (Request.QueryString["namespace"] == null) SelectedNameSpace = "System"; else SelectedNameSpace = Request.QueryString["namespace"]; if (Request.QueryString["assembly"] == null ) SelectedAssembly = "mscorlib"; else SelectedAssembly = Request.QueryString["assembly"];

if (Request.QueryString["class"] != null && Request.QueryString["assembly"] != null) DisplayClass(Request.QueryString["assembly"], Request.QueryString["class"]); else DisplayClassList(SelectedNameSpace); } private void DisplayNamespaces() {

ArrayList NameSpaceList = new ArrayList(); Hashtable NameSpaceHash = new Hashtable(); for (int y = 0; y < ModuleName.Count; y++) { Module[] CorRuntime = Assembly.Load(ModuleName[y].ToString()).GetModules(); Type[] CorClasses = CorRuntime[0].GetTypes();

for( int x=0; x < CorClasses.Length; x++ ) { if ( CorClasses[x].Namespace != null ) { if (!NameSpaceHash.ContainsKey(CorClasses[x].Namespace) && CorClasses[x].IsPublic ) { NameSpaceHash.Add(CorClasses[x].Namespace,""); NameSpaceList.Add(CorClasses[x].Namespace); } } } } NameSpaceList.Sort(); Namespace1.DataSource = NameSpaceList; Namespace1.DataBind(); } private void DisplayClassList(String CurrentNameSpace) { ArrayList ClassList = new ArrayList();

ArrayList InterfaceList = new ArrayList();

for( int y=0; y < ModuleName.Count; y++ ) { Module[] CorRuntime = Assembly.Load(ModuleName[y].ToString()).GetModules(); Type[] CorClasses = CorRuntime[0].GetTypes();

for (int x=0; x < CorClasses.Length; x++ ) { if ( CorClasses[x].Namespace == CurrentNameSpace && CorClasses[x].IsPublic) { SortTable props = new SortTable("GetType"); props["GetType"] = CorClasses[x].Name; props["Namespace"] = CorClasses[x].Namespace; props["Assembly"]= CorClasses[x].Assembly.GetName().Name; if ( CorClasses[x].IsInterface ) InterfaceList.Add(props); else ClassList.Add(props); } } } if (InterfaceList.Count > 0) IHeader.Visible = true; if (ClassList.Count > 0) CHeader.Visible = true; ClassList.Sort(); Classes.DataSource = ClassList;

Classes.DataBind(); InterfaceList.Sort(); Interfaces.DataSource = InterfaceList; Interfaces.DataBind(); } private void DisplayClass(String asmName, String className) { Assembly a = Assembly.Load(asmName); Type ClassType = a.GetType(SelectedNameSpace.ToString() + "." + className, false, true); if ( ClassType == null ) { DisplayClassList(SelectedNameSpace); return; } DisplayMethods MethodDetails if(MethodDetails.Count != 0 ) Methods.DataSource = MethodDetails; DataBind(); if (ClassType.IsInterface) spnClassName.InnerHtml = "Interface " + SelectedNameSpace + "." + className; else spnClassName.InnerHtml = "Class " + SelectedNameSpace + "." + className; NameSpacePanel.Visible=false; ClassPanel.Visible=true; } = new DisplayMethods(ClassType, className);

public String GetUrl(Object objTable) { if ( objTable is String ) { return "a.aspx?assembly=" + SelectedAssembly + "&namespace=" + SelectedNameSpace + "&class=" + objTable; } if ( ! (objTable is Hashtable) ) { Response.Write(objTable.GetType().ToString()); Response.End(); } Hashtable table = (Hashtable) objTable; return "a.aspx?assembly=" + table["Assembly"] + "&namespace=" + table["Namespace"] + "&class=" + table["GetType"]; } </script> </head> <body> <form runat="server"> <table> <tr> <td width=25% bgcolor=#CCCCFF valign=top > <br> <asp:DataList EnableViewState="false" runat=server id="Namespace1" RepeatLayOut="flow"> <HeaderTemplate>Namespaces <br> </HeaderTemplate> <ItemTemplate>

<asp:HyperLink runat="server" text=<%# Container.DataItem %> NavigateUrl=<%# "a.aspx?namespace=" + Container.DataItem %> /> </ItemTemplate> <SelectedItemTemplate> <b><asp:HyperLink runat=server text=<%# Container.DataItem %>/></b> </SelectedItemTemplate> </asp:DataList> <p> </td> <td valign=top > <div id="ClassPanel" style="margin-top:15;margin-left:10" visible="false" runat="server"> <b><font size=4 color="000666"><span style="text-indent:8" id="spnClassName" EnableViewState="false" runat="server"/></font></b> </div> <div id="NameSpacePanel" runat="server"> <table class="main" width=100%> <tr> <td class="main_header"> <span runat=server id="CHeader" visible="false" style="text-indent:8"> <b><font size=4 color=#000666>Classes in <%= SelectedNameSpace %> </b> </font></span> </td> </tr> <tr> <td align="left"> <asp:DataList EnableViewState="false" runat=server id="Classes" RepeatColumns="3" Gridlines=None borderstyle=none borderwidth=0>

<ItemTemplate> <asp:HyperLink runat=server text=<%# ((SortTable) Container.DataItem)["GetType"] %> NavigateUrl=<%# GetUrl(Container.DataItem) %> /> </ItemTemplate> </asp:DataList> </td> </tr> </table> <table class="main" width=100% > <tr> <td class="main_header" > <span runat=server id="IHeader" visible="false" style="text-indent:8"> <b> <font size=4 color=#000666>Interfaces in <% =SelectedNameSpace %> </font> </b> </span> </td> </tr> <tr> <td align="left"> <asp:DataList EnableViewState="false" runat=server id="Interfaces" RepeatColumns="4" Gridlines=None borderstyle=none borderwidth=0> <ItemTemplate> <asp:HyperLink runat=server text=<%# ((SortTable) Container.DataItem)["GetType"] %> NavigateUrl=<%# GetUrl(Container.DataItem) %>/> </ItemTemplate> </asp:DataList> </td>

</tr> </table> </div> <p> <asp:DataList EnableViewState="false" id="Methods" runat="server" Gridlines=None borderstyle="none" borderwidth="0" width="100%"> <HeaderTemplate> <table cellspacing=0 > <tr><td class="class_header"><b><font size=2> Methods </font></b></td></tr> <tr bgcolor="eeeeee"> <td width="75" ><b><u>Visibility</td> <td width="100"><b><u>Return </td> <td width="100"><b><u>Name</td> <td width="600"><b><u>Parameters</td> </tr> </HeaderTemplate> <ItemTemplate> <tr bgcolor="eeeeee"> <td width="75"><nobr><span runat=server InnerHtml=<%# ((SortTable) Container.DataItem)["Access"]%> /></nobr></td> <td width="100"> <asp:HyperLink runat=server NavigateUrl=<%# GetUrl(Container.DataItem) %> text=<%# ((SortTable) Container.DataItem)["Type"]%>/> </td>

<td width="100"><span runat=server InnerHtml=<%# ((SortTable) Container.DataItem)["Name"]%>/></td> <td width="900"> <asp:DataList EnableViewState="false" runat=server datasource=<%# ((SortTable) Container.DataItem)["Params"] %> RepeatLayout=Flow RepeatDirection="Horizontal" showfooter=true > <HeaderTemplate> ( </HeaderTemplate> <ItemTemplate> <asp:HyperLink text=<%# ((SortTable) Container.DataItem)["ParamType"].ToString() %> NavigateUrl=<%# GetUrl(Container.DataItem) %> runat=server /> <span InnerHtml=<%# ((SortTable) Container.DataItem)["ParamName"] %> runat=server /> </ItemTemplate> <SeparatorTemplate> ,</SeparatorTemplate> <FooterTemplate> ) </FooterTemplate> </asp:DataList> </td> </tr> </ItemTemplate> <FooterTemplate> </table> </FooterTemplate> </asp:DataList>

<p><p> <asp:DataList EnableViewState="false" id="Interface1" runat=server style="margin-left:10" RepeatDirection="horizontal" RepeatLayout="Flow" width="100%"> <HeaderTemplate> <font size=2><b> Implements </b></font> <br> </HeaderTemplate> <ItemTemplate> <asp:HyperLink runat=server NavigateUrl=<%# GetUrl(Container.DataItem) %> text=<%# ((SortTable) Container.DataItem)["FullName"]%> /> </ItemTemplate> <SeparatorTemplate> <font face="Verdana" style="font-size:8pt">, </SeparatorTemplate> </asp:DataList> <p> <p> </td> </tr> </table> </td> </tr> </table> </form>

</body> </html>

b.cs using System ; using System.Web; using System.Web.UI; using System.Collections; using System.Reflection; namespace ClassInfo { public class SortTable : Hashtable, IComparable { public String sortField; public SortTable() : this(null) { } public SortTable(String sField) { sortField = sField; } public int CompareTo(Object b) { if ( sortField == null ) { return 0; } return ((String)this[sortField]).CompareTo((String)((SortTable)b)[sortField]); }

} public class DisplayMethods : ArrayList { public DisplayMethods(Type classType, String myclassname) { System.Reflection.MethodInfo[] methodInfos = classType.GetMethods() ; if (methodInfos == null) return; for (int x=0; x<methodInfos.Length; x++) { if((String.Compare(myclassname,methodInfos[x].DeclaringType.Name )==0)&&(methodInfos[x].IsPublic || methodInfos[x].IsFamily) && (!(methodInfos[x].IsSpecialName)) ) { SortTable MethodDetails = new SortTable("Name"); MethodDetails["Assembly"] = methodInfos[x].GetType().Assembly.GetName().Name; MethodDetails["Name"] = methodInfos[x].Name; MethodDetails["Type"] = methodInfos[x].ReturnType.Name; if(( methodInfos[x].ReturnType.IsArray && methodInfos[x].ReturnType.Name !="Array") || methodInfos[x].ReturnType.IsPointer) { Type ReturnElementType = methodInfos[x].ReturnType.GetElementType(); while(ReturnElementType.IsArray) { ReturnElementType = ReturnElementType.GetElementType(); } MethodDetails["GetType"] = ReturnElementType.Name ; MethodDetails["Namespace"] = ReturnElementType.Namespace ; } else { MethodDetails["GetType"] = methodInfos[x].ReturnType.Name; MethodDetails["Namespace"] = methodInfos[x].ReturnType.Namespace ;

} if (methodInfos[x].IsPublic == true) { MethodDetails["Access"] = "public "; } else if (methodInfos[x].IsPrivate == true) { MethodDetails["Access"] = "private "; } else if (methodInfos[x].IsFamily == true) { MethodDetails["Access"] = "protected "; } if (methodInfos[x].IsStatic == true) { MethodDetails["Access"] = ((String) MethodDetails["Access"]) + "static "; } System.Reflection.ParameterInfo[] paramInfos = methodInfos[x].GetParameters(); if (paramInfos != null) { ArrayList paramTable = new ArrayList(); for (int y=0; y<paramInfos.Length; y++) { SortTable paramDetails = new SortTable(); paramDetails["Assembly"] = paramInfos[y].GetType().Assembly.GetName().Name; paramDetails["ParamName"] = paramInfos[y].Name; paramDetails["ParamType"] = paramInfos[y].ParameterType.Name; if(( paramInfos[y].ParameterType.IsArray && paramInfos[y].ParameterType.Name != "Array" ) || paramInfos[y].ParameterType.IsPointer) { paramDetails["GetType"] = paramInfos[y].ParameterType.GetElementType().Name ; paramDetails["Namespace"] = paramInfos[y].ParameterType.GetElementType().Namespace ; } else {

paramDetails["GetType"] = paramInfos[y].ParameterType.Name; paramDetails["Namespace"] = paramInfos[y].ParameterType.Namespace ; } paramTable.Add(paramDetails); } MethodDetails["Params"] = paramTable; } this.Add(MethodDetails); } } this.Sort(); } } }

To run the above program, you need to first place the file b.cs in the sub-directory c:\inetpub\wwwroot\bin and compile it as follows:

>csc /target:library b.cs When a.aspx is loaded in the browser, the list of namespaces is displayed on the left, and the list of classes belonging to the System namespace is seen on the right. If you click on any class, a list of functions belonging to that class will be displayed. The data is displayed in a tabular format in four columns.

The first column represents the visibility. The values contained in it, are either public, or private or protected.

The second column indicates the return data type. The third column displays the names of the functions. The fourth column holds the parameters with their names and data types.

All types are hyper linked, so when we click on any one of them, a screen comes forth, displaying the functions or methods that the specified type supports.

When we click on the name of a class, the following URL gets generated:

http://localhost/a.aspx?assembly=mscorlib&namespace=System&class=Exception

The Page_Load function calls the DisplayClass function, since the class and the assembly parameter contains a value. This proves that the DisplayClassList function is called only in the first round, while loading the page.

In the DisplayClass function, we first need the type of the object. The static function called GetType, belonging to the Type class, returns a type when it is supplied with the full name of the class. So, we concatenate the namespace name stored in the instance variable SelectedNameSpace, with the parameter className, and then pass the full name to this function. The Type returned by the GetType function is stored in a variable called ClassType.

Next, we create an object called MethodDetails of type DisplayMethods, which requires two parameters, the Type and the className. DisplayMethods is, in turn, derived from the class ArrayList. The ArrayList object named MethodDetails, obviously contains the details about the methods. Using the Count member, we can determine the total number of methods in the class. If the value returned is greater than 0, we initialize the DataSource member called Methods, of the DataList, to this ArrayList. The span control called spnClassName, then displays the name of the namespace and that of the class.

We have two div tags having the ids ClassPanel and NameSpacePanel. Their visible property is set to either true or false, thereby, ensuring that all the div contents are either displayed or hidden

from view. In the DisplayClass, we have hidden the data contained within these tags by setting the Visible property to false. Thus, in one stroke, we can conceal or reveal a large number of entities. These tags are extremely useful because our browser's real estate is restricted, and we do not have the space to display everything.

Let us now scrutinize the presentation logic. As we mentioned earlier, the DataList called Methods displays all the method names neatly formatted. You may have been ambushed by the revelation that a simple DataList was able to display everything. The template named headertemplate is called once, to display the four column headers of the table. The table tag does not end with the template, as each method is now displayed as a table row. The bold and underline tags have been provided to produce visually stunning output.

The DisplayMethods class uses the indexer method to retrieve the values of the Visible and Type members. Thus, in the span tag, we use the array syntax to display the Access and Type members. The function GetUrl navigates to the relevant type by creating a URL, followed by the parameters called assembly, namespace and class, filled up with relevant values. From the browser's point of view, it does not make any difference whether we click on the class name in the first screen or in the second one.

Life is not very straightforward now, since we have made an endeavor to display the parameters of the method, which could number from nil to infinity. In order to achieve this, we create another DataList within the Methods DataList and initialize the DataSource parameter to the Params value in the DisplayMethods object. To display the parameters, a template with a hyper link is utilized. It shows the data type or ParamType as a hyperlink. The URL to this link is generated by the GetUrl function. The ParamName is displayed as normal text.

The whole code is enclosed in open and close brackets, and is available in the headertemplate and footertemplate. The template named separatortemplate supplies the commas to separate the individual parameter names and values. To summarize, we are using a nested DataList to display an array of values within another array.

We have a confession to make at this juncture. The class named DisplayMethods has not been supplied by Microsoft. It is created in the file b.cs. This class is derived from ArrayList and gives us all the details of every method that exists in a type.

Let us now focus on the class DisplayMethods in the file b.cs. This is a perfect example of a two-tier illustration, where the presentation logic is placed in one file, and the C# code that handles Reflection, is placed in another file.

The class DisplayMethods has to extend the ArrayList class, because in the aspx file, we are initializing the DataSource member of the Methods DataList to this data type. Also, the constructor in the DisplayClass function has been supplied with two parameters, namely, the Type and className.

DisplayMethods MethodDetails= new DisplayMethods(ClassType, className);

There exists a static method called GetMethods in the Type class, that returns a MethodInfo array. The methodInfos array reveals every aspect of the function. No parameter is supplied indicating that the default rules are to be applied when locating a function. In case there are no methods available in a class, a null value is stored in the array variable.

The Length member of the array stores a count of the number of methods contained in the array. Thereafter, using a for loop we iterate through each and every method. A 'foreach' loop could also be used to achieve the same functionality. In the loop, we use a Compare function of the String class, to verify the validity of the method. The property DeclaringType returns a Type or the class that consists of this method. Type in turn, has a property called Name, that represents the name of the class. Compare takes this name and checks it with the parameter myclassname, which is a parameter passed to the constructor. It is just an additional check.

We also ensure that the method is public or it belongs to the family (current of derived class) that can access it. The compiler treats functions that possess special names, differently. For example, the constructor is given a special name, i.e. .ctor. These methods are not to be included in our list of methods, and hence, the ! sign is used. The method must successfully pass all the above conditions, or else, it will not be incorporated as a part of the methods list that is returned.

On passing the above test, the next task is to gain access to the template in the aspx file. To accomplish this, an indexer or an array is employed. It returns an object that is an instance of a Hashtable. For the ones who walked in late, the Hashtable class lets us access data in an efficient manner, and also offers us an indexer support.

MethodDetails is an instance of the SortTable class, which consecutively extends the class Hashtable. The single parameter constructor of the SortTable is called using the Name parameter. The constructor stores the value contained in the Name variable, in a public variable called sortField. Thereafter, using the indexer features of the Hashtable class, the following is achieved:

The name of the assembly is stored in an indexer variable called Assembly. The name of the method is stored in an indexer variable called Name. The name of the return type is stored in the indexer variable called Type.

The name of the return type or class is obtained as follows: The MethodInfo class has a property called ReturnType that returns the Type of the return value. The Type in turn, has a member called Name that holds the name of the Type.

There are instances where a multi-dimension array or a pointer is returned. These being exceptional cases, separate 'if 'statements are required to handle them. First, using the property IsArray, the name property in ReturnType is checked. If the name contains the word 'Array' or the ReturnType is a pointer, we can safely conclude that the function returns a MultiDimensional array. So, we use the function GetElementType in ReturnType, to return the Type of the object encompassed, or referenced by either an array, or a pointer, or by ByRef.

The predicament with arrays is that their dimensions could range from 2 to infinity, which could put us in a tight spot. To tide over this situation, we use a loop construct like a while or a for loop. Thus, using IsArray, we keep looping, until the Type becomes an array. All arrays, multidimensional or otherwise, have a Type name. Ignoring the fact that it is an array, we initialize the indexer variable GetType to this Type name, and initialize the namespace variable to the namespace of this type. This course of action is essential if we aspire to display the final data type of the array.

Under normal circumstances, the return type is generally a Type object. In such cases, we can use the same Name and Namespace properties to retrieve its value and store it in the MethodDetail Indexer.

The next task in sequence is to store the access modifiers, which our function has been tagged with. We intend to determine whether the method is public, private or protected. To achieve this, we use the three properties named, IsPublic, IsPrivate and IsFamily. Accordingly, the relevant access modifier is stored in the indexer variable called Access. The function is also checked to establish if it is static. To accomplish this, the property IsStatic is used. If it returns a value of true, the string static is added to the Access indexer variable.

Now, we have arrived at a relatively uncomplicated part. The names and the data types of the parameters have to be retrieved. The number of parameters to a function can range from zero to infinity. We initialize an object called paramInfos by calling the GetParameters function, which returns a ParameterInfo array. A separate ArrayList is now required to store this variable set of data. So, we create a separate ArrayList object called paramTable, which stores certain information about the parameters, such as the name and type.

Depending upon the length of the array, the loop is repeated a specific number of times, wherein, the Name property of a ParameterInfo object, is assigned to an indexer variable called ParamName. The ParameterInfo class also contains a property called ParameterType, whose Type member holds the name of the Type. Thereafter, as before, we check if the return type is a Multi-dimensional array. If so, the final type of the Multi-Dimensional array is figured out. Eventually, the GetType and Namespace are initialized from the normal types of the multidimensional arrays, to the return type of the function and the namespace of the type, respectively. Thereafter, this single record of paramDetails is added to the paramTable ArrayList. This loop is repeated for every method in the class. Once the loop terminates, the indexer variable Params in MethodDetails, is initialized to the paramTable object.

Finally, the MethodDetails is added to the ArrayList and the ArrayList is sorted. Sortng of the list is not obligatory.

To recapitulate, the MethodDetails class consists of multiple records that can be accessed through an indexer, using parameter names like GetType and Namespace. The Params parameter

in the MethodDetail indexer is made up of another ArrayList, and has members like ParamName and ParamType.

The interface IComparable attains significance because it contains the CompareTo function from the string class.

Now, for the grand finale! We shall delve upon the class browser application from the Microsoft Samples.

web.config <configuration> <configSections> <sectionGroup name="system.web"> <section name="ClassBrowser" type="System.Configuration.NameValueSectionHandler,System"/> </sectionGroup> </configSections> <system.web> <ClassBrowser> <add key="WinForms Library" value="System.Windows.Forms" /> <add key="Drawing Library" value="System.Drawing" /> <add key="Data Library" value="System.Data" /> <add key="Xml Library" value="System.Xml" /> <add key="Messaging Library" value="System.Messaging" />

<add key="Directory Services Library" value="System.DirectoryServices" /> <add key="ASP.NET Class Library" value="System.Web" /> <add key=".NET Framework class Library" value="mscorlib" /> </ClassBrowser> </system.web> </configuration>

a.aspx <%@ Page Language="C#" Debug="True" %> <%@ Import NameSpace="ClassInfo" %> <%@ Import NameSpace="System.Collections" %> <%@ Import NameSpace="System.Collections.Specialized" %> <%@ Import NameSpace="System.Reflection" %> <html><head> <script runat="server" language="C#"> public String SelectedAssembly; public String SelectedNameSpace; public ArrayList ModuleName = new ArrayList(); protected void Page_Load(Object Sender, EventArgs e) { NameValueCollection ConfigSettings = (NameValueCollection)Context.GetConfig("system.web/ClassBrowser"); for (int i = 0; i < ConfigSettings.Count; i++) { ModuleName.Add(ConfigSettings[i].ToString()); }

DisplayNamespaces(); if (Request.QueryString["namespace"] == null) SelectedNameSpace = "System"; else SelectedNameSpace = Request.QueryString["namespace"];

if (Request.QueryString["assembly"] == null ) SelectedAssembly = "mscorlib"; else SelectedAssembly = Request.QueryString["assembly"]; if (Request.QueryString["class"] != null && Request.QueryString["assembly"] != null) DisplayClass(Request.QueryString["assembly"], Request.QueryString["class"]); else DisplayClassList(SelectedNameSpace); } private void DisplayNamespaces() { ArrayList NameSpaceList = new ArrayList(); Hashtable NameSpaceHash = new Hashtable(); for (int y = 0; y < ModuleName.Count; y++) { Module[] CorRuntime = Assembly.Load(ModuleName[y].ToString()).GetModules(); Type[] CorClasses = CorRuntime[0].GetTypes();

for( int x=0; x < CorClasses.Length; x++ ) { if ( CorClasses[x].Namespace != null ) {

if (!NameSpaceHash.ContainsKey(CorClasses[x].Namespace) && CorClasses[x].IsPublic ) { NameSpaceHash.Add(CorClasses[x].Namespace,""); NameSpaceList.Add(CorClasses[x].Namespace); } } } } NameSpaceList.Sort(); Namespace1.DataSource = NameSpaceList; Namespace1.DataBind(); } private void DisplayClassList(String CurrentNameSpace) { ArrayList ClassList = new ArrayList();

ArrayList InterfaceList = new ArrayList(); for( int y=0; y < ModuleName.Count; y++ ) { Module[] CorRuntime = Assembly.Load(ModuleName[y].ToString()).GetModules(); Type[] CorClasses = CorRuntime[0].GetTypes();

for (int x=0; x < CorClasses.Length; x++ ) { if ( CorClasses[x].Namespace == CurrentNameSpace && CorClasses[x].IsPublic) { SortTable props = new SortTable("GetType"); props["GetType"] = CorClasses[x].Name; props["Namespace"] = CorClasses[x].Namespace; props["Assembly"] = CorClasses[x].Assembly.GetName().Name;

if ( CorClasses[x].IsInterface ) InterfaceList.Add(props); else ClassList.Add(props); } } }

if (InterfaceList.Count > 0) IHeader.Visible = true;

if (ClassList.Count > 0) CHeader.Visible = true;

ClassList.Sort(); Classes.DataSource = ClassList; Classes.DataBind();

InterfaceList.Sort(); Interfaces.DataSource = InterfaceList; Interfaces.DataBind(); }

private void DisplayClass(String asmName, String className) {

Assembly a = Assembly.Load(asmName); Type ClassType = a.GetType(SelectedNameSpace.ToString() + "." + className, false, true); if ( ClassType == null ) { DisplayClassList(SelectedNameSpace); return; } ArrayList SubClassDetails = new DisplaySubClasses(ClassType, ModuleName); DisplayConstructors ConstructorDetails = new DisplayConstructors(ClassType); DisplayFields DisplayProperties DisplayMethods FieldDetails = new DisplayFields(ClassType); = new DisplayProperties(ClassType); = new DisplayMethods(ClassType, className);

PropertyDetails MethodDetails

DisplaySuperclasses SuperClassDetails = new DisplaySuperclasses(ClassType); DisplayInterfaces DisplayEvents InterfaceDetails = new DisplayInterfaces(ClassType); EventDetails = new DisplayEvents(ClassType);

if(ConstructorDetails.Count != 0 ) Constructors.DataSource = ConstructorDetails; if(SubClassDetails.Count != 0 ) SubClasses.DataSource = SubClassDetails; if(FieldDetails.Count != 0 ) Fields.DataSource = FieldDetails;

if(PropertyDetails.Count != 0 ) Properties.DataSource = PropertyDetails; if(MethodDetails.Count != 0 ) Methods.DataSource = MethodDetails; if(InterfaceDetails.Count != 0 ) Interface1.DataSource = InterfaceDetails; if(SuperClassDetails.Count != 0 ) SuperClasses.DataSource = SuperClassDetails; if(EventDetails.Count != 0 ) Events.DataSource = EventDetails; DataBind(); if (ClassType.IsInterface) spnClassName.InnerHtml = "Interface " + SelectedNameSpace + "." + className; else spnClassName.InnerHtml = "Class " + SelectedNameSpace + "." + className; NameSpacePanel.Visible=false; ClassPanel.Visible=true; }

public String GetUrl(Object objTable) { if ( objTable is String ) { return "a.aspx?assembly=" + SelectedAssembly + "&namespace=" + SelectedNameSpace + "&class=" + objTable; }

if ( ! (objTable is Hashtable) ) { Response.Write(objTable.GetType().ToString()); Response.End(); } Hashtable table = (Hashtable) objTable; return "a.aspx?assembly=" + table["Assembly"] + "&namespace=" + table["Namespace"] + "&class=" + table["GetType"]; } </script> </head> <body> <form runat="server"> <table width=100% height=700 cellpadding=0 cellspacing=0> <tr> <td width=25% bgcolor=#CCCCFF valign=top > <br> <asp:DataList EnableViewState="false" runat=server id="Namespace1" RepeatLayOut="flow" ItemStyle-Font-Size="9pt" HeaderStyle-Font-Size="12pt" > <HeaderTemplate> <div left-margin="10"> Namespaces <br> </HeaderTemplate> <ItemTemplate> <asp:HyperLink runat="server" text=<%# Container.DataItem %> NavigateUrl=<%# "a.aspx?namespace=" + Container.DataItem %> /> </ItemTemplate> <SelectedItemTemplate>

<b><asp:HyperLink runat=server text=<%# Container.DataItem %>/></b> </SelectedItemTemplate> </asp:DataList> <p> </td> <td valign=top > <div id="ClassPanel" style="margin-top:15;margin-left:10" visible="false" runat="server"> <b><font size=4 color="000666"><span style="text-indent:8" id="spnClassName" EnableViewState="false" runat="server"/></font></b> </div> <div id="NameSpacePanel" runat="server"> <table class="main" width=100%> <tr> <td class="main_header"> <span runat=server id="CHeader" visible="false" style="text-indent:8"> <b><font size=4 color=#000666>Classes in <%= SelectedNameSpace %> </b> </font></span> </td> </tr> <tr> <td align="left"> <asp:DataList EnableViewState="false" runat=server id="Classes" RepeatColumns="3" Gridlines=None borderstyle=none borderwidth=0 > <ItemTemplate> <asp:HyperLink runat=server text=<%# ((SortTable) Container.DataItem)["GetType"] %> NavigateUrl=<%# GetUrl(Container.DataItem) %> /> </ItemTemplate>

</asp:DataList> </td> </tr> </table> <table class="main" width=100% > <tr> <td class="main_header" > <span runat=server id="IHeader" visible="false" style="text-indent:8"> <b><font size=4 color=#000666>Interfaces in <%= SelectedNameSpace %> </font> </b> </span> </td> </tr> <tr> <td align="left"> <asp:DataList EnableViewState="false" runat=server id="Interfaces" RepeatColumns="4" Gridlines=None borderstyle=none borderwidth=0 > <ItemTemplate> <asp:HyperLink runat=server text=<%# ((SortTable) Container.DataItem)["GetType"] %> NavigateUrl=<%# GetUrl(Container.DataItem) %>/> </ItemTemplate> </asp:DataList> </td> </tr> </table>

</div>

<table class="main" width=100% cellpadding=0 cellspacing=0 > <tr> <td class="main_header" valign="top" > <asp:DataList EnableViewState="false" id="Constructors" runat="server" Gridlines=None borderstyle="none" borderwidth=0 width="100%"> <HeaderTemplate> <table cellspacing=0 width="100%"> <tr><td class="class_header"><b><font size=2> Constructors </font></b></td></tr> <tr bgcolor="eeeeee"> <td width="75" > <b><u> Visibility <td width="100"> <b><u> Constructor <td> <b><u> Parameters </tr> </HeaderTemplate> </u> </td> </u> </td> </u> </td>

<ItemTemplate> <tr bgcolor="eeeeee"> <td width="75"> <span runat=server InnerHtml=<%# ((SortTable) Container.DataItem)["Access"] %> /> </td>

<td width="100"> <span runat=server InnerHtml =<%# ((SortTable) Container.DataItem)["Name"] %> /> </td> <td width="1000"> <asp:DataList EnableViewState="false" runat=server RepeatDirection="Horizontal" RepeatLayout=Flow showfooter=true datasource=<%# ((SortTable) Container.DataItem)["Params"]%> > <HeaderTemplate> ( </HeaderTemplate> <ItemTemplate> <asp:HyperLink text=<%# ((SortTable) Container.DataItem)["ParamType"] %> NavigateUrl=<%# GetUrl(Container.DataItem) %> runat=server /> <span innerhtml=<%# ((SortTable) Container.DataItem)["ParamName"] %> runat=server /> </ItemTemplate> <SeparatorTemplate>, </SeparatorTemplate> <FooterTemplate> ) </FooterTemplate> </asp:DataList> </td> </tr> </ItemTemplate> <FooterTemplate>

</table> </FooterTemplate> </asp:DataList> <p> <asp:DataList EnableViewState="false" id="Fields" runat="server" Gridlines=None BorderStyle="none" width="100%" BorderWidth=0> <HeaderTemplate> <table cellspacing=0 width="100%"> <tr><td class="class_header"><b><font size=2> Fields </font></b></td></tr> <tr bgcolor="eeeeee"> <td width="120" ><b><u> Visibility </td> <td width="100"><b><u> Type <td ><b><u> Name </tr> </HeaderTemplate> <ItemTemplate> <tr bgcolor="eeeeee"> <td width="120"> <nobr><span InnerHTML=<%# ((SortTable) Container.DataItem)["Access"]%> runat=server /></nobr> </td> <td width="100"> <asp:HyperLink text=<%# ((SortTable) Container.DataItem)["Type"] %> NavigateUrl=<%# GetUrl(Container.DataItem) %> runat=server/> </td> <td> </td> </td>

<span InnerHTML=<%# ((SortTable) Container.DataItem)["Name"] %> runat=server /> </td> </tr> </ItemTemplate> <FooterTemplate> </table> </FooterTemplate> </asp:DataList> <p> <asp:DataList EnableViewState="false" id="Events" runat="server" Gridlines=None BorderStyle="none" width="100%" BorderWidth=0> <HeaderTemplate> <table cellspacing=0 width="100%"> <tr><td class="class_header"><b><font size=2> Events </font></b></td></tr> <tr bgcolor="eeeeee"> <td width="120" ><b><u> Multicast </td> <td width="100"><b><u> Type <td ><b><u> Name </tr> </HeaderTemplate> <ItemTemplate> <tr bgcolor="eeeeee"> <td width="120"> </td> </td>

<nobr><span InnerHTML=<%# ((SortTable) Container.DataItem)["Access"]%> runat=server /></nobr> </td> <td width="100"> <asp:HyperLink text=<%# ((SortTable) Container.DataItem)["Type"] %> NavigateUrl=<%# GetUrl(Container.DataItem) %> runat=server/> </td> <td> <span InnerHTML=<%# ((SortTable) Container.DataItem)["Name"] %> runat=server /> </td> </tr> </ItemTemplate> <FooterTemplate> </table> </FooterTemplate> </asp:DataList> <p> <asp:DataList EnableViewState="false" id="Properties" runat="server" Gridlines=None BorderStyle="none" BorderWidth=0 width="100%"> <HeaderTemplate> <table cellspacing=0 width="100%" > <tr><td class="class_header"><b><font size=2> Properties </font></b></td></tr> <tr bgcolor="eeeeee"> <td width="75"><b><u>Visibility</td> <td width="100"><b><u>Type</td>

<td width="150"><b><u>Name</td> <td><b><u>Accessibility</td> </tr> </HeaderTemplate> <ItemTemplate> <tr bgcolor="eeeeee"> <td width="75"><span InnerHTML=<%# ((SortTable) Container.DataItem)["Visibility"] %> runat=server /> </td> <td width="100"> <asp:HyperLink runat=server runat="server" text=<%# ((SortTable) Container.DataItem)["Type"] %> NavigateUrl=<%# GetUrl(Container.DataItem) %>/> </td> <td width="150"><span InnerHTML=<%# ((SortTable) Container.DataItem)["Name"]%> runat=server/> <asp:DataList EnableViewState="false" runat=server RepeatLayout="Flow" ShowFooter=true RepeatDirection="Horizontal" datasource=<%# ((SortTable) Container.DataItem)["Params"] %>> <ItemTemplate> ( <asp:HyperLink runat=server text=<%# ((SortTable) Container.DataItem)["ParamType"]%> NavigateUrl=<%# GetUrl(Container.DataItem) %> /> <span InnerHtml=<%# ((SortTable) Container.DataItem)["ParamName"] %> runat=server /> ) </ItemTemplate> </asp:DataList> </td><td><span InnerHTML=<%# ((SortTable) Container.DataItem)["Access"]%> runat=server/></td> </tr> </ItemTemplate> <FooterTemplate>

</table> </FooterTemplate> </asp:DataList> <p> <asp:DataList EnableViewState="false" id="Methods" runat="server" Gridlines=None borderstyle="none" borderwidth="0" width="100%"> <HeaderTemplate> <table cellspacing=0 > <tr><td class="class_header"><b><font size=2> Methods </font></b></td></tr> <tr bgcolor="eeeeee"> <td width="75" ><b><u>Visibility</td> <td width="100"><b><u>Return </td> <td width="100"><b><u>Name</td> <td width="600"><b><u>Parameters</td> </tr> </HeaderTemplate> <ItemTemplate> <tr bgcolor="eeeeee"> <td width="75"><nobr><span runat=server InnerHtml=<%# ((SortTable) Container.DataItem)["Access"]%> /></nobr></td> <td width="100"> <asp:HyperLink runat=server NavigateUrl=<%# GetUrl(Container.DataItem) %> text=<%# ((SortTable) Container.DataItem)["Type"]%>/> </td>

<td width="100"><span runat=server InnerHtml=<%# ((SortTable) Container.DataItem)["Name"]%>/></td> <td width="900"> <asp:DataList EnableViewState="false" runat=server datasource=<%# ((SortTable) Container.DataItem)["Params"] %> RepeatLayout=Flow RepeatDirection="Horizontal" showfooter=true > <HeaderTemplate> ( </HeaderTemplate> <ItemTemplate> <asp:HyperLink text=<%# ((SortTable) Container.DataItem)["ParamType"].ToString() %> NavigateUrl=<%# GetUrl(Container.DataItem) %> runat=server /> <span InnerHtml=<%# ((SortTable) Container.DataItem)["ParamName"] %> runat=server /> </ItemTemplate> <SeparatorTemplate> ,</SeparatorTemplate> <FooterTemplate> ) </FooterTemplate> </asp:DataList> </td> </tr> </ItemTemplate> <FooterTemplate> </table>

</FooterTemplate> </asp:DataList> <p> <asp:DataList EnableViewState="false" id="SuperClasses" style="margin-left:10" runat="server" RepeatLayout="Flow" RepeatDirection="horizontal" width="100%"> <HeaderTemplate> <font size=2><b> Hierarchy </b></font> <br> </HeaderTemplate> <ItemTemplate> <asp:HyperLink runat=server NavigateUrl=<%# GetUrl(Container.DataItem) %> text=<%# ((SortTable) Container.DataItem)["FullName"]%> /> </ItemTemplate> <SeparatorTemplate> <font face="Verdana" style="font-size:8pt"><nobr>---></nobr> </SeparatorTemplate> </asp:DataList> <p> <asp:DataList EnableViewState="false" id="Interface1" runat=server style="margin-left:10" RepeatDirection="horizontal" RepeatLayout="Flow" width="100%"> <HeaderTemplate> <font size=2><b> Implements </b></font> <br> </HeaderTemplate> <ItemTemplate>

<asp:HyperLink runat=server NavigateUrl=<%# GetUrl(Container.DataItem) %> text=<%# ((SortTable) Container.DataItem)["FullName"]%> /> </ItemTemplate> <SeparatorTemplate> <font face="Verdana" style="font-size:8pt">, </SeparatorTemplate> </asp:DataList> <p> <asp:DataList EnableViewState="false" id="SubClasses" style="margin-left:10" runat=server RepeatLayout="Flow" RepeatDirection="horizontal" width="100%"> <HeaderTemplate> <font size=2> <b>Subclassed By </b></font> <br> </HeaderTemplate> <ItemTemplate> <asp:HyperLink runat=server NavigateUrl=<%# GetUrl(Container.DataItem) %> text=<%# ((SortTable) Container.DataItem)["FullName"]%> /> </ItemTemplate> <SeparatorTemplate> <font face="Verdana" style="font-size:8pt">, </SeparatorTemplate> </asp:DataList> <p> </td> </tr>

</table> </td> </tr> </table> </form> </body> </html>

b.cs using System ; using System.Web; using System.Web.UI; using System.Collections; using System.Reflection; namespace ClassInfo { public class SortTable : Hashtable, IComparable { public String sortField; public SortTable() : this(null) { } public SortTable(String sField) { sortField = sField; } public int CompareTo(Object b) {

if ( sortField == null ) { return 0; } return ((String)this[sortField]).CompareTo((String)((SortTable)b)[sortField]); } } public class DisplayEvents : ArrayList { public DisplayEvents(Type classType) { System.Reflection.EventInfo[] eventInfos = classType.GetEvents(); if (eventInfos == null) return; ArrayList eventTable = new ArrayList(); for (int x=0; x<eventInfos.Length; x++) { SortTable eventDetails = new SortTable("Name"); eventDetails["Assembly"] eventDetails["Name"] eventDetails["Type"] eventDetails["GetType"] = eventInfos[x].EventHandlerType.Assembly.GetName().Name; = eventInfos[x].Name; = eventInfos[x].EventHandlerType.Name; = eventInfos[x].EventHandlerType.Name;

eventDetails["Namespace"] = eventInfos[x].EventHandlerType.Namespace; if (eventInfos[x].IsMulticast == true) { eventDetails["Access"] = "multicast "; } this.Add(eventDetails);

} this.Sort(); } } public class DisplayFields : ArrayList { public DisplayFields(Type classType) { System.Reflection.FieldInfo[] fieldInfos = classType.GetFields(); if (fieldInfos == null) return; ArrayList fieldTable = new ArrayList(); for (int x=0; x<fieldInfos.Length; x++) { SortTable fieldDetails = new SortTable("Name"); fieldDetails["Assembly"] = fieldInfos[x].GetType().Assembly.GetName().Name; fieldDetails["Name"] = fieldInfos[x].Name; fieldDetails["Type"] = fieldInfos[x].FieldType.Name; if(( fieldInfos[x].FieldType.IsArray && fieldInfos[x].FieldType.Name != "Array") || fieldInfos[x].FieldType.IsPointer) { fieldDetails["GetType"] = fieldInfos[x].FieldType.GetElementType().Name; fieldDetails["Namespace"] = fieldInfos[x].FieldType.GetElementType().Namespace; } else { fieldDetails["GetType"] = fieldInfos[x].FieldType.Name;

fieldDetails["Namespace"] = fieldInfos[x].FieldType.Namespace; } if (fieldInfos[x].IsPublic == true){ fieldDetails["Access"] = "public "; } else if (fieldInfos[x].IsPrivate == true){ fieldDetails["Access"] = "private "; } else if (fieldInfos[x].IsFamily == true){ fieldDetails["Access"] = "protected "; } if (fieldInfos[x].IsStatic == true){ fieldDetails["Access"] = ((String) fieldDetails["Access"]) + "static "; } if (fieldInfos[x].IsLiteral == true){ fieldDetails["Access"] = ((String) fieldDetails["Access"]) + "const "; } this.Add(fieldDetails); } this.Sort(); } } public class DisplayConstructors : ArrayList {

public DisplayConstructors(Type classType) { System.Reflection.ConstructorInfo[] constructorInfos = classType.GetConstructors(); if (constructorInfos == null) return; for (int x=0; x<constructorInfos.Length; x++) { SortTable constructorDetails = new SortTable(); constructorDetails["Assembly"] = constructorInfos[x].GetType().Assembly.GetName().Name; constructorDetails["Name"] = classType.Name; if (constructorInfos[x].IsPublic == true) { constructorDetails["Access"] = "public "; } else if (constructorInfos[x].IsPrivate == true) { constructorDetails["Access"] = "private "; } else if (constructorInfos[x].IsFamily == true) { constructorDetails["Access"] = "protected "; } System.Reflection.ParameterInfo[] paramInfos = constructorInfos[x].GetParameters(); if (paramInfos != null) { ArrayList paramTable = new ArrayList(); for (int y=0; y<paramInfos.Length; y++) { SortTable paramDetails = new SortTable();

paramDetails["Assembly"] = paramInfos[y].GetType().Assembly.GetName().Name; paramDetails["ParamName"] = paramInfos[y].Name; paramDetails["ParamType"] = paramInfos[y].ParameterType.Name; if ( ( paramInfos[y].ParameterType.IsArray && paramInfos[y].ParameterType.Name !="Array" ) || paramInfos[y].ParameterType.IsPointer ) { paramDetails["GetType"] = paramInfos[y].ParameterType.GetElementType().Name ; paramDetails["Namespace"] = paramInfos[y].ParameterType.GetElementType().Namespace ; } else { paramDetails["GetType"] = paramInfos[y].ParameterType.Name; paramDetails["Namespace"] = paramInfos[y].ParameterType.Namespace ; } paramTable.Add(paramDetails); } constructorDetails["Params"] = paramTable; } this.Add(constructorDetails); } } } public class DisplayProperties : ArrayList { public DisplayProperties(Type classType) {

System.Reflection.PropertyInfo[] propertyInfos = classType.GetProperties(); if (propertyInfos == null) return; ArrayList propertyTable = new ArrayList(); for (int x=0; x<propertyInfos.Length; x++) { SortTable propertyDetails = new SortTable("Name"); if(propertyInfos[x].GetGetMethod() != null) { if(( propertyInfos[x].GetGetMethod().ReturnType.IsArray && propertyInfos[x].GetGetMethod().ReturnType.Name !="Array" ) || propertyInfos[x].GetGetMethod().ReturnType.IsPointer ) { propertyDetails["GetType"] = propertyInfos[x].GetGetMethod().ReturnType.GetElementType().Name; propertyDetails["Namespace"] = propertyInfos[x].GetGetMethod().ReturnType.GetElementType().Namespace;

} else { propertyDetails["GetType"] = propertyInfos[x].GetGetMethod().ReturnType.Name; propertyDetails["Namespace"] = propertyInfos[x].GetGetMethod().ReturnType.Namespace; } propertyDetails["Type"] = propertyInfos[x].GetGetMethod().ReturnType.Name;

propertyDetails["Assembly"] = propertyInfos[x].GetGetMethod().ReturnType.Assembly.GetName().Name; propertyDetails["Name"] = propertyInfos[x].Name;

if (propertyInfos[x].GetGetMethod().IsPublic == true) {

propertyDetails["Visibility"] = "public"; } else if (propertyInfos[x].GetGetMethod().IsPrivate == true) { propertyDetails["Visibility"] = "private"; } else if (propertyInfos[x].GetGetMethod().IsFamily == true) { propertyDetails["Visibility"] = "protected"; } if (propertyInfos[x].GetGetMethod().IsStatic == true) { propertyDetails["Visibility"] = ((String) propertyDetails["Visibility"]) + " static"; } if (propertyInfos[x].GetSetMethod() == null) { propertyDetails["Access"] = "[Get]" ; } else { propertyDetails["Access"] = "[Get , Set]" ; } System.Reflection.ParameterInfo[] paramInfos = propertyInfos[x].GetGetMethod().GetParameters(); if (paramInfos != null) { ArrayList paramTable = new ArrayList(); for (int y=0; y<paramInfos.Length; y++) { SortTable paramDetails = new SortTable(); paramDetails["Assembly"] = paramInfos[y].GetType().Assembly.GetName().Name; paramDetails["ParamName"] = paramInfos[y].Name; paramDetails["ParamType"] = paramInfos[y].ParameterType.Name;

if (( paramInfos[y].ParameterType.IsArray && paramInfos[y].ParameterType.Name !="Array") ||paramInfos[y].ParameterType.IsPointer ) { paramDetails["GetType"] = paramInfos[y].ParameterType.GetElementType().Name ; paramDetails["Namespace"] = paramInfos[y].ParameterType.GetElementType().Namespace ; } else { paramDetails["GetType"] = paramInfos[y].ParameterType.Name; paramDetails["Namespace"] = paramInfos[y].ParameterType.Namespace ; } paramTable.Add(paramDetails); } propertyDetails["Params"] = paramTable; } } else if(propertyInfos[x].GetSetMethod() != null) { propertyDetails["GetType"] = propertyInfos[x].GetSetMethod().ReturnType.Name; propertyDetails["Namespace"] = propertyInfos[x].GetSetMethod().ReturnType.Namespace; propertyDetails["Type"] = propertyInfos[x].GetSetMethod().ReturnType.Name;

propertyDetails["Assembly"] = propertyInfos[x].GetGetMethod().ReturnType.Assembly.GetName().Name; propertyDetails["Name"] = propertyInfos[x].Name;

if (propertyInfos[x].GetSetMethod().IsPublic == true) { propertyDetails["Visibility"] = "public"; } else if (propertyInfos[x].GetSetMethod().IsPrivate == true) { propertyDetails["Visibility"] = "private";

} else if (propertyInfos[x].GetSetMethod().IsFamily == true) { propertyDetails["Visibility"] = "protected"; } if (propertyInfos[x].GetSetMethod().IsStatic == true) { propertyDetails["Visibility"] = ((String) propertyDetails["Visibility"]) + " static"; } propertyDetails["Access"] = "[ Set ]" ; System.Reflection.ParameterInfo[] paramInfos = propertyInfos[x].GetSetMethod().GetParameters(); if (paramInfos != null) { ArrayList paramTable = new ArrayList();

for (int y=0; y<paramInfos.Length; y++) { SortTable paramDetails = new SortTable(); paramDetails["Assembly"] = paramInfos[y].GetType().Assembly.GetName().Name; paramDetails["ParamName"] = paramInfos[y].Name; paramDetails["ParamType"] = paramInfos[y].ParameterType.Name; if(( paramInfos[y].ParameterType.IsArray && paramInfos[y].ParameterType.Name !="Array") || paramInfos[y].ParameterType.IsPointer) { paramDetails["GetType"] = paramInfos[y].ParameterType.GetElementType().Name ; paramDetails["Namespace"] = paramInfos[y].ParameterType.GetElementType().Namespace ; } else { paramDetails["GetType"] = paramInfos[y].ParameterType.Name;

paramDetails["Namespace"] = paramInfos[y].ParameterType.Namespace ; } paramTable.Add(paramDetails); }

propertyDetails["Params"] = paramTable; } } this.Add(propertyDetails); } this.Sort(); } }

public class DisplayMethods : ArrayList { public DisplayMethods(Type classType, String myclassname) { System.Reflection.MethodInfo[] methodInfos = classType.GetMethods() ;

if (methodInfos == null) return; for (int x=0; x<methodInfos.Length; x++) {

if((String.Compare(myclassname,methodInfos[x].DeclaringType.Name )==0)&&(methodInfos[x].IsPublic || methodInfos[x].IsFamily) && (!(methodInfos[x].IsSpecialName)) ) { SortTable MethodDetails = new SortTable("Name"); MethodDetails["Assembly"] = methodInfos[x].GetType().Assembly.GetName().Name; MethodDetails["Name"] = methodInfos[x].Name; MethodDetails["Type"] = methodInfos[x].ReturnType.Name; if(( methodInfos[x].ReturnType.IsArray && methodInfos[x].ReturnType.Name !="Array") || methodInfos[x].ReturnType.IsPointer) { Type ReturnElementType = methodInfos[x].ReturnType.GetElementType(); while(ReturnElementType.IsArray) { ReturnElementType = ReturnElementType.GetElementType(); } MethodDetails["GetType"] = ReturnElementType.Name ; MethodDetails["Namespace"] = ReturnElementType.Namespace ; } else { MethodDetails["GetType"] = methodInfos[x].ReturnType.Name; MethodDetails["Namespace"] = methodInfos[x].ReturnType.Namespace ; } if (methodInfos[x].IsPublic == true) { MethodDetails["Access"] = "public "; } else if (methodInfos[x].IsPrivate == true) { MethodDetails["Access"] = "private "; } else if (methodInfos[x].IsFamily == true) { MethodDetails["Access"] = "protected ";

} if (methodInfos[x].IsStatic == true) { MethodDetails["Access"] = ((String) MethodDetails["Access"]) + "static "; } System.Reflection.ParameterInfo[] paramInfos = methodInfos[x].GetParameters(); if (paramInfos != null) { ArrayList paramTable = new ArrayList(); for (int y=0; y<paramInfos.Length; y++) { SortTable paramDetails = new SortTable(); paramDetails["Assembly"] = paramInfos[y].GetType().Assembly.GetName().Name; paramDetails["ParamName"] = paramInfos[y].Name; paramDetails["ParamType"] = paramInfos[y].ParameterType.Name; if(( paramInfos[y].ParameterType.IsArray && paramInfos[y].ParameterType.Name != "Array" ) || paramInfos[y].ParameterType.IsPointer) { paramDetails["GetType"] = paramInfos[y].ParameterType.GetElementType().Name ; paramDetails["Namespace"] = paramInfos[y].ParameterType.GetElementType().Namespace ; } else { paramDetails["GetType"] = paramInfos[y].ParameterType.Name; paramDetails["Namespace"] = paramInfos[y].ParameterType.Namespace ; } paramTable.Add(paramDetails); } MethodDetails["Params"] = paramTable; }

this.Add(MethodDetails); } } this.Sort(); } } public class DisplayInterfaces : ArrayList { public DisplayInterfaces(Type classType) { Type[] classInterfaces = classType.GetInterfaces(); for(int x = 0 ; x < classInterfaces.Length ; x++) { SortTable interfaceDetails = new SortTable(); interfaceDetails["Assembly"] interfaceDetails["FullName"] interfaceDetails["GetType"] interfaceDetails["Namespace"] this.Add(interfaceDetails); } } } public class DisplaySuperclasses : ArrayList { public DisplaySuperclasses(Type classType) { Type SuperClass ; SortTable classDetails = new SortTable(); = classInterfaces[x].Assembly.GetName().Name; = classInterfaces[x].FullName; = classInterfaces[x].Name; = classInterfaces[x].Namespace;

classDetails["Assembly"] classDetails["FullName"] classDetails["GetType"] classDetails["Namespace"] this.Add(classDetails);

= classType.Assembly.GetName().Name; = classType.FullName; = classType.Name; = classType.Namespace;

while (classType.BaseType != null) { SortTable superclassDetails = new SortTable(); SuperClass = classType.BaseType ; classType = SuperClass ; = SuperClass.Assembly.GetName().Name; = SuperClass.FullName; = SuperClass.Name; = SuperClass.Namespace;

superclassDetails["Assembly"] superclassDetails["FullName"] superclassDetails["GetType"] superclassDetails["Namespace"] this.Add(superclassDetails) } this.Reverse() ; } } ;

public class DisplaySubClasses : ArrayList { private Type classType ;

private Module[] CorRuntime ; private Type[] private String CorClasses; myclassname ;

private Type[]

classInterfaces;

public DisplaySubClasses(Type classtype, ArrayList ModuleName) { this.classType = classtype; myclassname = classType.FullName ; if (classType.IsInterface ) { for(int y = 0 ; y < ModuleName.Count ;y++) { CorRuntime = Assembly.Load(ModuleName[y].ToString()).GetModules(); CorClasses = CorRuntime[0].GetTypes() ; for(int x= 0 ; x < CorClasses.Length; x++) { classType = CorClasses[x];

classInterfaces = classType.GetInterfaces() ; for(int i = 0 ; i < classInterfaces.Length ; i++) { if(String.Compare(myclassname , classInterfaces[i].FullName )==0) { SortTable subclassDetails = new SortTable("FullName"); = classType.Assembly.GetName().Name; = classType.FullName; = classType.Name; = classType.Namespace;

subclassDetails["Assembly"] subclassDetails["FullName"] subclassDetails["GetType"] subclassDetails["Namespace"] this.Add(subclassDetails) ; } } } }

} else { for(int y = 0; y < ModuleName.Count ; y++) { CorRuntime = Assembly.Load(ModuleName[y].ToString()).GetModules(); CorClasses = CorRuntime[0].GetTypes(); for( int x= 0 ; x< CorClasses.Length ;x++) { classType = CorClasses[x].BaseType ; if ( null != classType ) { if( String.Compare(classType.FullName, myclassname)==0) { SortTable subclassDetails = new SortTable("FullName"); = CorClasses[x].Assembly.GetName().Name; = CorClasses[x].FullName; = CorClasses[x].Name; = CorClasses[x].Namespace;

subclassDetails["Assembly"] subclassDetails["FullName"] subclassDetails["GetType"] subclassDetails["Namespace"] this.Add(subclassDetails) ; } } } } } this.Sort(); } } }

In the web.config file, there are far more assemblies than is desirable, to carry out a search for the names of namespaces. In the a.aspx, we have not introduced too many structural changes. The code is voluminous, but most of it has been explained earlier. Hence, we shall make a quick run through.

In the Page_Load function, where life originates for our aspx application, we first display the namespaces, depending upon the existence of a parameter called class in the Url.

If the class parameter is available, all the details of that class are displayed, using the function DisplayClass. If it is not present, a set of classes from the namespace, are displayed using the function DisplayClassList.

The DisplayClassList function remains the same as before. Modifications have been incorporated in the DisplayClass function. Where we had created one object earlier, which was an instance of DisplayMethods, we now have created seven objects. All these classes reside in the file b.cs. We therefore, have seven occurrences of the 'if' statement. They initialize seven DataList objects DataSource members by these ArrayList types, when the Count property is greater than zero. In their order of appearance, we have ArrayList objects that store details of the following:

Sub-classes Constructors Fields Methods Superclasses Interfaces

We start with a DataList named Namespace1 that displays the list of Namespaces in the first column. Then, we have a div spnClassName that either displays the interface name or the class name. As mentioned earlier, the table, td and tr tags are utilized for display purposes.

The DataList Classes store the class names, while the DataList Interfaces store the names of the Interfaces belonging to a Namespace. To display the list of constructors, we use a DataList called Constructors. In the template named headertemplate for constructors, we simply display the headings' Visibility and Parameters in a tabular format. In the class DisplayConstructors, indexers with names like Access and Name, are created and used in the itemtemplate.

There is always a likelihood of a complication stirring in situations, where the number can vary. Here, the number of parameters passed to the constructor, varies. Hence, we need a DataList within a DataList. The inner DataList is not assigned any name, but its DataSource member is initialized to the indexer variable called Params. Params is an ArrayList with members having the name of ParamType, etc. This is exactly what we had done earlier, in the case of methods. There is no alteration in the basic ground rules.

The mechanism employed to display different items, is as follows:

To display the fields, a DataList called Fields is put into action. To display properties, a DataList called Properties is used. Superclasses are retrieved by a DataList called SuperClasses. Interfaces are retrieved by a DataList called Interface1. Sub-classes need their own DataList called SubClasses.

It is definitely not our concern, as to how the code that figured out the sub-classes, was written. We are not going to get distracted by the C# code written by someone else. We shall primarily focus on the presentation logic in the aspx file. The central idea of a class browser is that, some C# code is responsible for creating an ArrayList. Thereafter, the DataList in the aspx file displays it in a presentable form.

The main chunk of the source code lies in the classes present in the file b.cs. We have already seen as to how methods are to be retrieved. The rest of the code is quite similar. Let us commence with the mechanism for retrieving the constructors that are present in a specific type.

The class that retrieves fields is called DisplayFields. It is derived from ArrayList. The GetFields function is used to return an array of FieldInfo objects. The code to fill up the ArrayList object remains the same as that used for methods. The class named DispalyConstructors uses the function GetConstructors to generate a list of ConstructorInfo objects. Similarly, the class called DisplayProperties uses the function GetPropeties to return a PropertyInfo array. Here, one more function named GetSetMethod is added, which returns a null value, if the property accessor has only a get accessor. The class DisplayInterfaces is similar to the method class.

We need to be acquainted with the class hierarchy, which consists of the list of all the classes that a specific class is derived from, and also, all the classes that derive from it. The class DisplaySuperclasses meets the requirement, but uses a very original approach.

We create an object SuperClass, derived from Type and a Hashtable object classDetails. We initialize three indexer variables named FullName, GetType and Namespace, to the properties FullName, Name and Namespace, which are present in the class Type, respectively. Then, we append this data to the ArrayList class.

A Type has a property called dBaseType, which is set to null, whenever the Type has no base Type. Putting it differently, only the Objects type will have the BaseType property set to null, since all types are finally derived from the class Object. The while loop will repeat itself for the number of types that we have derived from.

For each type, a Hashtable called superclassDetails is created and the SuperClass Type object is initialized to the BaseType. This value is also stored in the parameter variable named ClassType, because we shall lose the earlier value of SuperClass, in the next iteration of the while loop. Once again, the FullName, GetType and Namespace indexer variables are initialized, and thereafter, the new Hashtable object is added to the ArrayList.

The while loop stores data in the ArrayList in the reverse order. We intend to display the class Object first, leading upto the class whose details we are interested in. Thus, we need to reverse the order of the data in the ArrayList.

Das könnte Ihnen auch gefallen