ASP.Net Unleashed

Stephen Walther

Chapter 6: Separating Code from Presentation

In This Chapter

Web developers are not necessarily good designers. Most companies divide the task of building Web sites between two teams. Normally, one team is responsible for the design content of a page, and the other team is responsible for the application logic.

Maintaining this separation of tasks is difficult when both the design content and application logic are jumbled together on a single page. A carefully engineered ASP.NET page can be easily garbled after being loaded into a design program. Likewise, a beautifully designed page can quickly become mangled in the hands of an engineer.

In this chapter, you learn two methods of dividing your application code from your presentation content. In other words, you learn how to keep both your design and engineering teams happy.

First, you learn how to package application code into custom business components. Using a business component, you can place all your application logic into a separate Visual Basic class file. You also learn how to use business components to build multitiered Web applications.

Next, you learn how to take advantage of a feature of ASP.NET pages named code behind. Using code behind, you can place all your application logic into a file and create one or more ASP.NET pages that inherit from this file. Code behind is the technology used by Visual Studio.NET to divide presentation content from application logic.

Creating Business Components

In this section, you learn how to create business components using Visual Basic and use the components in an ASP.NET page. Business components have a number of benefits:

Creating a Simple Business Component

A business component is a Visual Basic class file. Whenever you create a component, you need to complete each of the following three steps:

  1. Create a file that contains the definitions for one or more Visual Basic classes and save the file with the extension .vb.

  2. Compile the class file.

  3. Copy the compiled class file into your Web application's /BIN directory.

Start by creating a simple component that randomly displays different quotations. You can call this component the quote component. First, you need to create the Visual Basic class file for the component. The quote component is contained in Listing 6.1.

Listing 6.1  quote.vb

Imports System

Namespace myComponents

Public Class quote

 Dim myRand As New Random

 Public Function showQuote() As String
  Select myRand.Next( 3 )
   Case 0
    showQuote = "Look before you leap"
   Case 1
    showQuote = "Necessity is the mother of invention"
   Case 2
    showQuote = "Life is full of risks"
  End Select
 End Function

End Class

End Namespace

The first line in Listing 6.1 imports the System namespace. You need to import this namespace because you use the Random class in your function, and the Random class is a member of the System namespace.


Note

You don't have to import the System, System.Collections, System.IO, System. Web, System.Web.UI, System.Web.UI.HTMLControls, or System.Web.UI. WebControls namespaces in an ASP.NET page because these namespaces are automatically imported by default. However, a Visual Basic class file does not have default namespaces.


Next, you need to create your own namespace for the class file. In Listing 6.1, you created a new namespace called myComponents. You could have created a namespace with any name you pleased. You need to import this namespace when you create the ASP.NET page that uses this component.

The remainder of Listing 6.1 contains the declaration for your Visual Basic class. The class has a single function, named showQuote(), that randomly returns one of three quotations. This function is exposed as a method of the quote class.

After you write your component, you need to save it in a file that ends with the extension .vb. Save the file in Listing 6.1 with the name quote.vb.

The next step is to compile your quote.vb file by using the vbc command-line compiler included with the .NET framework. Open a DOS prompt, navigate to the directory that contains the quote.vb file, and execute the following statement (see Figure 6.1):

vbc /t:library quote.vb

The /t option tells the compiler to create a DLL file rather than an EXE file.

Figure 6.1
Compiling a component.


Note

If you use either Web or HTML controls in your component, you need to add a reference to the system.web.dll assembly when you compile the component like this:

vbc /t:library /r:system.web.dll quote.vb

All the classes in the .NET framework are contained in assemblies. If you use a specialized class (one not contained in the System assembly), you need to reference the proper assembly when you compile the component.


If no errors are encountered during compilation, a new file named quote.dll should appear in the same directory as the quote.vb file. You now have a compiled business component.

The final step is to move the component to a directory where the Web server can find it. To use the component in your ASP.NET pages, you need to move it to a special directory named /BIN. If this directory does not already exist, you can create it.


ASP Classic Note

