
Pro CSharp 2008 And The .NET 3.5 Platform [eng]
.pdf


1164 CHAPTER 31 ■ BUILDING ASP.NET WEB PAGES
Figure 31-1. The HTTP request/response cycle
HTTP Is a Stateless Protocol
Another aspect of web development that is markedly different from traditional desktop programming is the fact that HTTP is essentially a stateless wire protocol. As soon as the web server emits a response to the client, everything about the previous interaction is forgotten. This is certainly not the case for a traditional desktop application, where the state of the executable is most often alive and kicking until the user shuts down the application in question.
Given this point, as a web developer, it is up to you take specific steps to “remember” information (such as items in a shopping cart, credit card numbers, home and work addresses, etc.) about the users who are currently logged on to your site. As you will see in Chapter 33, ASP.NET provides numerous ways to handle state, many of which are commonplace to any web platform (session variables, cookies, and application variables) as well as some .NET-particular techniques such as the ASP.NET profile management API.
Understanding Web Applications and Web Servers
A web application can be understood as a collection of files (*.htm, *.asp, *.aspx, image files, XMLbased file data, etc.) and related components (such as a .NET code library or legacy COM server) stored within a particular set of directories on a given web server. As shown in Chapter 33, ASP.NET web applications have a specific life cycle and provide numerous events (such as initial startup or final shutdown) that you can hook into to perform specialized processing during your website’s operation.
A web server is a software product in charge of hosting your web applications, and it typically provides a number of related services such as integrated security, File Transfer Protocol (FTP) support, mail exchange services, and so forth. Internet Information Services (IIS) is Microsoft’s enterprise-level web server product, and as you would guess, it has intrinsic support for classic ASP as well as ASP.NET web applications.
When you build production-ready ASP.NET web applications, you will often need to interact with IIS. Be aware, however, that IIS is not automatically selected as an installation option when you install the Windows operating system (also be aware that not all versions of Windows can support IIS, such as Windows XP Home). Thus, depending on the configuration of your development machine, you may wish to install IIS before proceeding through this chapter. To do so, simply access the Add/Remove Program applet from the Control Panel folder and select Add/Remove Windows Components. Consult the Windows help system if you require further details.

CHAPTER 31 ■ BUILDING ASP.NET WEB PAGES |
1165 |
■Note Ideally, your development machine will have IIS installed before you install Visual Studio 2008. If you install IIS after you install Visual Studio 2008, none of your ASP.NET web applications will execute correctly (you will simply get back a blank page). Luckily, you can reconfigure IIS to host .NET applications by running the aspnet_regiis.exe command-line tool and specifying the /i option.
Assuming you have IIS properly installed on your workstation, you can interact with IIS from the Administrative Tools folder (located in the Control Panel folder) by double-clicking the Internet Information Services applet. For the purposes of this chapter, you are concerned only with the Default Web Site node (see Figure 31-2).
Figure 31-2. The IIS applet
The Role of IIS Virtual Directories
A single IIS installation is able to host numerous web applications, each of which resides in a virtual directory. Each virtual directory is mapped to a physical directory on the hard drive. Therefore, if you create a new virtual directory named CarsRUs, the outside world can navigate to this site using a URL such as http://www.CarsRUs.com (assuming your site’s IP address has been registered with the world at large). Under the hood, this virtual directory maps to a physical root directory on the web server, such as C:\inetpub\wwwroot\AspNetCarsSite, which contains the content of the CarsRUs web application.
As you will see later in this chapter, when you create ASP.NET web applications using Visual Studio 2008, you have the option of having the IDE generate a new virtual directory for the current website automatically. If required, you are certainly able to manually create a virtual directory by hand by right-clicking the Default Web Site node of IIS and selecting New Virtual Directory (or on Vista, simply Add Virtual Directory) from the context menu.

1166 CHAPTER 31 ■ BUILDING ASP.NET WEB PAGES
When you select the option to create a new virtual directory, you will be prompted for the name and physical folder that will contain the web content. To illustrate working with IIS (and to set us up for our first web example), create a new directory on your hard drive that will hold yet- to-be-generated web content. For this discussion I’ll assume this directory to be C:\CodeTests\ CarsWebSite. Now, right-click the Default Web Site node of IIS to create a new virtual directory named Cars that maps to this new directory. Figure 31-3 shows the end result.
Figure 31-3. The Cars virtual directory
We will add some content to this website in just a moment.
The ASP.NET Development Server
Prior to .NET 2.0, ASP.NET developers were required to make use of IIS virtual directories during the development and testing of their web content. In many cases, this tight dependency on IIS made team development more complex than necessary (not to mention that many network administrators frowned upon installing IIS on every developer’s machine). Thankfully, we now have the option to use a lightweight web server named WebDev.WebServer.exe. This utility allows developers to host an ASP.NET web application outside the bounds of IIS. Using this tool, you can build and test your web pages from any directory on your machine. This is quite helpful for team development scenarios and for building ASP.NET web programs on versions of Windows that do not support IIS installations (such as Windows XP Home).
■Note WebDev.WebServer.exe cannot be used to test or host classic (COM-based) ASP web applications. This web server can host only ASP.NET web applications and/or .NET-based XML web services.
When building a website with Visual Studio 2008, you have the option of using WebDev. WebServer.exe to host your pages (as you will see a bit later in this chapter). However, you are also able to manually interact with this tool from a Visual Studio 2008 command prompt. If you enter the following command:

