This document was uploaded by user and they confirmed that they have the permission to share
it. If you are author or own the copyright of this book, please report to us by using this DMCA
report form. Report DMCA
Overview
Download & View Vijay Mukhi 's Asp as PDF for free.
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, you’ll 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. file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/intro.htm (1 of 3)2/13/2007 4:53:25 PM
Introduction - ASP.NET - Beta2
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 •
Net Framework SDK Beta 2 can be downloaded off the Microsoft site • http://download.microsoft.com/download/VisualStudioNET/Trial/2.0/W982KMeXP/ EN-US/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.
file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/intro.htm (2 of 3)2/13/2007 4:53:25 PM
Introduction - ASP.NET - Beta2
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. Vijay Mukhi
file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/intro.htm (3 of 3)2/13/2007 4:53:25 PM
Getting Started - ASP.NET - Beta2
-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 hi bye
We then start Internet Explorer (IE) to check-out the output. You can use Netscape or any other browser of your choice, since, it will not affect the output in any way. In the Internet Explorer Address bar, enter the following: c:\inetpub\wwwroot\a.html The abovementioned line will beckon IE or the web browser to pick up a file called a.html from the wwwroot subdirectory and display its contents in the browser window. Thus, the resultant output is as follows: Output hi bye
Any text enclosed within a less than sign (<) and a greater than sign (>) is called an HTML tag. As the character 'b' is enclosed within < 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:
file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/chap1.htm (1 of 29)2/13/2007 4:54:25 PM
Getting Started - ASP.NET - Beta2
http://localhost/a.html
The output, to our pleasant surprise, remains unchanged. (To be able to see the output as shown above, make sure you are running the IIS Web Server from Microsoft. In case you have not installed ASP.Net, please refer to the Installation section of the Introduction chapter in this book for details.) The only difference between the current output and the one displayed earlier is that: • In the earlier case, the HTML file was obtained from a specified directory on our hard disk. • In this case, the HTML file has been obtained from the IIS Web Server. How did this sudden variation occur? Every machine on the Internet is recognized by a name. Thus, the Microsoft server on the Internet is called Microsoft, while our server is called vijaymukhi. In the same vein, as all human beings on the planet earth are called humans, every machine on the internet is recognized by the common nomenclature of 'localhost'. Hence, your machine and my machine, both share this common name. The World Wide Web or WWW is also technically described as http. Therefore, while executing http://localhost/a.html, IE requests the Web Server running on the local machine, to send back a file called a.html. Had we replaced the name localhost with Microsoft, the browser would have requested the web server running on the Microsoft machine, for the same file, a.html. The pertinent question that crops up is "Where does the file a.html reside?" To answer this question, we need to understand, that every Web Server has a default 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 hi <$ hi $> bye
First, we supply the location of the file in IE, i.e. c:\inetpub\wwwroot\a.html. The output displayed by the browser is as shown below. Output hi <$ hi $> bye
file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/chap1.htm (2 of 29)2/13/2007 4:54:25 PM
Getting Started - ASP.NET - Beta2
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. ViewSource menuoption displays our hand-written html file. In the next round, we give the address or the URL as http://localhost/a.html. The address of a file on Internet is also known as a URL or Uniform Resource Locator. The output that is displayed in the browser window is as follows: Output hi <$ hi $> bye View-Source hi <$ hi $> bye
Each time IIS stumbles upon a tag that it does not recognize, it simply sends the tag across to the browser. Thus, the $ tag too is sent to the browser. The file present on the server's hard disk is similar to the one that finally reaches the Web Browser. In the context of the above explanation, we hope that you are truly able to appreciate the difference between the following: • •
Asking a Web Browser to read a file from the disk. Requesting for the same file from the Web Server.
Let us now rename the same file as a.aspx. Here, we have merely changed the file extension and asked IE to fetch the file from the local hard disk. On providing the file location on the address bar, IE displays a dialog box that requests us to choose a program that shall open this file. We choose IE itself from the list of programs displayed. The output we receive now is as shown below Output hi <$ hi $> bye Since the file extension is not html anymore, the browser refuses to parse the tags contained in the file and displays it as is. In the next instance, we ask the Web Server to pick up a.aspx, using the URL. On doing so, IIS seems to go into a slumber or appears to be preoccupied elsewhere. As a result, it takes a very long time to yield the output. It finally displays the following: Output hi <$ hi $> bye View-Source hi
file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/chap1.htm (3 of 29)2/13/2007 4:54:25 PM
Getting Started - ASP.NET - Beta2
<$ hi $> bye
Thus, it may be observed that the Web Server behaves differently in this situation. It interprets a file with an aspx extension, as a special file and therefore, takes longer to process it than before. As before, it also sends the $ tag along with the other tags. We shall now make a small change in the a.aspx file by replacing the $ sign with a % sign a.aspx hi <% hi %> bye
When IE displays the file from the local hard disk, the output remains unchanged. Output hi <% hi %> bye
A tag is a tag is a tag. IE does not understand the tag <$ or the tag <%. So, it ignores both of them. In numerous instances, when you enter the same URL, i.e. http://localhost/a.aspx, IE may not request the Web Server to send the file again. It may simply display the same contents as it did earlier. This happens because, technically, IE fetches the file from its cache. Thus, you should invariably click on the refresh button to make a new request to the Web Server. We shall not remind you about this salient feature hereon. On requesting IIS to fetch the file a.aspx, all hell seems to break loose. To our utter shock and dismay, we get the following error page: Output Server Error in '/' Application. -------------------------------------------------------------------------Compilation Error Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. Compiler Error Message: BC30451: The name 'hi' is not declared. Source Error: Line 1: hi Line 2: <% hi %> Line 3: bye Source File: c:\inetpub\wwwroot\a.aspx Line: 2 Your sagging spirits are bound to receive a fillip on knowing that we did not commit a blunder in the above code. The only faux pas committed was that, one of the tags had been prefixed and suffixed by the symbol %, and it did not have a corresponding closing tag. The error message conveys to us that the name 'hi' is not declared. What does declare mean? In cricket, it means that one team decided not complete its innings. But in the world of programming, it has a very
file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/chap1.htm (4 of 29)2/13/2007 4:54:25 PM
Getting Started - ASP.NET - Beta2
different connotation. So what really went wrong? After a significant amount of brainstorming, we deciphered that the Web Server understands and reads the text placed between the <% and %> symbols. These tags have a special significance for IIS and hence, we need to be extremely careful about the statements that are inserted within them. Further, on viewing the HTML source code, it was confirmed that the Web Server was greatly annoyed by this syntax. It conveyed its irritation by generating a large HTML file. All this ruckus was created for the lone word 'hi'. But IE does not seem to care. Now, we shall carry out one more change in our aspx file. a.aspx hi <% Response.Write("hell") %> bye
The local file with the complete path gives the following output in the browser window: Output : c:\inetpub\wwwroot\a.aspx hi <% Response.Write("hell") %> bye
As before, IE ignores all the tags as it does not recognize the aspx extension. Henceforth, we will not request the Web Browser to fetch an aspx file from the hard disk. When IE requests the Web Server for the same file, the output generated is as follows: Output : http://localhost/a.aspx hi hell bye View-Source hi hell bye
Finally, we have arrived at an error free program ! No error has been generated !! This goes on to prove that IIS gets involved when the tags are enclosed within the symbols <% and %>. However, it does not take any notice of the tags that are enclosed within the symbols <$ and $>. Thus, the symbol % indicates that the tag has a special significance as far as IIS is concerned. The text Response.Write, with the word "hell" enclosed within double inverted commas, is converted into HTML 'hell' and sent over. Using the View-Source menuoption, observe carefully that the syntax Response.Write is not sent over. This concept of the Web Server being able to understand a % tag and specific syntaxes like Response.Write, forms the very core of ASP+ or Active Server Pages Plus. The fundamental concept of ASP.Net is that, it merges the programming language code with file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/chap1.htm (5 of 29)2/13/2007 4:54:25 PM
Getting Started - ASP.NET - Beta2
HTML. You can place unlimited code between the <% and %> symbols which finally is executed by IIS, and the output is merged with the rest of the static HTML text. Thus, ASP.Net is capable of creating dynamic web pages. If this had not been possible, the Internet would not have been such a "moving experience". All that the web server would have done then would be, serve static HTML pages, thus giving us a very limited range of experiences available on the Internet. On the other hand, if the web server is well equipped to create dynamic HTML pages that do not originally exist on the server's hard disk, the variety of content that can be generated is boundless. This dynamism is extensively exploited in different garbs, by developers of web sites to build business applications. In order to learn how to program ASP.Net, we have to ascertain what IIS understands. It understands text such as Response.Write. Response.Write is called a function. A function is represented by a word that is followed by a pair of round brackets. IIS understands innumerable such functions. It is these functions that make the ASP.Net programming astoundingly powerful. Functions are like black boxes that are designed to accomplish specific tasks. As a programmer, you have to understand their functionality and syntax. You should know what a function accomplishes, and how it operates. The function Response.Write accepts a word enclosed within double inverted commas. Technically, a word that is passed to this function is called a parameter. In a.aspx, the parameter passed to the Response.Write function is merged by the server with the HTML file. In the ultimate analysis, an ASP.Net program is a concoction of static HTML text and code. The Web Server IIS, converts the code written within the tags <% %> into text, and thereafter, sends it over to the Web Browser. As the Web Browser can only accept and understand HTML files, it simply displays this file, ignoring the tags that it cannot comprehend. Thus, an aspx file undergoes dramatic transformation before it reaches the Web Browser. Consequently, a file on the server's hard disk is very different from the file that finally reaches the Web Browser. ASP.Net is the single largest concept being used extensively to build Internet Enabled Applications. In order to appreciate the concepts more deeply, you need to study the source file using the View-Source menuoption. You can also execute the examples on the web server and ascertain for yourself, that the results produced are identical. a.aspx hi <% Response.Write("hell ") %> <% Response.Write("no") %> bye Output : http://localhost/a.aspx hi hell no bye
You are at liberty to insert unlimited ASP.Net tags. All the extra spaces preceding or following the text within the tag are removed while displaying the output. The View-Source menuoption file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/chap1.htm (6 of 29)2/13/2007 4:54:25 PM
Getting Started - ASP.NET - Beta2
will make it unambiguously apparent that IIS sends the spaces over, but it is the Web Browser that filters them out and refuses to display them. View-Source hi hell no bye a.aspx hi <% response.Write("hell") %> bye
The letter r of the function Response is in lower case in the above program. However, IIS simply turns a blind eye to it and displays the same output as before. Thus, it can be concluded that IIS is not case sensitive. We then initiate one more change in the program, we spell Write with an additional s. a.aspx hi <% Response.Writes("hell") %> bye Output Compiler Error Message: BC30456: The name 'Writes' is not a member of 'System.Web.HttpResponse'
Alas! An error message has been flashed. IIS can recognize only predefined functions, thus it informs us that it is not aware of a function called Writes. It is because of the cryptic error messages generated by the programming languages, that people like us are in business. It is our job to decipher them for you. The two words, 'member' and 'function' are identical in meaning. All these are rules and it is these rules that constitute a programming language. Within the ASP. Net tags, IIS works on the default assumption that we are following the rules of a language called VBScript. Our only grouse with VBScript is that it is a language of considerable vintage. Hence, we would rather use a language like C# which Microsoft has recently released, which is on the cutting edge of technology. So, we decided to write all our code in C#. In order to facilitate this, all that we need to do is, direct IIS to follow the rules of C#. This instruction is given using a directive. a.aspx <%@ language="C#" %> hi <% Response.Write("hell") %> bye Output Compiler Error Message: CS1002: ; expected
file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/chap1.htm (7 of 29)2/13/2007 4:54:25 PM
Getting Started - ASP.NET - Beta2
Line 4: bye
We started our ASP.Net page with a % symbol as usual, but now we shall follow it up with a @ symbol. A directive in ASP.Net is indicated with the @ sign following the % sign. In a directive, we simply specify the language that we want to use. The word language is called an attribute and we have initialized it to C#, the language that we want to use in the ASP.Net tags, henceforth. Note that the name of the programming language is enclosed within double quotes. Most programmers of ASP.Net code however, may not use the double quotes since they are optional. We have not yet removed the shrouds of mystery behind the error that has been generated. Every language has its own set of rules. In C#, every statement has to be terminated by a semi colon symbol i.e. ;. The absence of the semicolon at the end of the function statement, caused the error. It is pertinent for you to ask, as to why was the semi colon symbol selected ? Since, the C programming language used a ; symbol to mark the end of every statement, and thereafter, C++ and Java also adopted the same syntax, C# also chose to follow suit. a.aspx <%@ language=C# %> hi <% Response.Write("hell"); %> bye Output hi hell bye
On inserting the semicolon, the error vanishes. Thus to conclude, a statement in VB takes an enter to mark the end of every statement, but in C#, it is mandatory to use a ; . Let us now see as to what happens when we change the R of Response to lower case. If you recall, VB ignored it completely since it is case insensitive. a.aspx <%@ language=C# %> hi <% response.Write("hell"); %> bye Output Compiler Error Message: CS0246: The type or namespace name 'response' could not be found (are you missing a using directive or an assembly reference?)
On changing the letter R to r, C# creates havoc, since the language is case sensitive. Thus, in C#, a lower case and an upper case R are two different characters. In this sense, C# is more restrictive than VB. The differences between them are not extensive, but they are sufficient to make you cling on to one of these programming languages. a.aspx
file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/chap1.htm (8 of 29)2/13/2007 4:54:25 PM
Getting Started - ASP.NET - Beta2
<%@ language=C# %> hi <% Response.Write("hell"); %> bye Output hi hell bye
Whatever parameter we pass to the Response.Write function gets sent over to the browser unchanged. IIS does not read this parameter at all. It simply makes it a part of the text file that it has to send over. The word 'hell' is underlined because of the u tag. a.aspx <%@ language=C# %> hi <% Response.Write(""); %> bye
We now see the Windows 2000 logo displayed between the words 'hi' and 'bye'. IIS sends an html file containing an image tag over to the Web Browser. The attribute src with img denotes the name of the picture to be displayed. When the browser sees the img tag, it reverts to the Web Server to obtain the image file. In this case, the specified file is win2000.gif, located in the wwwroot sub-directory. The Web Server sends this graphic file over and the Web Browser displays it. The Web Server cannot send a mixture of a text file as well as graphic files at the same time. It can send only one of them at a time. The View-Source file menuoption can be used to view the textfile . a.aspx <%@ language=C# %> hi <% Response.Write(vijay); %> bye Output Compiler Error Message: CS0103: The name 'vijay' does not exist in the class or namespace 'ASP.a_aspx' Line 3: <% Response.Write(vijay); %>
Initially, we shall display two lines of the error message, but once you get acquainted with the error screen, we will display the error message only. The first line contains the actual error message and the second line, depicted in red, indicates the position where according to C#, feels that the error has occurred. This is only an approximation which may not be correct. The word vijay, without quotes, is passed as a parameter to the Response.Write function. Since, C# is not familiar with my name, it displays an error. This really hurts my ego, because I thought I was known world over. 'Arrogance thy name is
file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/chap1.htm (9 of 29)2/13/2007 4:54:25 PM
Getting Started - ASP.NET - Beta2
Vijay Mukhi !' you may say. So, how do we make the word vijay significant to C# ? a.aspx <%@ language=C# %> hi <% String vijay; vijay = "good"; Response.Write(vijay); %> bye Output hi good bye
Reason to Rejoice! No errors have been generated by the above program. Further, vijay has been replaced by the word 'good'. Are these two words linked in any way ? Programmers will call vijay a variable. A variable is a word that can hold a value. We have created a variable called vijay, and in the next line, we have assigned it the value 'good'. Thus, from now on, wherever C# comes across vijay, it will replace it with the word 'good'. One mystery has been solved. Now, let us take the next one by its horns! What is the word String doing in front of the variable vijay? This word is called a data type. It apprizes us of the nature of the content that the variable vijay shall store. Since, we want to store letters of the alphabet or words in vijay, we precede it with the String data type. Whenever a variable is created, C# must be informed about the nature of data or the contents of the variable. C# recognizes a large number of data types. One more question that may crop up in your mind to vex you is, "Why is vijay called a variable?" a.aspx <%@ language=C# %> hi <% String vijay; vijay = "hell"; Response.Write(vijay); vijay = "no"; Response.Write(vijay); %> bye Output hi hellno bye
A variable is a word whose value can vary. The variable vijay first stored the value hell and then 'hi'. Thus, a variable can hold one value at one point in time, and a different value at another point in time. Every program that you pen down, will revolve around variables. file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/chap1.htm (10 of 29)2/13/2007 4:54:25 PM
Getting Started - ASP.NET - Beta2
a.aspx <%@ language=C# %> hi <% String vijay; vijay = "hell"; Response.Write(vijay + " "); vijay = "no"; Response.Write(vijay); %> Output hi hell no
In the above program, we want to write the words hell and no, on two separate lines. To do so, we firstly add a + sign to join the two strings. The first string is our variable vijay, and the second string is an HTML tag br that results in a line break. The + sign does not attempt to add the two strings as is done in arithmetic, but concatenates them to form a single string. As a result, the final HTML file sent to the browser, is as follows: View-Source hi hell no
With this limited knowledge, we shall proceed to unravel the workings of a Search Engine. Search Engines are programs that accept a word from you, and as soon as you click on a specified button, it generates a page with a list of sites containing the specified word. Let us first fortify our knowledge of HTML by learning some more of its basics. a.aspx <%@ language=C# %>
The HTML tag input along with the attribute text, enables us to input characters just as we do in a textbox. This widget is used to accept data from the user. a.aspx <%@ language=C# %>
We have added another input tag with the attribute 'submit'. This generates a button on the screen. This button has the word Click as its label, because the value attribute is assigned the word Click. The attribute value for the textbox is vijay. Thus, vijay is displayed in the textbox when the page is loaded.
file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/chap1.htm (11 of 29)2/13/2007 4:54:25 PM
Getting Started - ASP.NET - Beta2
When we click on the button, nothing happens. Had we clicked on a similar button in a Search Engine, it would have displayed a page with the results of the search. Let us achieve the same functionality here also. a.aspx <%@ language=C# %> a1.aspx <%@ language=C# %> Hi in a1.aspx
A new HTML tag called form, makes its debut in our aspx file. This tag has an attribute called action, which has been assigned the value a1.aspx. Similarly, the textbox has been given an attribute called name that has been initialized to aa. In the textbox, we input vijay1 and click on the submit button. This act awakens IE, which searches for a tag called form, within the HTML file. The tag form also has an attribute called action, with the value a1.aspx. IE takes this value and creates a new URL as http://localhost/ a1.apx. Since, only the filename is specified in the action attribute without any machine name, it defaults to the machine containing the file a.aspx. With a URL in the action attribute followed by the file name will have the form tag as follows:
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 + " ");
file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/chap1.htm (13 of 29)2/13/2007 4:54:25 PM
Getting Started - ASP.NET - Beta2
a = Request.QueryString["bb"]; Response.Write(a); %> Output Hi in a1.aspx vijay mukhi
Just as we displayed one parameter value, we can also display another one. The same concept is relevant, except that the values supplied as parameters get altered. The variable a, first stores the word vijay, and subsequently, it stores the value mukhi. Thus, its value fluctuates. Let us now write a program that has a superior level of built-in intelligence. It will display different values depending upon the name of the user. So, here we go! a1.aspx <%@ language=C# %> Hi in a1.aspx <% String a; a = Request.QueryString["aa"]; if ( a == "vijay") Response.Write("
Welcome " + a + "
"); if ( a == "sonal") Response.Write("
You are not Welcome " + a + "
"); %>
If we input the word sonal in the first textbox and click on the submit button, we get the following output: Output Hi in a1.aspx You are not Welcome sonal
Now, if we input the word vijay, we get the following output: Output Hi in a1.aspx Welcome vijay
Thereafter, if we input the word vijay1, the output obtained is as follows: Output Hi in a1.aspx
Thus, we get a different output depending upon the data entered in the textbox. This is only an elementary demonstration of code that generates dynamic pages. One way of introducing dynamism is by using the 'if' statement. The 'if' statement inserts a lot file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/chap1.htm (14 of 29)2/13/2007 4:54:25 PM
Getting Started - ASP.NET - Beta2
of intelligence into our code. The 'if' statement checks whether the value of the variable a is equal to vijay or not. If the answer is yes, it executes the next line. If the answer is no, then the next line is ignored. Thus, we now have the ability to conditionally execute some code, depending upon the value of a variable. Variables now seem to have come of age and have begun to prove their usefulness. The 'if' statement assists in making intelligent decisions. When the parameter aa holds the value of vijay, the first if statement is true, but the second one is false. Similarly, when the parameter aa has the value sonal , the first 'if' statement is false, whereas, the second one is true. In the last case, where the value is neither vijay nor sonal, none of the 'if' statements evaluate to true. Hence, no code within the % signs is executed. We hope the use of the double 'equal to' , == to check for equality, did not slip your attention. It does not alter the value of a variable. It evaluates either to true or to false. A single 'equal to' symbol =, is used for assigning values. a1.aspx <%@ language=C# %> Hi in a1.aspx <% String a; a = Request.QueryString["aa"]; if ( a == "vijay") Response.Write("
Welcome " + a + "
"); Response.Write("Not in the range of a if "); if ( a == "sonal") Response.Write("
You are not Welcome " + a + "
"); %> Output Hi in a1.aspx Not in the range of a if You are not Welcome sonal
In the above program, when we typed in the word sonal in the textbox, surprisingly the Write function containing the text 'Not in the range of a if ', also got called. If you had been mindful and observant just a few paragraphs earlier, you would be able to remember us having stated very clearly that, the 'if' statement operates only on the immediately succeeding line. Thus, the second Write function does not come under the influence of the first 'if' statement. The default number of the lines under the influence of the 'if' statement, is only one. What if we desire to have the next 10 lines controlled by the 'if' statement ? The next program has the answer to that. a1.aspx <%@ language=C# %> Hi in a1.aspx <% String a; a = Request.QueryString["aa"];
file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/chap1.htm (15 of 29)2/13/2007 4:54:25 PM
Getting Started - ASP.NET - Beta2
if ( a == "vijay") { Response.Write("
Welcome " + a + "
"); Response.Write("Not in the range of a if "); } if ( a == "sonal") Response.Write("
You are not Welcome " + a + "
"); %> Output Hi in a1.aspx You are not Welcome sonal
The only way to execute or bypass a block of statements with the 'if' statement is, by placing them within curly braces. Code written in curly braces is treated as one lengthy statement. Thus, if there are more than one statement to be executed by the 'if' statement, the code should be placed in curly braces. a1.aspx <%@ language=C# %> Hi in a1.aspx <% String a; a = Request.QueryString["aa"]; if ( a == "vijay") Response.Write("
Welcome " + a + "
"); else Response.Write("
You are not Welcome " + a + "
"); %> Output Hi in a1.aspx You are not Welcome sonal1
The data entered in the textbox is sonal1. In a1.aspx, C# stores this value in the variable a and then checks the value against vijay, using the 'if' statement. As the content of the variable a is not vijay, the 'if' statement becomes false. Hence, the 'else' statement is executed. The 'else' statement can only be used as part of the 'if' statement. When the 'if'' statement is false, the code associated with the 'else' statement is executed. Conversely, when the 'if' statement is true, the code associated with the 'else' statement is ignored. Therefore, under any eventuality, either the 'if' or the 'else' gets called, in other words, only one of them is executed. We now run the program a1.aspx directly, using http://localhost/a1.aspx. a1.aspx <%@ language=C# %> Hi in a1.aspx <% int i; i = 10; Response.Write(i); file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/chap1.htm (16 of 29)2/13/2007 4:54:25 PM
Getting Started - ASP.NET - Beta2
%> 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
file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/chap1.htm (17 of 29)2/13/2007 4:54:25 PM
Getting Started - ASP.NET - Beta2
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.
file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/chap1.htm (18 of 29)2/13/2007 4:54:25 PM
Getting Started - ASP.NET - Beta2
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; file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/chap1.htm (19 of 29)2/13/2007 4:54:25 PM
Getting Started - ASP.NET - Beta2
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 file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/chap1.htm (20 of 29)2/13/2007 4:54:25 PM
Getting Started - ASP.NET - Beta2
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++; } %> file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/chap1.htm (21 of 29)2/13/2007 4:54:25 PM
Getting Started - ASP.NET - Beta2
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(" hi "); %> Output hi hi hi
Let us now explore the convenience that a loop provides to help us write code, which otherwise would have been difficult to write. The font tag in HTML takes an attribute called size. This tag determines the size of the font for the text to be displayed. Using the 'for' loop, we are assigning different values to the variable i in such a way that we get three different font tags, each of which has different values for the size attribute. The View-Source output endorses our statement. View Source hi hi hi a1.aspx <%@ language=C# %> <% int i = 10; %> <%= i %> Output
file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/chap1.htm (22 of 29)2/13/2007 4:54:25 PM
Getting Started - ASP.NET - Beta2
10
There are a number of shortcuts in ASP.Net. One of them being, the expression <%= which is an equivalent of the function Response.Write. Only the parameter supplied to the Response. Write function is used with %=. It is mandatory to insert a space after the 'equal to' sign.
The code using the <%= expression is very compact and precise, and it does not require a semicolon at the end of the statement. Let us incorporate this directive in the next example. a1.aspx <%@ language=C# %> <% int i; for ( i = 1; i<=3 ; i++) { %> > hi <% } %>
The output of the above program is similar to that of a previous program. The only variation is in the style and approach. If you observe very carefully, the file contains ASP.Net tags, as well as HTML tags. Unlike the earlier case, where the code contained only ASP.Net tags, the source code in this case, uses ASP.Net and HTML. Thus, the font tag is written in HTML with the exception of the attribute size. Since, a different value is required each time, variable i is enclosed within % tags. Moreover, in a 'for' statement, only the first line following the 'for' statement is acted upon by the 'for' loop, unless we enclose multiple lines using curly braces. Here, the variable i, the 'for' loop and the curly braces are also enclosed within the ASP.Net tags. Thus, we are able to dynamically generate different HTML tags. Finally, all the code is translated into an HTML file for the convenience of the Web Browser. All the HTML tags in an aspx file are converted into one gigantic C# program, wherein, the static HTML tags are converted into parameters to the Response.Write function. Someday, we shall disclose to you the source of the above information. The final transition is from one large C# program to one large HTML file. a1.aspx <%@ language=C# %> <% int i; for ( i = 1; i<=3 ; i++) { %> > hi > <% } %>
file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/chap1.htm (23 of 29)2/13/2007 4:54:25 PM
Getting Started - ASP.NET - Beta2
Output
hi hi hi
The word 'hi' is displayed in three different sizes because, the heading tag (h) changes with each iteration of the 'for' statement. This program is very similar to the font program seen earlier. The View-Source menuoption will clear all the cobwebs in your mind, in this regard. View-Source
hi
hi
hi
When the 'for' loop iterates, the h tag changes from h1 to h2 and then to h3. The same logic is applied for the closing tag also. a1.aspx <%@ language=C# %> bye <% if ( false) %> hi Output bye
Since, the 'if' condition has a false value, 'hi' is not displayed in the browser window. Thus, we can safely assume that the C# code acts upon HTML statements. Let us look at it this way: Since all the code is finally amalgamated into one large C# program, the 'if' statement does not act on the HTML text 'hi', but on the function Response.Write("hi"). a1.aspx <%@ language=C# %> <% abc(); %> Output Compiler Error Message: CS0103: The name 'abc' does not exist in the class or namespace 'ASP.a1_aspx' Line 3: abc();
Here, we are calling a function called abc by writing its name, following it by a pair of round brackets, and then ending it with a semicolon. The compiler reports an error as there is no function called abc. This error is pretty obvious. The function call to a non-existent function was done on purpose to educate you on the error messages thrown up by the compiler.
file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/chap1.htm (24 of 29)2/13/2007 4:54:25 PM
Getting Started - ASP.NET - Beta2
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"); } <% 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(); } file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/chap1.htm (25 of 29)2/13/2007 4:54:25 PM
Getting Started - ASP.NET - Beta2
<% 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 "); } <% 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) { file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/chap1.htm (26 of 29)2/13/2007 4:54:25 PM
Getting Started - ASP.NET - Beta2
Response.Write(i + " " + j); } <% 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); } <% 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> file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/chap1.htm (27 of 29)2/13/2007 4:54:25 PM
Getting Started - ASP.NET - Beta2
int abc( int i, int j) { } <% 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"); } <% 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> file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/chap1.htm (28 of 29)2/13/2007 4:54:25 PM
Getting Started - ASP.NET - Beta2
void abc( int i, int j) { return i + j; } <% 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.
file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/chap1.htm (29 of 29)2/13/2007 4:54:25 PM
Server Controls - ASP.NET - Beta2
-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# %> a1.aspx <%@ language=C# %>
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 ViewSource menuoption displays the following in respect of a.aspx: View-Source
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 file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/chap2.htm (1 of 38)2/13/2007 4:58:14 PM
Server Controls - ASP.NET - Beta2
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
When we click on the button after writing 'no', the address bar changes to- http://localhost/a1. aspx?aa=no&ctrl2=Click+a1.aspx but the output displayed by View-Source remains the same. View-Source
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# %>
file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/chap2.htm (2 of 38)2/13/2007 4:58:14 PM
Server Controls - ASP.NET - Beta2
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
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
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
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# %> View Source
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
file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/chap2.htm (4 of 38)2/13/2007 4:58:14 PM
Server Controls - ASP.NET - Beta2
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# %>
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# %> a.xml /quickstart/aspplus/images/banner2.gif/quickstart/aspplus/images/banner3.gif
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
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# %>
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
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',
file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/chap2.htm (6 of 38)2/13/2007 4:58:14 PM
Server Controls - ASP.NET - Beta2
followed by the textbox that contains 'vijay', and then the View-Source displays the following: View-Source hell
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# %> 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
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# %> file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/chap2.htm (7 of 38)2/13/2007 4:58:14 PM
Server Controls - ASP.NET - Beta2
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; } 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
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. file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/chap2.htm (8 of 38)2/13/2007 4:58:14 PM
Server Controls - ASP.NET - Beta2
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; } Hi Click here
We now have an asp hyperlink tag that is equivalent of the 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"]; } Hi !
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
file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/chap2.htm (9 of 38)2/13/2007 4:58:14 PM
Server Controls - ASP.NET - Beta2
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!"; } } a1.aspx <%@ language=C# %> <script language="C#" runat="server"> void Page_Load(Object s,EventArgs e) { aa.Text = Request.Params["bb"]; } Hi !
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.
file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/chap2.htm (10 of 38)2/13/2007 4:58:14 PM
Server Controls - ASP.NET - Beta2
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; } 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# %>
In the browser, a textbox and a button are displayed. When we click on the button, the file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/chap2.htm (11 of 38)2/13/2007 4:58:14 PM
Server Controls - ASP.NET - Beta2
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 View-Source 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
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 file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/chap2.htm (12 of 38)2/13/2007 4:58:14 PM
Server Controls - ASP.NET - Beta2
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# %>
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 file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/chap2.htm (13 of 38)2/13/2007 4:58:14 PM
Server Controls - ASP.NET - Beta2
<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"; } }
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. file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/chap2.htm (14 of 38)2/13/2007 4:58:14 PM
Server Controls - ASP.NET - Beta2
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 %> View Source
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 file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/chap2.htm (15 of 38)2/13/2007 4:58:14 PM
Server Controls - ASP.NET - Beta2
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 %> <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"; } }
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%> file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/chap2.htm (16 of 38)2/13/2007 4:58:14 PM
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
file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/chap2.htm (17 of 38)2/13/2007 4:58:14 PM
Server Controls - ASP.NET - Beta2
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','')" rel="nofollow">
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 page with the new format for the validation tag. This tag displays the list of errors only if IsValid is False. a.aspx <%@ Page clienttarget=downlevel %> <script language="C#" runat="server"> void abc(Object s, EventArgs e) { if (Page.IsValid) { aa.Text = "Result: Valid!"; } else { aa.Text = "Result: Not valid!"; } } void pqr(Object s,EventArgs e) { cc.Operator = (ValidationCompareOperator) bb.SelectedIndex; cc.Validate(); }
There are two textboxes t1 and t2, a label aa and a button in the above program. The function abc is called whenever we click on the button. In the listbox bb, we have a large number of options, which have names that are similar to terms used for comparison, such as Greater Than, GreaterThanEqual, NotEqual etc. A new ASP.Net tag <script language="C#" runat="server">
file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/chap2.htm (19 of 38)2/13/2007 4:58:14 PM
In the above program, we have used a validator called RangeValidator that checks whether the specified value falls within a range or not. The control that is to be validated, should be mentioned with the validator. Hence, ControlToValidate is initialized to t3. Furthermore, the maximum value and the minimum value of the range are to be provided. This is achieved by assigning these values to the attributes MaximumValue and MinimumValue, respectively. If the value contained in the control t3 does not fall within the specified range, IsValid becomes False. When the page is loaded, the third textbox has the value 20. If we change the value in the third textbox to 15 and click on the button, the function abc is called, where the Validate function from the control cc, checks the value contained in the IsValid property. Earlier, we had selected an operator from a listbox. Hence, the type was a String. In this case, since we are dealing with numbers, we change the Type property to integer. a.aspx <%@ Page clienttarget=downlevel %> <script language="C#" runat="server"> void abc(Object s, EventArgs e) { cc.Validate(); if (Page.IsValid) { file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/chap2.htm (20 of 38)2/13/2007 4:58:14 PM
The validator RegularExpressionValidator, which is introduced for the first time, is employed to validate control values. The validator simply requires the control to be validated, followed by a regular expression. A Regular Expression generally appears like gibberish, since it contains special characters, but it can prove to be extremely powerful. A whole lot of books have been written on the simplicities and the complexities of Regular Expressions. A regular expression is an expression that matches the data entered, with a pattern or a rule. In the above case, we want the user to enter a zip code that consists of only 5 numbers. He has to type in exactly 5 numbers, and they must be nothing but numbers. The regular expression will be ^\d{5}$. A caret sign ^ matches the input from the beginning of the line, while a dollar sign $ indicates the end. \d refers to a digit, and 5 in {} braces indicates 5 occurrences of the specified data type, i.e. 5 digits. In simple terms, only 5 digits should be entered. Thus, '^/d{5} $' corresponds to 'start - check 5 digits - end'. Let us look at another Regular Expression reflected on the next line. ^[\w-]+@[\w-]+\.(com|net|org|edu|mil)$ This expression verifies whether the e-mail address has been provided in the right format or not. The square brackets agree with any one of the many characters that it embodies. \w permits any character to be typed in. + means one or more, and the @ is an actual literal. Round brackets with value of ( aa | bb ) will check for either aa or bb. And as mentioned earlier, ^ marks the beginning of the line, while $ denotes the end of the line. The above Regular Expression will match an e-mail address exactly with the pattern specified. This is just a preface to regular Expressions. There is a lot more to it than meets the eye at present. However, this introduction shall suffice for the time being.
file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/chap2.htm (21 of 38)2/13/2007 4:58:14 PM
This program restricts data entry of any number less than 100. The error is checked at the client end and not at the server end. Here, you are introduced to one more validator tag
Server Controls - ASP.NET - Beta2
then a value of False is returned. In the case of the function abc in Javascript, the View-Source menuoption shows code that is similar to what we had entered in aspx. Thus, we have clearly demonstrated how to build your own custom error checks. a.aspx <script language="C#" runat=server> void pqr(object sender, EventArgs e) { if (Page.IsValid) { aa.Text = "Page is valid!"; } else { aa.Text = "Page is not valid! :-("; } } void abc (object source, ServerValidateEventArgs value) { int n = Int32.Parse(value.Value); if (n > 100) value.IsValid = true; else value.IsValid = false; }
How do we achieve the same validation on the Server? To do so, CustomValidator takes an additional attribute called OnServerValidate, which is initialized to the function abc. Thus, each time we click on the button, data is retransmitted to the function abc, which is located on the server. On being called, the function abc checks the number. Thereafter, the function pqr is called. If the function abc returns true, IsValid in pqr becomes true. C# code never gets executed on the client-side. It is the Web Server's responsibility to parse the C# code and create the correct HTML file. The View-Source menuoption will substantiate this file:///E|/STUDY/BOOKS/asp.net%20%20....%20vijay%20mukhi/chap2.htm (23 of 38)2/13/2007 4:58:14 PM
Server Controls - ASP.NET - Beta2
fact.
Functional Controls Buttons a.aspx Output
A simple button can perform complicated tasks. The aspx file contains two button controls, labeled vijay and mukhi. Two different properties are associated with each of them. The button with an id of Button1, which contains the text 'vijay', has properties called onmouseover and mouseout. The property mouseover is called when the mouse moves over the button. At this point, we are employing this property to change the background colour of the button to yellow. In the same vein, the property onmouseout is called when the mouse leaves the button. Here, we utilize this property to change the colour back to normal. In the second button, having an id of button2 and the text 'mukhi', we take the same style property and change the font weight to bold. The 'this' keyword is optional. a.aspx