You do not need to register the component in the server's Registry by using a tool such as regsvr32.exe. Information about ASP.NET components is not stored in the Registry. This means that you can copy a Web application to a new server, and all the components immediately work on that new server.


The /BIN directory must be an immediate subdirectory of your application's root directory. By default, the /BIN directory should be located under the wwwroot directory. However, if your application is contained in a Virtual Directory, you must create the /BIN directory in the root directory of the Virtual Directory.

Immediately after you copy the component to the /BIN directory, you can start using it in your ASP.NET pages. For example, the page in Listing 6.2 uses the quote component to assign a random quote to a Label control.


ASP Classic Note

Great news! You no longer need to stop and restart your Web server to start using a component whenever you modify it. As soon as you move a component into the /BIN directory, the new component will be used for all new page requests.

ASP.NET components are not locked on disk because the Web server maintains shadow copies of all the components in a separate directory. When you replace a component in the /BIN directory, the Web server completes all the current page requests using the old version of the component in the shadow directory. As soon as all the current requests are completed, the shadow copy of the old component is automatically replaced with the new component.


Listing 6.2  showquote.aspx

<%@ Import Namespace="myComponents" %>

<Script Runat="Server">

Sub Page_Load( s As Object, e As EventArgs )
 Dim myQuote As New Quote
 myLabel.Text = myQuote.ShowQuote()
End Sub

</Script>

<html>
<head><title>showquote.aspx</title></head>
<body>

And the quote is...
<br>
<asp:Label
 ID="myLabel"
 Runat="Server" />

</body>
</html>

The first line in Listing 6.2 imports the namespace. After the namespace is imported, you can use your component just like any .NET class.

In the Page_Load subroutine, you create an instance of your component. Next, you call the ShowQuote() method of the component to assign a random quotation to the Label control (see Figure 6.2).

Figure 6.2
Output of the quote component.

Using Properties in a Component

You can add properties to a component in two ways. Either you can create public variables, or you can use property accessor syntax.

Adding properties by using public variables is the easiest method. For example, the component in Listing 6.3 has two variables named firstValue and secondValue. Because these variables are exposed as public variables, you can access them as properties of the object.

Listing 6.3  adder.vb

Imports System

Namespace myComponents

Public Class adder

 Public firstValue As Integer
 Public secondValue As Integer

 Function AddValues() As Integer
  Return firstValue + secondValue
 End Function

End Class

End Namespace

The component in Listing 6.3 is named the adder component. It simply adds together the values of whatever numbers are assigned to its properties and returns the sum in the AddValues() function.

The ASP.NET page in Listing 6.4 illustrates how you can use the adder component to add the values entered into two TextBox controls.

Listing 6.4  addValues.aspx

<%@ Import Namespace="myComponents" %>

<Script Runat="Server">

 Sub add( s As Object, e As EventArgs )
  Dim myAdder As New Adder
  myAdder.FirstValue = val1.Text.ToInt32()
  myAdder.SecondValue = val2.Text.ToInt32()
  Output.Text = myAdder.AddValues()
 End Sub

</Script>

<html>
<head><title>addValues.aspx</title></head>
<body>

<form Runat="Server">

Value 1:
<asp:TextBox
 ID="val1"
 Runat="Server" />

<p>

Value 2:
<asp:TextBox
 ID="val2"
 Runat="Server" />

<p>
<asp:Button
 Text="Add!"
 OnClick="add"
 Runat="Server" />

<p>
Output:
<asp:Label
 ID="output"
 Runat="Server" />

</form>

</body>
</html>

You also can expose properties in a component by using property accessor syntax. Using this syntax, you can define a Set function that executes every time you assign a value to a property and a Get function that executes every time you read a value from a property. You can then place validation logic into the property's Get and Set functions to prevent certain values from being assigned or read.

The modified version of the adder component in Listing 6.5, for example, uses property accessor syntax.

Listing 6.5  adder2.aspx

Imports System

Namespace myComponents

Public Class adder2

 Private _firstValue As Integer
 Private _secondValue As Integer

 Public Property firstValue As Integer
  Get
   Return _firstValue
  End Get
  Set
   _firstValue = Value
  End Set
 End Property

 Public Property secondValue As Integer
  Get
   Return _secondValue
  End Get
  Set
   _secondValue = Value
  End Set
 End Property

 Function AddValues() As Integer
  Return _firstValue + _secondValue
 End Function