CHAPTER 31 ■ BUILDING ASP.NET WEB PAGES |
1167 |
WebDev.WebServer.exe -?
you will be presented with a message box that describes the valid command-line options. In a nutshell, you will need to specify an unused port (via the /port: option), the root directory of the web application (via the /path: option), and an optional virtual path using the /vpath: option (if you do not supply a /vpath: option, the default is simply /). Consider the following usage, which opens an arbitrary port to view content in the C:\CodeTests\CarsWebSite directory created previously:
WebDev.WebServer.exe /port:12345 /path:"C:\CodeTests\CarsWebSite"
Once you have entered this command, you can launch your web browser of choice to request pages. Thus, if the CarsWebSite folder had a file named Default.aspx, you could enter the following URL:
http://localhost:12345/CarsWebSite/Default.aspx
Many of the examples in this chapter and the next will make use of WebDev.WebServer.exe via Visual Studio 2008, rather than hosting web content under an IIS virtual directory. While this approach can simplify the development of your web application, do be aware that this web server is not intended to host production-level web applications. It is intended purely for development and testing purposes. Once a web application is ready for prime time, your site will need to be copied to an IIS virtual directory.
■Note The Mono project (see Appendix B) provides a free ASP.NET plug-in for the Apache web server. This makes it possible to build and host ASP.NET web applications on operating systems other than Microsoft Windows. If you are interested, check out http://www.mono-project.com/ASP.NET for details.
The Role of HTML
Now that you have configured a directory to host your web application, and you have chosen a web server to serve as the host, you need to create the content itself. Recall that “web application” is simply the term given to the set of files that constitute the functionality of the site. To be sure, a vast number of these files will contain tokens defined by Hypertext Markup Language (HTML). HTML is a standard markup language used to describe how literal text, images, external links, and various HTML-based UI widgets are to be rendered within the client-side browser.
This particular aspect of web development is one of the major reasons why many programmers dislike building web-based programs. While it is true that modern IDEs (including Visual Studio 2008) and web development platforms (such as ASP.NET) generate much of the HTML automatically, you will do well to have a working knowledge of HTML as you work with ASP.NET.
■Note Recall from Chapter 2 that Microsoft has released a number of free IDEs under the Express family of products (such as Visual C# Express). If you are interested in web development, you may wish to also download Visual Web Developer Express. This free IDE is geared exclusively at the construction of ASP.NET web applications.
While this section will most certainly not cover all aspects of HTML (by any means), let’s check out some basics and build a simple web application using HTML, classic (COM-based) ASP, and IIS. This will serve as a road map for those of you coming to ASP.NET from a traditional desktop application development background.

1168 CHAPTER 31 ■ BUILDING ASP.NET WEB PAGES
■Note If you are already comfortable with the overall process of web page development, feel free to skip ahead to the section “Problems with Classic ASP.”
HTML Document Structure
An HTML file consists of a set of tags that describe the look and feel of a given web page. As you would expect, the basic structure of an HTML document tends to remain the same. For example, *.htm files (or, equivalently, *.html files) open and close with <html> and </html> tags, typically define a <body> section, and so forth. Keep in mind that traditional HTML is not case sensitive. Therefore, in the eyes of the hosting browser, <HTML>, <html>, and <HtmL> are identical.
To illustrate some HTML basics, open Visual Studio 2008, create an empty HTML file using the File New File menu selection, and save this file under your C:\CodeTests\CarsWebSite directory as default.htm. As you can see, the initial markup is rather uneventful:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Untitled Page</title> </head>
<body>
</body>
</html>
First of all, notice that this HTML file opens with a DOCTYPE processing instruction. This informs the IDE that the contained HTML tags should be validated against the XHTML standard. As suggested, traditional HTML was very “loose” in its syntax. For example, it was permissible to define an opening element (such as <br>, for a line break) that did not have a corresponding closing break (</br> in this case), was not case sensitive, and so forth. The XHTML standard is a W3C specification that adds some much-needed rigor to the HTML markup language.
■Note By default, Visual Studio 2008 validates all HTML documents against the XHTML 1.0 Transitional validation scheme. Simply put, HTML validation schemes are used to ensure the markup is in sync with specific standards. If you wish to specify an alternative validation scheme, activate the Tools Options dialog box, and then select the Validation node under HTML. If you would rather not see validation errors, simply uncheck the Show Errors check box.
The <html> and </html> tags are used to mark the beginning and end of your document. Notice that the opening <html> tag is further qualified with an xmlns (XML namespace) attribute that qualifies the various tags that may appear within this document (again, by default these tags are based on the XHTML standard). Web browsers use these particular tags to understand where to begin applying the rendering formats specified in the body of the document. The <body> scope is where the vast majority of the actual content is defined. To spruce things up just a bit, update the title of your page as follows:
<head>
<title>This Is the Cars Web site</title> </head>

CHAPTER 31 ■ BUILDING ASP.NET WEB PAGES |
1169 |
Not surprisingly, the <title> tags are used to specify the text string that should be placed in the title bar of the calling web browser.
HTML Form Development
The real meat of most *.htm files occurs within the scope of the <form> elements. An HTML form is simply a named group of related UI elements used to gather user input, which is then transmitted to the web application via an HTTP request. Do not confuse an HTML form with the entire display area shown by a given browser. In reality, an HTML form is more of a logical grouping of widgets placed in the <form> and </form> tag set:
<html xmlns="http://www.w3.org/1999/xhtml" > <head>
<title>This Is the Cars Web site</title> </head>
<body>
<form id="defaultPage">
<!-- Insert web UI content here ->
</form>
</body>
</html>
This form has been assigned the ID and name of "defaultPage". Typically, the opening <form> tag supplies an action attribute that specifies the URL to which to submit the form data, as well as the method of transmitting that data itself (POST or GET). You will examine this aspect of the <form> tag in just a bit. For the time being, let’s look at the sorts of items that can be placed in an HTML form (beyond simple literal text). Visual Studio 2008 provides an HTML tab on the Toolbox that allows you to select each HTML-based UI widget, as shown in Figure 31-4.
Figure 31-4. The HTML tab of the Toolbox
Similar to the process of building a Windows Forms or WPF application, these HTML controls can be dragged onto the HTML designer surface. By default, the bottom pane of the HTML editor

1170 CHAPTER 31 ■ BUILDING ASP.NET WEB PAGES
will display the HTML visual layout, while the upper pane will show the related markup. Another benefit of this editor is that as you select markup or an HTML UI element, the corresponding representation is highlighted. This makes it very simple to see the scope of your changes (see Figure 31-5).
Figure 31-5. The Visual Studio 2008 HTML editor displays markup and UI layout.
Building an HTML-Based User Interface
Before you add the HTML widgets to the HTML <form>, it is worth pointing out that Visual Studio 2008 allows you to edit the overall look and feel of the *.htm file itself using the integrated HTML designer and the Properties window. If you select DOCUMENT from the drop-down list of the Properties window, as shown in Figure 31-6, you are able to configure various aspects of the HTML page, such as the background color, background image, title, and so forth.
Update the <body> of the default.htm file to display some literal text that prompts the user to enter a username and password, and choose a background color of your liking (be aware that you can enter and format literal textual content by typing directly in the HTML designer):
<html xmlns="http://www.w3.org/1999/xhtml" > <head>
<title>This is the Cars Web site</title> </head>
<body bgcolor="NavajoWhite">
<!-- Prompt for user input-->
<h1 align="center"> The Cars Login Page</h1> <p align="center"> <br/>
Please enter your <i>user name</i> and <i>password</i>. </p>
<form id="defaultPage"> </form>
</body>
</html>

CHAPTER 31 ■ BUILDING ASP.NET WEB PAGES |
1171 |
Figure 31-6. Editing an HTML document via the Visual Studio 2008 Properties window
Now let’s build the HTML form itself. In general, each HTML widget is described using a name attribute (used to identify the item programmatically) and a type attribute (used to specify which UI element you are interested in placing in the <form> declaration). Depending on which UI widget you manipulate, you will find additional attributes specific to that particular item that can be modified using the Properties window.
The UI you will build here will contain two text fields (one of which is a Password widget) and two button types (one to submit the form data and the other to reset the form data to the default values):
<!-- Build a form to get user info -->
<form id="defaultPage"> <p align="center">
User Name:
<input id="txtUserName" type="text" name="txtUserName"/></p> <p align="center">
Password:
<input name="txtPassword" type="password" id="txtPassword"/></p> <p align="center">
<input name="btnSubmit" type="submit" value="Submit" id="btnSubmit"/> <input name="btnReset" type="reset" value="Reset" id="btnReset"/>
</p>
</form>
Notice that you have assigned relevant names and IDs to each widget (txtUserName, txtPassword, btnSubmit, and btnReset). Of greater importance, note that each input item has an extra attribute named type that marks these buttons as UI items that automatically clear all fields to their initial values (type="reset"), mask the input as a password (type="password"), or send the form data to the recipient (type="submit"). Figure 31-7 displays the page thus far.