Home > Articles > Programming > Windows Programming

Separating Code from Presentation

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020