End Class

End Namespace

The modified version of the adder component in Listing 6.5 works in exactly the same way as the original adder component. When you assign a new value to the firstValue property, the Set function executes and assigns the value to a private variable named _firstValue. When you read the firstValue property, the Get function executes and returns the value of the private _firstvalue variable.

The advantage of using accessor functions with properties is that you can add validation logic into the functions. For example, if you never want someone to assign a value less than 0 to the firstValue property, you can declare the firstValue property like this:

Public Property firstValue As Integer
 Get
  Return _firstValue
 End Get
 Set
  If value < 0 Then
  _firstValue = 0
  Else
  _firstValue = Value
  End If
 End Set
End Property

This Set function checks whether the value passed to it is less than 0. If the value is, in fact, less than 0, the value 0 is assigned to the private _firstValue variable.

Using a Component to Handle Events

You can use components to move some, but not all, of the application logic away from an ASP.NET page to a separate compiled file.

Imagine, for example, that you want to create a simple user registration form with an ASP.NET page. When someone completes the user registration form, you want the information to be saved in a file. You also want to use a component to encapsulate the logic for saving the form data to a file.

Listing 6.6 contains a simple user registration component. This component has a subroutine named doRegister that accepts three parameters: firstname, lastname, and favColor. The component saves the values of these parameters to a file named userlist.txt.


Note

File access in the .NET framework is discussed in detail in Chapter 25, "Working with the File System."


Listing 6.6  register.vb

Imports System
Imports System.IO

Namespace myComponents

Public Class register

 Sub doRegister( firstname As String, lastname As String, favColor As String )
  Dim myPath As String = "c:\userlist.txt"
  Dim myFile As StreamWriter
  myFile = File.AppendText( myPath )
  myFile.Write( "first name: " & firstname & Environment.NewLine )
  myFile.Write( "last name: " & lastname & Environment.NewLine )
  myFile.Write( "favorite Color: " & favColor & Environment.NewLine )
  myFile.Write( "=============" & Environment.NewLine )
  myFile.Close
 End Sub

End Class

End Namespace

After you compile the register.vb file and copy the compiled component to the /BIN directory, you can use the component in an ASP.NET page. The page in Listing 6.7 demonstrates how you can use the register component.

Listing 6.7  userRegistration.aspx

<%@ Import Namespace="myComponents" %>
<Script Runat="Server">

 Sub doSomething( s As Object, e As EventArgs )
  Dim myReg As New Register
  myReg.doRegister( firstname.Text, lastname.Text, favColor.Text )
 End Sub

</Script>

<html>
<head><title>userRegistration.aspx</title></head>
<body>

<form Runat="Server">

First Name:
<br>
<asp:TextBox
 ID="firstname"
 Runat="Server" />

<p>
Last Name:
<br>
<asp:TextBox
 ID="lastname"
 Runat="Server" />

<p>
Favorite Color:
<br>
<asp:TextBox
 ID="favColor"
 Runat="Server" />

<p>
<asp:Button
 Text="Register!"
 OnClick="doSomething"
 Runat="Server" />

</form>

When someone completes the form and clicks the button, the doSomething subroutine is executed. This subroutine creates an instance of the register component and calls its doRegister() method to save the form data to a file.

Notice that you must still place some of the application logic in the userRegistration.aspx page. In the doSomething subroutine, you must pass the values entered into each of the TextBox controls to the doRegister() method. You are forced to do so because you cannot refer directly to the controls in userRegistration.aspx from the register component.

Later in this chapter, in the discussion of code behind, you learn how to move all your application logic into a separate compiled file.

Creating Multitiered Web Applications

You can use components to divide your Web application into multiple layers, thereby creating a multitiered application. For example, in a two-tiered application, you might have a user interface layer built from ASP.NET pages and a data layer built from components. In a three-tiered application, you might introduce a third layer, representing your application's business logic, between the user interface and data layers.

