Chapter 6: Separating Code from Presentation
Chapter 6: Separating Code from Presentation
In This Chapter
Creating Business Components
Creating Multitiered Web Applications
Using Code Behind
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:
Business components enable you to divide presentation content from application logic. You can design an attractive ASP.NET page and package all the page's application logic into a business component.
Business components promote code reuse. You can write a library of useful subroutines and functions, package them into a business component, and reuse the same code on multiple ASP.NET pages.
Business components are compiled. You therefore can distribute a component without worrying about the source code being revealed or modified.
Business components can be written in multiple languages. Some developers like working with Visual Basic, some prefer C# or C++, and some even like COBOL and Perl. You can write components with different languages and combine the components into a single ASP.NET page. You can even call methods from a component written in one language from a component written in another language.
Business components enable you to build multitiered Web applications. For example, you can use components to create a data layer that abstracts away from the design specifics of a particular database. Or you can write a set of components that encapsulate your business logic.
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:
Create a file that contains the definitions for one or more Visual Basic classes and save the file with the extension .vb.
Compile the class file.
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.
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.
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).
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.
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.