Home > Articles > Programming > Windows Programming

Separating Code from Presentation

  • Print
  • + Share This
Do you want to keep both your design and engineering teams happy? In this sample chapter, you learn two methods of dividing your application code from your presentation content.
This sample chapter is excerpted from ASP.NET Unleashed (Sams, 2001, ISBN: 0672320681), by Stephen Walther.
This chapter is from the book

This chapter is from the book

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 article, 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.

NOTE

You can view "live" versions of many of the code samples in this article by visiting the Superexpert Web site at

http://http://www.Superexpert.com/AspNetUnleashed/

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 easily 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:

  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 1.

Listing 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
    Return "Look before you leap"
   Case 1
    Return "Necessity is the mother of invention"
   Case 2
    Return "Life is full of risks"
  End Select
 End Function

End Class

End Namespace

The first line in Listing 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.Collections.Specialized, System.Configuration, System.Text, System.Text.RegularExpressions, System.Web, System.Web.Caching, System.Web.Security, System.Web.SessionState, 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 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.

NOTE

If you don't create a namespace for a class, the class is added to something called the global namespace. In general, it's not a good idea to add classes to the global namespace since it increases the likelihood of naming conflicts.

The remainder of Listing 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 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 1):

vbc /t:library quote.vb

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

Figure 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, you need to reference the proper assembly when you compile the component. If you lookup a particular class in the .NET Framework SDK Documentation, it will list the assembly associated with the class.

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 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 2—ShowQuote.aspx

<%@ Import Namespace="myComponents" %>

<Script Runat="Server">

Sub Page_Load
 Dim myQuote As New Quote

 lblOutput.Text = myQuote.ShowQuote()
End Sub

</Script>

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

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

</body>
</html>

The first line in Listing 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 2).

Figure 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 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 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 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 4 illustrates how you can use the adder component to add the values entered into two TextBox controls.

Listing 4—AddValues.aspx

<%@ Import Namespace="myComponents" %>

<Script Runat="Server">

 Sub Button_Click( s As Object, e As EventArgs )
  Dim myAdder As New Adder

  myAdder.FirstValue = txtVal1.Text
  myAdder.SecondValue = txtVal2.Text
  lblOutput.Text = myAdder.AddValues()
 End Sub

</Script>

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

<form Runat="Server">

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

<p>

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

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

<p>
Output:
<asp:Label
 ID="lblOutput"
 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 5, for example, uses property accessor syntax.

Listing 5—AdderProperties.vb

Imports System

Namespace myComponents

Public Class AdderProperties

 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 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 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—Register.vb

Imports System
Imports System.IO

Namespace myComponents

Public Class Register

 Shared Sub doRegister( FirstName As String, LastName As String, FavColor As String )
  Dim strPath As String = "c:\userlist.txt"
  Dim strmFile As StreamWriter

  strmFile = File.AppendText( strPath )
  strmFile.Write( "first name: " & firstname & Environment.NewLine )
  strmFile.Write( "last name: " & lastname & Environment.NewLine )
  strmFile.Write( "favorite Color: " & favColor & Environment.NewLine )
  strmFile.Write( "=============" & Environment.NewLine )
  strmFile.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 7 demonstrates how you can use the register component.

Listing 7—UserRegistration.aspx

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

Sub Button_Click( s As Object, e As EventArgs )
 Register.doRegister( txtFirstName.Text, txtLastName.Text, txtFavColor.Text )
End Sub

</Script>

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

<form Runat="Server">

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

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

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

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

</form>
</body>
</html>

When someone completes the form and clicks the button, the Button_Click subroutine is executed. This subroutine calls the doRegister() method to save the form data to a file.

NOTE

In Listing 7, you do not need to create an instance of the Register component before calling its doRegister() method. You don't need to create an instance of the component since the doRegister() method is declared as a shared method.

Typically, when you declare a method, you declare instance methods. Instance methods operate on a particular instance of a class. A shared method, however, operates on the class itself.

Notice that you must still place some of the application logic in the UserRegistration.aspx page. In the Button_Click 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 article, in the discussion of code-behind, you learn how to move all your application logic into a separate compiled file.

  • + Share This
  • 🔖 Save To Your Account