Why would you want to create multiple layers? The advantage of dividing an application into multiple layers is that you can more easily manage and change the application.

In the preceding section, for example, you created a component that enables you to save form information to a file. In essence, you created a single component for the data layer. Now suppose that your needs change, and you decide to save the data to a database table instead of a file. In that case, you need to modify only the component. You don't have to touch a line of code in the ASP.NET page itself. In other words, you can isolate changes in the data layer from changes in the user interface layer.

An additional benefit of dividing an application into multiple layers is that doing so makes it easier for multiple teams of programmers to work on the same application at the same time. If all the application logic is contained in a single page, you face the problem of multiple programmers stumbling over each other while performing modifications.

To illustrate these points, you can construct a simple three-tiered Web application consisting of user interface, business, and data layers to create a simple order entry application.

The application consists of the following three objects:

First, build the user interface layer. The ASP.NET page for the user interface is contained in Listing 6.8. The page requests five pieces of information: the customer name, product, unit price of the product, quantity, and customer's state of residence (see Figure 6.3).

Figure 6.3
A simple order form.

Listing 6.8  orderform.aspx

<%@ Import Namespace="myComponents" %>

<Script Runat="Server">

 Sub PlaceOrder( s As Object, e As EventArgs )
  Dim myBizObject As New BizObject
  If isValid Then
  Try
  myBizObject.CheckOrder( _
   customer.Text, _
    Product.SelectedItem.Text, _
     unitPrice.Text.ToDouble, _
     Quantity.Text.ToInt32, _
      StateOfResidence.SelectedItem.Text )
  Catch myEx As Exception
   errorLabel.Text = myEx.Message
  End Try
  End If
 End Sub

</Script>

<html>
<head><title>orderform.aspx</title></head>
<body>

<form Runat="Server">

<h2>Enter an Order:</h2>

<asp:Label
 ID="errorLabel"
 forecolor="Red"
 font-bold="True"
 MaintainState="False"
 Runat="Server" />

<p>
Customer Name:
<br>
<asp:TextBox
 ID="customer"
 Runat="Server" />

<asp:RequiredFieldValidator
 ControlToValidate="customer"
 Text="You must enter a customer name!"
 Runat="Server" />

<p>
Product:
<br>
<asp:ListBox
 ID="Product"
 Runat="Server">
 <asp:ListItem Text="Hair Dryer" />
 <asp:ListItem Text="Shaving Cream" />
 <asp:ListItem Text="Electric Comb" />
</asp:ListBox>

<asp:RequiredFieldValidator
 ControlToValidate="Product"
 Text="You must select a product!"
 Runat="Server" />

<p>
Unit Price:
<br>
<asp:TextBox
 ID="unitPrice"
 Runat="Server" />

<asp:RequiredFieldValidator
 ControlToValidate="unitPrice"
 Text="You must enter a Unit Price!"
 Runat="Server" />


<p>
Quantity:
<br>
<asp:TextBox
 ID="quantity"
 Runat="Server" />

<asp:RequiredFieldValidator
 ControlToValidate="quantity"
 Text="You must enter a quantity!"
 Runat="Server" />

<asp:CompareValidator
 ControlToValidate="quantity"
 Text="Quantity must be a number!"
 Operator="DataTypeCheck"
 Type="Integer"
 Runat="Server" />

<p>
Customer State:
<br>
<asp:DropDownList
 ID="StateOfResidence"
 Runat="Server">
 <asp:ListItem Text="California" />
 <asp:ListItem Text="Nevada" />
 <asp:ListItem Text="Washington" />
</asp:DropDownList>

<p>
<asp:Button
 Text="Place Order"
 OnClick="placeOrder"
 Runat="Server" />

</form>

</body>
</html>

When all the information is entered into the form, and the Place Order button is clicked, the placeOrder subroutine executes. This subroutine creates an instance of the BizObject component and passes all the form information to the component's CheckOrder() method.

The business component is contained in Listing 6.9.

Listing 6.9  BizObject.vb

Imports System

Namespace myComponents

