In this conclusion to a three-part series on ASP.Net web programming, you'll take a look at how an ASP.Net application actually works. This article is excerpted from chapter one of Murach's ASP.NET 3.5 Web Programming with VB 2008, written by Anne Boehm (Murach, 2008; ISBN: 1890774472).
A quick preview of how an ASP.NET application works
With that as background, you’re ready to learn more about how an ASP.NET application works. That’s why this topic presents a quick preview of how the Order form in the Shopping Cart application works.
The files used by the Shopping Cart application
Figure 1-9 presents the Order form of the Shopping Cart application as it appears in the Web Forms Designer that you use when you develop web forms with Visual Studio 2008. In chapter 2, you’ll learn how to use this Designer, but for now just try to get the big picture of how this form works.
If you look at the Designer window in the middle of the IDE, you can see the table that’s used for this form as well as the label controls that are used to display the data for each product. You can also see that the smart tag menu for the drop-down list has been used to enable the AutoPostBack property. This means that the Order form will be posted back to the web server when the user selects an item from the drop-down list.
If you look at the Solution Explorer to the right of the Designer window, you can see the folders and files that this application requires. For now, though, just focus on the six code files that are summarized in the table in this figure. The first two files in this table, which are in the App_Code folder, are two files that represent business classes named CartItem and Product. Both of these files have vb as the extension, which means that they’re Visual Basic files.
The next four files in the table are for the two web forms, Cart and Order, with two files for each form. The files with aspx as the extension (Cart.aspx and Order.aspx) contain the code that represents the design of the form. This code consists of standard HTML code plus asp tags that define the server controls used on the forms. We refer to this as aspx code, because the files that contain the code have the aspx extension.
The other two files, which have aspx.vb as the extension, contain the Visual Basic code that controls the operation of the forms. These are called code-behind files because they provide the code behind the web forms. For instance, the Order.aspx.vb file is the code-behind file for the Order form.
Before I go on, you should realize that it isn’t necessary to store the aspx and Visual Basic code for a web form in separate files. Instead, ASP.NET lets you combine this code into a single aspx file. However, storing the aspx and Visual Basic code in separate files can simplify application development because it lets you separate the presentation elements for a page from its Visual Basic coding. This also makes it possible for HTML designers to work on the aspx files for an application, and then have Visual Basic programmers develop the code for the code-behind files.
The Order form in Design view
The aspx and Visual Basic files in the Shopping Cart application
Folder File
Description
App_Code
CartItem.vb
A class that represents an item in the shopping cart.
App_Code
Product.vb
A class that represents a product.
(root)
Cart.aspx
The aspx file for the Cart page.
(root)
Cart.aspx.vb
The code-behind file for the Cart page.
(root)
Order.aspx
The aspx file for the Order page.
(root)
Order.aspx.vb
The code-behind file for the Order page.
Description
For each web form in an application, ASP.NET 3.5 keeps two files. The file with the aspx extension holds the HTML code and the asp tags for the server controls. The file with the aspx.vb extension is the code-behind file that contains the Visual Basic code for the form.
If an ASP.NET 3.5 application requires other classes like business classes, they are kept in the App_Code folder.
Figure 1-9 The files used by the Shopping Cart application
To give you some idea of how aspx code works, figure 1-10 shows some of the aspx code for the Order form. All of this code is generated by Visual Studio as you use the Web Forms Designer to design a form, so you don’t have to code it. But you still should have a general understanding of how this code works.
The first set of tags for each web form defines a page directive that provides four attributes. Here, the Language attribute says that the language is Visual Basic, the CodeFile attribute says that the code-behind file is named Order.aspx.vb, and the Inherits attribute specifies the class named Order. In figure 1-12, you’ll see how the Order.aspx class inherits the Order class.
The second set of tags defines a DOCTYPE declaration, which tells the browser what version of HTML the HTML document uses. You can ignore this declaration for now, because you’ll learn more about it in chapter 5.
The Html tags mark the beginning and end of the HTML document, and the Head tags define the heading for the document. Here, the Title tags define the title that is displayed in the title bar of the browser when the page is run. In addition, the Style tags define the styles used by the page. As you’ll learn in chapter 5, this is just one way to define styles.
The content of the web page itself is defined within the Div tags, which are within the Body and Form tags. Notice that the first Form tag includes a Runat attribute that’s assigned a value of “server.” That indicates that the form will be processed on the server by ASP.NET. This attribute is required for all ASP.NET web forms and all ASP.NET server controls.
The asp tags within the Div tags define the server controls that appear on the page. For example, the asp:Image tags define an Image control, the asp:Label tags define a label control, the asp:DropDownList tags define a drop-down list, and the asp:Button tags define a button. Since these controls include the Runat attribute with a value of “server,” they will be processed on the server by ASP.NET. The last phase of this processing is rendering the controls, which means that the asp code is converted to standard HTML so the page can be displayed by a browser.
If you look at the asp code for the drop-down list, you can see that the AutoPostBack attribute has been set to True. That means that a postback will occur whenever the user selects an item from that list. Note that a postback will also occur whenever the user clicks the Add to Cart button. However, the AutoPostBack attribute isn’t required for this control because performing a postback is the default operation of a button.
Another attribute that you should notice is the PostBackUrl attribute for the last button in the aspx code. This attribute provides the path for the Cart.aspx file, which means that the Cart form will be requested when this button is clicked. That’s one way to switch from one form to another as an application is run, and you’ll see another in the next figure.
Although this has been a quick introduction to the aspx code for a web form, you should begin to see how this code defines a web page. In the next two chapters, though, you’ll learn more about this code. And just in case you need it, chapter 5 presents a complete crash course in HTML.
To give you some idea of how the Visual Basic code for a form works, figure 1-11 presents the code-behind file for the Order form. Here, I’ve highlighted the code that’s specific to ASP.NET, and all of the other code is standard Visual Basic code.
The first highlighted line is a Class statement that names the class, which has the same name as the form. Because this statement uses the Partial keyword, this is a partial class that must be combined with another partial class when it’s compiled. The second line of code in this class indicates that it inherits the System.Web.UI.Page class, which is the .NET class that provides all of the basic functionality of ASP.NET pages.
Each time the page is requested, ASP.NET initializes it and raises the Load event, which is handled by the Page_Load procedure. This procedure uses the IsPostBack property of the page to determine whether the page is being posted back to the server from the same page. If this property isn’t True, the DataBind method of the drop-down list is used to bind the products that are retrieved from a database to the list. You will often see the IsPostBack property used like this in a Page_Load procedure to determine whether or not a page is being posted back by the user.
The btnAdd_Click procedure is executed when the user clicks on the Add to Cart button on the Order page, which starts a postback. After this procedure adds the selected item to the cart, it uses the Redirect method of the Response property of the page to transfer to the Cart page. This is a second way to switch from one page to another.
To refer to the session state object, you use the Session property of the page. This is done in the GetCart procedure, which is the last procedure for the page. Here, if the session state object doesn’t already contain a cart, a new sorted list is added to the object. Otherwise, the current cart is retrieved from the session object as a sorted list. Either way, control returns to the calling procedure, which is the AddToCart procedure, and that procedure can add a cart item to the cart. In addition, the Cart page will have access to the cart when the Order page is redirected to the Cart page.
One coding point worth noting is that IsPostBack, Response, and Session are all properties of the page. As a result, you could code them with Page as a qualifier as in
Page.IsPostBack
However, since Page is the default object within a code-behind file, you can omit this reference.
Although this is just a quick introduction to a code-behind file, I hope it gives you some insight into the way code-behind files are coded. Keep in mind, though, that all of this code will be explained in detail in the next two chapters. For now, you just need a general idea of how the events are processed, how the IsPostBack property is used, how one web page can switch to another page, and how the session state object is used.
The code-behind file for the Order form (Order.aspx.vb)
Imports System.Data Partial Class Order Inherits System.Web.UI.Page
Private selectedProduct As Product
Protected Sub Page_Load(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.Load If Not IsPostBack Then ddlProducts.DataBind() End If selectedProduct = Me.GetSelectedProduct lblName.Text = selectedProduct.Name lblShortDescription.Text = selectedProduct.ShortDescription lblLongDescription.Text = selectedProduct.LongDescription lblUnitPrice.Text = FormatCurrency(selectedProduct.UnitPrice) imgProduct.ImageUrl = "Images\Products" & selectedProduct.ImageFile End Sub
Private Function GetSelectedProduct() As Product Dim productTable As DataView = CType(AccessDataSource1.Select( _ DataSourceSelectArguments.Empty), DataView) productTable.RowFilter = "ProductID = '" & ddlProducts.SelectedValue & "'" Dim productRow As DataRowView = productTable(0) Dim product As New Product product.ProductID = productRow("ProductID").ToString product.Name = productRow("Name").ToString product.ShortDescription = productRow("ShortDescription").ToString product.LongDescription = productRow("LongDescription").ToString product.UnitPrice = CDec(productRow("UnitPrice")) product.ImageFile = productRow("ImageFile").ToString Return product End Function
Protected Sub btnAdd_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles btnAdd.Click Dim cartItem As New CartItem cartItem.Product = selectedProduct cartItem.Quantity = CInt(txtQuantity.Text) Me.AddToCart(cartItem) Response.Redirect("Cart.aspx") End Sub
Private Sub AddToCart(ByVal cartItem As CartItem) Dim cart As SortedList = Me.GetCart Dim productID As String = selectedProduct.ProductID If cart.ContainsKey(productID) Then cartItem = CType(cart(productID), CartItem) cartItem.Quantity += CInt(txtQuantity.Text) Else cart.Add(productID, cartItem) End If End Sub
Private Function GetCart() As SortedList If Session("Cart") Is Nothing Then Session.Add("Cart", New SortedList) End If Return CType(Session("Cart"), SortedList) End Function
Figure 1-11The Visual Basic code for the Order form
The diagram in figure 1-12 shows what actually happens behind the scenes when a user requests a page of an ASP.NET 3.5 application. In step 1, the ASP.NET runtime reads the aspx file for the requested web page and generates a class and a partial class. The partial class contains the declarations for the form and the controls it contains and is given the same name as the partial class that’s defined by the code-behind file for the page (Order in this example). In step 2, these partial classes are compiled to create a single class that provides all of the event-handling code for the page. The result is stored in a single assembly (dll file).
The class that’s generated by the ASP.NET runtime contains the code that actually creates the ASP.NET page. This class gets its name from the aspx file for the web page plus _aspx, so its name is Order_aspx in this example. In step 3, this class is compiled and stored in another assembly. Because this class inherits the Order class, an object that is instantiated from the Order_aspx class will contain the code that creates the page, as well as the event-handling code provided by the Order class.
In step 4, after the page classes are compiled, the ASP.NET runtime calls the Visual Basic compiler to compile any class files that are in the application’s App_Code folder. For the Shopping Cart application, this means that the CartItem and Product classes are compiled and the result is saved in a single assembly.
After all the files are compiled into assemblies, ASP.NET creates an instance of the page and raises the appropriate events. Then, the events are processed by the event handlers for the page and the HTML for the page is rendered. To complete the round trip, the HTML document for the page is passed back to the web server and on to the user’s browser.
Please note that the first four steps are done only the first time an aspx page is accessed. That’s because ASP.NET caches the assemblies that are created by these steps. Then, when the page is accessed again, the saved assemblies are reused, so the application doesn’t have to be recompiled. However, ASP.NET does compare the time stamps on the source files with the time stamps on the dll files. If any of the source files have been modified since they were last compiled, ASP.NET automatically recompiles them.
How an ASP.NET application is compiled
What happens when an ASP.NET page is requested
The ASP.NET runtime processes the .aspx file and generates a partial class (Order) that contains the declarations for the form and its controls, and a class (Order_aspx) that contains the code that will initialize the form, instantiate the controls, and generate the HTML for the web page.
The Visual Basic compiler compiles the partial class that contains the control declarations with the partial class defined by the code-behind file for the form into an assembly (.dll) that provides the event-handling code for the requested page.
The Visual Basic compiler compiles the Order_aspx class, which inherits the first compiled class (Order), and saves the result as an assembly that’s executed when the page is requested.
If necessary, the Visual Basic compiler compiles any other class files that are stored in the application’s App_Code folder. These classes are saved in a single assembly.
ASP.NET creates an instance of the page from the page’s final assembly. Then, ASP.NET raises the appropriate events, which are processed by the event handlers for the page, and the page generates the HTML that’s passed back to IIS for the response.
Description
The first four steps of this process are done only the first time the aspx page is requested. After that, the page is processed directly from the compiled assemblies.
For the Default page, the name of the code-behind class is _Default.
Figure 1-12How an ASP.NET 3.5 application is compiled and run
Now that you’ve read this chapter, you should have a general understanding of how ASP.NET applications work and what software you need for developing these applications. With that as background, you’re ready to learn how to develop ASP.NET applications of your own. And that’s what you’ll learn to do in the next two chapters.
Terms
web application web page web form
session state session state object session ID
client/server application client
application state application state object
server
profile
HTTP (Hypertext Transfer Protocol) web browser
.NET Framework .NET Framework Class Library
web server
class
IIS (Internet Information Services) DBMS (database management system) LAN (local area network) intranet
namespace CLR (Common Language Runtime) IL (Intermediate Language) MSIL (Microsoft Intermediate
static web page HTML document
Language) Common Type System
HTML (Hypertext Markup Language) URL (Uniform Resource Locator) HTTP request HTTP response domain name
standalone environment development server SQL Server Express FPSE (FrontPage Server Extensions) FTP (File Transfer Protocol)
dynamic web page server control
FTP server business class
application server application mapping round trip postback state
You can download all of the applications that are presented in this book from our web site (www.murach.com). Then, you can run the applications, review all of their code, and experiment with them on your own system. For more information about downloading and running these applications, please read appendix A.
About the exercises
If you’re new to ASP.NET web programming, we recommend that you practice what you’ve learned after you finish each chapter in the first section of this book. To help you do that, we provide exercises for each of these chapters. Most of these exercises use directories and files that you can download from our web site. Before you start the exercises, then, you’ll need to install these directories and files. When you do, they’ll be placed in a directory named ASP.NET 3.5 VB on your C drive.
By the time you complete section 1, you should be ready to start building applications of your own. Because of that, we don’t include exercises for the remaining chapters. Instead, as you go through each chapter, you can use the techniques that are illustrated on your own application. When you’re done, you can compare your application with the one you’ve downloaded.
Exercise 1-1 Use your web browser to run Internet applications
Open your web browser and type in this URL:
http://www.microsoft.com Then, search for information about Visual Web Developer 2008 Express Edition. This of course is the site that you can use to download Visual Web Developer 2008 Express and SQL Server 2005 Express for free. As you move from page to page, note that some are static html pages and others are dynamic aspx pages.
Type this URL into your web browser:
http://www.discountasp.net Then, click on some of the links on the home page, and note which pages are static and which are dynamic.
Exercise 1-2 Use your web browser to run the Shopping Cart application on your PC
In this exercise, you’ll use your web browser to run the Shopping Cart application that’s illustrated in this chapter. This assumes that you’ve already installed IIS, Visual Studio 2008, and the files for these exercises. When you get this application running, you’ll know that you’ve got IIS and the application set up correctly on your PC.
Create a virtual directory for the Shopping Cart application
Use the procedure in figure B-1 of appendix B (Windows XP) or figure C-1 of appendix C (Windows Vista) to create a virtual directory named Ch01Cart for the application in C:\ASP.NET 3.5 VB\Ch01Cart.
Run the Shopping Cart application
Open your web browser, and type in the following URL, which uses the virtual directory as the path:
http://localhost/Ch01Cart/Order.aspx This should start the Shopping Cart application that’s shown in figure 1-1. If it doesn’t, you need to make sure that IIS is installed, that the exercise files are installed, and that you did step 1 correctly.
Select a product from the drop-down list on the Order page that’s displayed. Note that this starts a postback that returns the Order page with the data and image for the product that was selected.
Enter a quantity and click the Add to Cart button to display the Cart page. Then, click the Continue Shopping button to return to the Order page.
Continue to experiment with this application until you understand how it works. Then, click the Close button in the upper right corner of the browser window to end the application.