|
|
|
|
|||||||||||||||
ASP.Net UnleashedStephen WaltherChapter 6: Separating Code from PresentationIn 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 ComponentsIn 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 ComponentA business component is a Visual Basic class file. Whenever you create a component, you need to complete each of the following three steps:
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.vbImports 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.
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
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.
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.
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 Using Properties in a ComponentYou 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.vbImports 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.aspxImports 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 EventsYou 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.
Listing 6.6 register.vbImports 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 ApplicationsYou 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 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.vbImports 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:
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
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.vbImports 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 BehindUsing 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.vbImports 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 WorksIf 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 FilesYou 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 FileYou 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.vbImports 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 Compiling a Complete ASP.NET PageIn this chapter, you have examined various methods of moving the application logic out of an ASP.NET page and placing it in a |