Public Class bizObject

 Sub checkOrder( customer As String, _
  product As String, _
   unitPrice As Double, _
    quantity As Integer, _
     state As String )

  If quantity <= 0 Or quantity > 100 Then
   Throw New ArgumentException( "Invalid Quantity!" )
  End If

  If state = "California" And Product="Hair Dryer" Then
   Throw New ArgumentException( "Californians cannot own Hair Dryers!" )
  End IF

  If state = "Washington" Then
   unitPrice += unitPrice * .06
  End If

  Dim myDataObject As New DataObject
  myDataObject.SaveOrder( customer, product, unitPrice, quantity, state )

 End Sub

End Class

End Namespace

The business component contains all the business rules for the application. The component encapsulates the following rules:

  1. The product quantity must be greater than 0 and less than 100.

  2. People who live in California cannot buy hair dryers.

  3. People who live in Washington must pay an additional 6% sales tax.

If an order fails either of the first two requirements, an exception is raised. The error is caught in the orderentry.aspx page and displayed in a Label control. For example, Figure 6.4 displays what happens when you try to order more than 100 products.

Figure 6.4
Raising an exception in the order form.


Note

Exceptions and Try..Catch blocks are discussed in detail in Chapter 18, "Application Tracing and Error Handling."


If an order satisfies all the business rules, it is passed to the SaveOrder() method of the DataObject component, which saves the order to disk. This component is contained in Listing 6.10.

Listing 6.10  DataObject.vb

Imports System
Imports System.IO

Namespace myComponents

Public Class dataObject

 Sub saveOrder( customer As String, _
  product As String, _
   unitPrice As Double, _
    quantity As Integer, _
     state As String )

  Dim myPath As String = "c:\orders.txt"
  Dim myFile As StreamWriter
  myFile = File.AppendText( myPath )
  myFile.Write( "customer: " & customer & Environment.NewLine )
  myFile.Write( "product: " & product & Environment.NewLine )
  myFile.Write( "unit price: " & unitPrice.ToString() & Environment.NewLine )
  myFile.Write( "quantity: " & quantity.ToString() & Environment.NewLine )
  myFile.Write( "state: " & state & Environment.NewLine )
  myFile.Write( "=============" & Environment.NewLine )
  myFile.Close
 End Sub

End Class

End Namespace

Remember that you must compile both the BizObject and DataObject components and copy them to your application's /BIN directory before you can use them. The order of compilation is important. Because the BizObject component refers to the DataObject component, you must create the DataObject component first. You can compile this component by using the following statement (executed from a DOS prompt):

vbc /t:library DataObject.vb

After you copy the DataObject.dll file to your application's /BIN directory, you can compile the BizObject component by using the following statement:

vbc /t:library /r:DataObject.dll bizObject.vb

Notice the /r option used when compiling the BizObject component; it references the DataObject.dll file. If you don't include this reference, you receive the error User-defined type not defined: DataObject.

Using Code Behind

Using components is an excellent method of moving your application logic outside your ASP.NET pages. However, as you have seen, components have one serious shortcoming. Because you cannot directly refer to the controls contained in an ASP.NET page from a component, you cannot move all your application logic out of the page.

In this section, you learn about a second method of dividing presentation content from code that remedies this deficiency. You learn how to take advantage of a feature of ASP.NET pages called code behind.

You can use code behind to cleanly divide an ASP.NET page into two files. One file contains the presentation content, and the second file, called the code behind file, contains all the application logic.

Start with a page that has both its presentation content and application code jumbled together in one file. This page is shown in Listing 6.11.

Listing 6.11  jumble.aspx

<Script Runat="Server">

 Sub doSomething( s As Object, e As EventArgs )
  myLabel.Text = "Hello!"
 End Sub

</Script>

<html>
<head><title>jumble.aspx</title></head>
<body>

<form Runat="Server">

<asp:Button
 Text="Click Here!"
 OnClick="doSomething"
 Runat="Server" />

<p>

<asp:Label
 ID="myLabel"
 Runat="Server" />

</form>

</body>
</html>

The page in Listing 6.11 contains one Button control and one Label control. When you click the button, the doSomething subroutine executes and a message is assigned to the label.

Now, you can divide this page into separate presentation and code behind files. The presentation file is simple; it just contains everything but the doSomething subroutine. It also contains an additional page directive at the top of the file.

Listing 6.12  presentation.aspx

<%@ page inherits="myCodeBehind" src="codebehind.vb" %>
<html>
<head><title>presentation.aspx</title></head>
<body>

<form Runat="Server">

<asp:Button
 Text="Click Here!"
 OnClick="doSomething"
 Runat="Server" />

<p>

<asp:Label
 ID="myLabel"
 Runat="Server" />

</form>

</body>
</html>

The code behind file, contained in Listing 6.13, is a little more complicated. It consists of an uncompiled Visual Basic class file.

Listing 6.13  codebehind.vb

Imports System
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls

Public Class myCodeBehind
 Inherits Page

 Protected WithEvents myLabel As Label

 Sub doSomething( s As Object, e As EventArgs )
  myLabel.Text = "Hello!"
 End Sub


End Class

That's it. That's all you need to do to cleanly divide a page into separate files for presentation content and application logic. If you save the presentation.aspx and codebehind.vb files anywhere on your Web server, you can immediately open the presentation.aspx file in a Web browser, and the page will work as expected.

Notice that you do not even have to compile the code behind file. The Visual Basic class contained in the code behind file is compiled automatically when you request the presentation.aspx page.

How Code Behind Really Works

If you look closely at the Visual Basic class declared in the code behind file in the preceding section, you notice that the myCodeBehind class inherits from the Page class. The class definition for myCodeBehind begins with the following statement:

Inherits Page

When you create a code behind file, you are actually creating an instance of an ASP.NET page. You're explicitly building a new ASP.NET page in a class file by inheriting from the Page class.

Code behind pages use an additional level of inheritance. The page used for the presentation content in the preceding section, presentation.aspx, inherits from the code behind file. The first line of presentation.aspx is as follows:

<%@ page inherits="myCodeBehind" src="codebehind.vb" %>

The presentation page inherits all the properties, methods, and events of the code behind file. When you click the button, the doSomething subroutine executes because the presentation page is inherited from a class that contains this subroutine.

So, the code behind file inherits from the Page class, and the presentation file inherits from the code behind file. Because this hierarchy of inheritance exists, all the properties, methods, and events of the Page class are available in the code behind file, and all the properties, methods, and events in the code behind file are available to the presentation file.

When using code behind files, you must be careful to declare an instance of each control used in the presentation file within the code behind file. For example, in the code behind file, you refer to the myLabel control in the doSomething subroutine. So, you have to explicitly declare the control in the code behind file like this:

Protected WithEvents myLabel As Label

If you neglect to include this declaration, you would receive the error The name 'myLabel' is not declared when attempting to open the presentation page in a browser.

Compiling Code Behind Files

You don't need to compile a code behind file. The class file contained in a code behind file is compiled automatically when you request the presentation page. If you prefer, however, there is nothing to prevent you from compiling it. For example, to compile a code behind file named codebehind.vb, execute the following statement from a DOS prompt in the same directory as your code behind file:

vbc /t:library /r:system.web.dll codebehind.vb

This statement compiles a code behind file named codebehind.vb into a file named codebehind.dll. The /t option indicates that a DLL file should be created. The /r option references the system.web.dll assembly. (All the Web control classes inhabit this assembly.)

After you compile the code behind file into codebehind.dll, you need to move this file to your application's /BIN directory.

Finally, modify the page directive on the presentation page. Change the page directive from

<%@ page inherits="myCodeBehind" src="codebehind.vb" %>

to

<%@ page inherits="myCodeBehind" %>

You no longer need the src attribute because the compiled code behind file is located in the /BIN directory. The compiled classes in the /BIN directory are automatically available to use in all the ASP.NET pages in an application.

Inheriting Multiple Pages from a Code Behind File

You can inherit multiple presentation pages from the same code behind file. In fact, if you really want to, you could inherit all the pages in your Web site from a single code behind file.

Why is this capability useful? Imagine that you have a set of functions and subroutines that you need to call in almost every page. You can place the functions and subroutines in your code behind file, and they are immediately available in any page that inherits from the code behind file.

The code behind file in Listing 6.14, for example, has one subroutine and one function. The subroutine is the standard Page_Load subroutine that executes whenever a page is first loaded. The utility function named headerMessage returns the current date.

Listing 6.14  codebehind2.vb

Imports System
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls

Public Class myCodeBehind2
 Inherits Page

 Protected WithEvents header As Label

 Overridable Sub Page_Load( s As Object, e As EventArgs )
  header.Text = headerMessage()
 End Sub


 Function headerMessage() As String
  Dim tempMessage As String
  tempMessage = "Welcome to this Web site!<br>"
  tempMessage += "The current date is "
  tempMessage += DateTime.Now.Format( "D", Nothing )
  Return tempMessage
 End Function


End Class

Any page that derives from the code behind file in Listing 6.14 inherits both the Page_Load subroutine and headerMessage() function. For example, the presentation page in Listing 6.15 automatically uses the Page_Load subroutine from the code behind file.

Listing 6.15  presentation2.aspx

<%@ page inherits="myCodeBehind2" src="codebehind2.vb" %>

<html>
<head><title>presentation2.aspx</title></head>
<body>

<form Runat="Server">

<asp:Label
 ID="header"
 Runat="Server" />


<h2>Page 1</h2>



</form>

</body>
</html>

When you open the page contained in Listing 6.15, the Page_Load subroutine from the code behind file executes, and the header Label is assigned the text from the headerText() function.

Now, imagine that you want to use the Page_Load subroutine declared in the code behind file in some pages that inherit from the code behind file but not others. Because you declared the Page_Load subroutine as Overridable, you can override it in a presentation page.

The page in Listing 6.16, for example, overrides the Page_Load subroutine with its own Page_Load subroutine and displays a custom message in the header Label.

Listing 6.16  presentation3.aspx

<%@ page inherits="myCodeBehind2" src="codebehind2.vb" %>

<Script Runat="Server">

 Overrides Sub Page_Load( s As Object, e As EventArgs )
  header.Text = "Who cares about the current date?"
 End Sub

</Script>


<html>
<head><title>presentation2.aspx</title></head>
<body>

<form Runat="Server">

<asp:Label
 ID="header"
 Runat="Server" />


<h2>Page 2</h2>



</form>

</body>
</html>

Notice that the Page_Load subroutine uses the Overrides modifier, which overrides the Page_Load subroutine declared in the code behind file. You can set it up this way because the Page_Load subroutine was declared with the Overridable modifier.

Now, try one last example. Imagine that you want to create a page that executes the Page_Load subroutine in the code behind file but also executes a Page_Load subroutine of its own. You can extend the subroutine in the code behind file within a presentation file by overriding the original subroutine and calling the original subroutine in the new subroutine. In other words, you can extend the code behind subroutine in your presentation file.

The presentation page in Listing 6.17 illustrates how you would do so.

Listing 6.17  presentation4.aspx

<%@ page inherits="myCodeBehind2" src="codebehind2.vb" %>

<Script Runat="Server">

 Overrides Sub Page_Load( s As Object, e As EventArgs )
  myBase.Page_Load( s, e )
  header.Text &= "<br>And the current time is "
  header.Text &= Now.Format( "t", Nothing )

 End Sub

</Script>


<html>
<head><title>presentation4.aspx</title></head>
<body>

<form Runat="Server">

<asp:Label
 ID="header"
 Runat="Server" />


<h2>Page 3</h2>



</form>

</body>
</html>

In Listing 6.17, the Page_Load subroutine overrides the Page_Load subroutine from the code behind file. However, notice this statement:

myBase.Page_Load( s, e )

This statement invokes the Page_Load subroutine in the code behind file. The Visual Basic myBase keyword refers to the base class that the current class is derived from. Therefore, when the page contained in Listing 6.17 is opened in a browser, the Page_Load subroutines in both the code behind file and presentation file are executed. The page in Figure 6.5 is displayed.

Figure 6.5
Extending a code behind subroutine.

Compiling a Complete ASP.NET Page

In this chapter, you have examined various methods of moving the application logic out of an ASP.NET page and placing it in a separate file. In this section, I want to discuss an extreme case. How would you go about compiling all of an ASP.NET page, including both the presentation content and application code?

You might want to compile a complete page in several circumstances. For example, imagine that you have developed an e-Commerce Web site, and you want to sell the site to multiple clients. When you distribute the site, you might not want the clients to be able to view the source code. If you compile all the pages in your application, all the source code is hidden from view.

You can compile an ASP.NET page by placing all its contents into a code behind file. In the code behind file, you must explicitly declare all the controls and all the static content that appears in the page.

The code behind file in Listing 6.18 contains a complete ASP.NET page in a Visual Basic class.

Listing 6.18  myPage.vb

Imports System
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls

Public Class myPage
 Inherits Page

 Dim myTextBox As New TextBox
 Dim myLabel As New Label

 Protected Overrides Sub CreateChildControls

 ' Add Opening HTML Tags
 Dim OpenHTML As String
 OpenHTML = "<html><head><title>My Page</title></head>"
 OpenHTML &= "<body>Enter some text:"
 Controls.Add( New LiteralControl( OpenHTML ) )

 ' Add HTMLForm Tag
 Dim myForm As New HTMLForm
 myForm.ID = "myForm"
 Controls.Add( myForm )


 ' Add a TextBox
 myTextBox.ID = "myTextBox"
 myForm.Controls.Add( myTextBox )

 ' Add a Button
 Dim myButton As New Button
 myButton.Text = "Click Here!"
 AddHandler myButton.Click, AddressOf doSomething
 myForm.Controls.Add( myButton )

 ' Add Page Break
 myForm.Controls.Add( New LiteralControl( "<p>" ) )

 ' Add a Label
 myLabel.ID = "myLabel"
 myForm.Controls.Add( myLabel )


 ' Add Closing HTML Tags
 Dim CloseHTML As String
 CloseHTML = "</form></body></html>"
 Controls.Add( New LiteralControl( CloseHTML ) )

 End Sub

 Sub doSomething( s As Object, e As EventArgs )
  myLabel.Text = myTextBox.Text
 End Sub

End Class

The bulk of the code in Listing 6.18 is contained in a subroutine called CreateChildControls. In this subroutine, you create each of the controls that you want to appear in your ASP.NET page.

To add static content to the page, you use the LiteralControl control. For example, you use LiteralControl to create the opening HTML tags at the beginning of the CreateChildControls subroutine and the closing HTML tags at the end of the subroutine.

You also add all the Web controls to the page within the CreateChildControls subroutine. First, you add an HTMLForm control to the page's Controls collection. Next, you add TextBox, Button, and Label controls to the HTMLForm's Controls collection.

Finally, your page class contains a subroutine named doSomething. This subroutine is executed when you click the button. The doSomething subroutine assigns whatever text was entered into the TextBox control to the Label control.

To wire up the doSomething control to the Button control, you use the following statement:

AddHandler myButton.Click, AddressOf doSomething

This statement adds an event handler to the Click event of the Button control. It associates the doSomething subroutine with the Button Click event. So, whenever the button is clicked, the doSomething subroutine is executed.

After you create the page class in Listing 6.18, you can compile it by using the following statement:

vbc /t:library /r:system.web.dll myPage.vb

After the page is compiled, you need to move it to your application's /BIN directory.

Finally, to request the compiled page in a Web browser, you have to create one additional file. This file is contained in Listing 6.19.

Listing 6.19  showMyPage.aspx

<%@ Page inherits="myPage" %>

As you can see, the showMyPage.aspx file contains a single line; it's a page directive indicating that the current page should inherit from the myPage class. When you open showMyPage.aspx in a Web browser, the ASP.NET page created in the code behind file is displayed.

Summary

In this chapter, you examined two methods of dividing a page's application logic from its design content. First, you learned how to create custom business components using Visual Basic class files and discovered how to use components to create multitiered Web applications.

In the second half of this chapter, you learned how to take advantage of code behind. You learned how to divide an ASP.NET page into a presentation file and a code behind file. Finally, you examined a method of compiling a complete ASP.NET page.