Chapter 14. Building Components

<feature><title>In this Chapter</title> <objective>

Building Basic Components

</objective>
<objective>

Building Component Libraries

</objective>
<objective>

Architectural Considerations

</objective>
<objective>

Summary

</objective>
</feature>

Components enable you to reuse application logic across multiple pages or even across multiple applications. For example, you can write a method named GetProducts() once and use the method in all the pages in your website. By taking advantage of components, you can make your applications easier to maintain and extend.

For simple applications, there is no reason to take advantage of components. However, as soon as your application contains more than a few pages, you’ll discover that you are repeating the same work over and over again. Whenever you discover that you need to write the same method more than once, you should immediately rip the method out of your page and add the method to a component.

Classic ASP Note

In classic ASP, programmers often used massive and difficult to maintain #INCLUDE files to create libraries of reusable subroutines and functions. In ASP.NET, you use components to build these libraries.

In this chapter, you learn how to build components in the .NET framework. First, you are provided with an overview of writing components: You learn how to create simple components and use them in the pages in your application. In particular, you learn how to define component methods, properties, and constructors. You also learn how to take advantage of overloading, inheritance, and interfaces.

Next, you learn how to build component libraries that can be shared across multiple applications. Different methods of compiling a set of components into assemblies are examined. You also learn how you can add a component library to the Global Assembly Cache.

Finally, architectural issues involved in using components are discussed. The final section of this chapter shows you how to build a simple three-tiered application that is divided into distinct User Interface, Business Logic, and Data Access layers.

Note

Let’s clarify the terminology. In this book, I use the word component as a synonym for the word class. Furthermore, by the word object, I mean an instance of a class.

I am ignoring a special meaning for the word component in the .NET Framework. Technically, a component is a class that implements the System.ComponentModel.IComponent interface. I am ignoring this special meaning of the word component in favor of the common language use of the word.

Building Basic Components

Let’s start by building a super simple component. The HelloWorld component is contained in Listing 14.1.

Example 14.1. HelloWorld.vb

Public Class HelloWorld

    Public Function SayMessage() As String
        Return "Hello World!"
    End Function

End Class

Visual Web Developer Note

When using Visual Web Developer, you create a component by selecting the menu option Website, Add New Item, and then selecting the Class item (see Figure 14.1). The first time you add a component to a project, Visual Web Developer prompts you to create a new folder named App_Code. You want your new component to be added to this folder.

Creating a new component with Visual Web Developer.

Figure 14.1. Creating a new component with Visual Web Developer.

The HelloWorld component consists of a single method named SayMessage() which returns the string Hello World!.

Make sure that you save the HelloWorld.vb file to your application’s App_Code folder. If you don’t save the component to this folder, then you won’t be able to use the component in your pages.

Next, you need to create a page that uses the new component. This page is contained in Listing 14.2.

Example 14.2. ShowHelloWorld.aspx

<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<script runat="server">

    Sub Page_Load()
        Dim objHelloWorld As New HelloWorld()
        lblMessage.Text = objHelloWorld.SayMessage()
    End Sub

</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Show Hello World</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

    <asp:Label
        id="lblMessage"
        Runat="server" />

    </div>
    </form>

</body>
</html>

In the Page_Load() event handler, an instance of the HelloWorld component is created. Next, the result returned by a call to the SayMessage() method is assigned to a Label control. When you open the page in your browser, you’ll see the message Hello World!.

Notice how simple this process of creating the component is. You don’t need to perform any special registration and you don’t need to compile anything explicitly. Everything just works magically.

Components and Dynamic Compilation

You are not required to explicitly compile (build) the component because the ASP.NET Framework automatically compiles the component for you. Any component that you add to the App_Code folder is compiled dynamically in the same way as an ASP.NET page. If you add a new component to the App_Code folder and request any page from your website, the contents of the App_Code folder are compiled into a new assembly and saved to the Temporary ASP.NET Files folder, located at the following path:

C:WINDOWSMicrosoft.NETFramework[version]
Temporary ASP.NET Files[application name]

Whenever you modify the component, the existing assembly in the Temporary ASP.NET Files folder is deleted. The App_Code folder is compiled again when you make a new page request.

Note

An assembly is the dll file (or dll files) in which components are stored.

You can add as many subfolders to the App_Code folder as you need to organize your components. The ASP.NET Framework finds your component no matter how deeply you nest the component in a subfolder.

One significant drawback of this process of dynamic compilation is that any errors in any component contained in the App_Code folder prevent any pages from executing. Even if a page does not use a particular component, any syntax errors in the component raise an exception when you request the page.

Tip

If a component contains an error, and you want to temporarily hide the component from the ASP.NET Framework, change the file extension to an extension that the ASP.NET Framework does not recognize, such as HelloWorld.vb.exclude. Visual Web Developer uses this method to hide a component when you right-click a component and select the menu option Exclude From Project.

Mixing Different Language Components in the App_Code Folder

You don’t have to do anything special, just as long as all the components in the App_Code folder are written in the same language. For example, if you use Visual Basic .NET to create all your components, then the ASP.NET Framework automatically infers the language of your components and everything just works.

However, if you mix components written in more than one language in the App_Code folder—for example, Visual Basic .NET, and C#—then you must perform some extra steps.

First, you need to place components written in different languages in different subfolders. You can name the subfolders anything you want. The point is to not mix different language components in the same folder.

Furthermore, you need to modify your web configuration file to recognize the different subfolders. For example, if you create two subfolders in the App_Code folder named VBCode and CSCode, then you can use the web configuration file in Listing 14.3 to use components written in both VB.NET and C#.

Example 14.3. Web.Config

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation>
    <codeSubDirectories>
      <add directoryName="VBCode" />
      <add directoryName="CSCode" />
    </codeSubDirectories>
    </compilation>
  </system.web>
</configuration>

When the contents of the App_Code folder are compiled, two assemblies are created: one that corresponds to the VBCode folder and one that corresponds to the CSCode folder. Notice that you don’t need to indicate the language used for each folder—the ASP.NET Framework infers the language for you.

There is nothing wrong with mixing components written in different languages in the same ASP.NET page. After a component is compiled, the .NET Framework treats VB.NET and C# components in the same way.

Declaring Methods

The simple HelloWorld component in Listing 14.1 contains a single method named SayMessage(), which returns a string value. When writing components with Visual Basic .NET, you create methods by creating either a subroutine or a function. Use a subroutine when a method does not return a value, and use a function when a method does return a value.

The SayMessage() method in Listing 14.1 is an instance method. In other words, you must create a new instance of the HelloWorld class before you can call the SayMessage(), method like this:

Dim objHelloWorld As New HelloWorld()
lblMessage.Text = objHelloWorld.SayMessage()

In the first line, a new instance of the HelloWorld component is created. The SayMessage() method is called from this instance. For this reason, the SayMessage() method is an instance method.

As an alternative to creating an instance method, you can create a shared method. The advantage of a shared method is that you do not need to create an instance of a component before calling it. For example, the SayMessage() method in the modified HelloWorld component in Listing 14.4 is a shared method.

Note

Shared methods are called static methods in other languages such as C# and Java.

Example 14.4. SharedHelloWorld.vb

Public Class SharedHelloWorld

    Public Shared Function SayMessage() As String
        Return "Hello World!"
    End Function

End Class

The SharedHelloWorld component defined in Listing 14.3 is exactly the same as the HelloWorld component created in Listing 14.1 with one change: The SayMessage() method includes a Shared modifier.

The page in Listing 14.5 uses the SharedHelloWorld component to display the Hello World! message.

Example 14.5. ShowSharedHelloWorld.aspx

<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<script runat="server">

    Sub Page_Load()
        lblMessage.Text = SharedHelloWorld.SayMessage()
    End Sub

</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Show Shared Hello World</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

    <asp:Label
        id="lblMessage"
        Runat="server" />

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

Notice that the page in Listing 14.5 does not create an instance of the SharedHelloWorld component. The SayMessage() method is called directly from the SharedHelloWorld class.

The advantage of using shared methods is that they save you typing. You don’t have to go through the pain of instantiating a component before calling the method. Many classes in the .NET Framework include shared methods. For example, the String.Format() method, the Int32.Parse() method, and the DateTime.DaysInMonth() method are all shared methods.

There is nothing wrong with mixing both shared and instance methods in the same component. For example, you might want to create a Product component that has a shared GetProducts() method and an instance SaveProduct() method.

The one significant limitation of using a shared method is that a shared method cannot refer to an instance field or property. In other words, shared methods should be stateless.

Declaring Fields and Properties

You can define a property for a component in two ways: the lazy way and the virtuous way.

The lazy way to create a property is to create a public field. If you declare any field with the Public access modifier, then the field can be accessed from outside the component.

For example, the component in Listing 14.6 contains a public field named Message.

Example 14.6. FieldHelloWorld.vb

Public Class FieldHelloWorld

    Public Message As String

    Public Function SayMessage() As String
        Return Message
    End Function

End Class

The Message field is declared near the top of the FieldHelloWorld class definition. Notice that the Message field is returned by the SayMessage() method.

The page in Listing 14.7 uses the FieldHelloWorld component to display a message.

Example 14.7. ShowFieldHelloWorld.aspx

<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
   "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<script runat="server">

    Sub Page_Load()
        Dim objFieldHelloWorld As New FieldHelloWorld()
        objFieldHelloWorld.Message = "Good Day!"
        lblMessage.Text = objFieldHelloWorld.SayMessage()
    End Sub

</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Show Field Hello World</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

    <asp:Label
        id="lblMessage"
        Runat="server" />

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

In the Page_Load() event handler in Listing 14.7, an instance of the FieldHelloWorld class is created, a value is assigned to the Message field, and the SayMessage() method is called.

There are a couple of serious disadvantages to creating properties by creating public fields. First, the .NET Framework recognizes properties as separate entities. Several methods in the .NET Framework recognize properties but not fields.

For example, you can refer to component properties and not fields when using the Eval() method in a databinding expression. If you want to bind a collection of Product objects to a GridView control, then you should expose the properties of the Product component as true properties and not as fields.

The other disadvantage of fields is that they do not provide you with a chance to validate the value being assigned to the field. For example, imagine that a property represents a database column and the column accepts no more than five characters. In that case, you should check whether the value being assigned to the property is less than five characters.

The component in Listing 14.8 uses a property instead of a field. (It does things the virtuous way.)

Example 14.8. PropertyHelloWorld.vb

Imports System

Public Class PropertyHelloWorld

    Private _message As String

    Public Property Message() As String
        Get
            Return _message
        End Get
        Set(ByVal Value As String)
            If Value.Length > 5 Then
                Throw New Exception("Message too long!")
            End If
            _message = Value
        End Set
    End Property

    Public Function SayMessage() As String
        Return _message
    End Function

End Class

Notice that the component in Listing 14.8 contains a property named Message and a private backing field named _message. The Message property contains both a Get() and a Set() function. The Get() function is called when you read the value of the Message property, and the Set() function is called when you assign a value to the Message property.

The Get() function simply returns the value of the private _message field. The Set() function assigns a value to the private _message field. The Set() function throws an exception if the length of the value being assigned to the _message field exceeds five characters.

Note

In Listing 14.8, the private field is named _message. The underscore character (_) has no programmatic significance. By convention, private members of a class are named with a leading underscore, but there is nothing wrong with following some other convention.

The page in Listing 14.9 uses the PropertyHelloWorld component.

Example 14.9. ShowPropertyHelloWorld.aspx

<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
  "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<script runat="server">
    Sub Page_Load()
        Dim objPropertyHelloWorld As New PropertyHelloWorld()
        objPropertyHelloWorld.Message = "Hello World!"
        lblMessage.Text = objPropertyHelloWorld.SayMessage()
    End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Show Property Hello World</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

    <asp:Label
        id="lblMessage"
        Runat="server" />

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

If you open the page in Listing 14.9 in your web browser, you will get a big, fat error message (see Figure 14.2). Because a string longer than 5 characters is assigned to the Message property in the Page_Load() method, the Message property raises an exception.

Assigning more than five characters.

Figure 14.2. Assigning more than five characters.

You can also create read-only properties when the situation warrants it. For example, the component in Listing 14.10 returns the current server time. It would not make sense to assign a value to this property, so the property is declared as read-only.

Example 14.10. ServerTime.vb

Public Class ServerTime

    Public ReadOnly Property CurrentTime() As String
        Get
            Return DateTime.Now.ToString()
        End Get
    End Property

End Class

Note

You can create shared fields and properties in the same way as you create shared methods, by using the Shared keyword. Any value you assign to a shared field or property is shared among all instances of a component.

I recommend that you avoid using shared fields and properties when building ASP.NET applications. Using shared fields and properties raises nasty concurrency issues in a multi-threaded environment such as ASP.NET. If you insist on creating a shared property, make the property read-only.

Declaring Constructors

A constructor is a special class method that is called automatically when you create a new instance of a class. Typically, you use the constructor to initialize private fields contained in the class.

When creating a constructor in Visual Basic .NET, you create a public subroutine named New(). For example, the class in Listing 14.11 displays a random quotation (see Figure 14.3). The collection of random quotations is created in the component’s constructor.

Example 14.11. Quote.vb

Imports System.Collections.Generic

Public Class Quote

    Private _quotes As New List(Of String)

    Public Function GetQuote() As String
        Dim rnd As New Random()
        Return _quotes(rnd.Next(_quotes.Count))
    End Function

    Public Sub New()
        _quotes.Add("All paid jobs absorb and degrade the mind -- Aristotle")
        _quotes.Add("No evil can happen to a good man, either in life or after death -- Plato")
        _quotes.Add("The only good is knowledge and the only evil is ignorance -- Plato")
    End Sub

End Class

Displaying a random quotation.

Figure 14.3. Displaying a random quotation.

Notice that the collection named _quotes is declared in the body of the class. That way, you can refer to the _quotes field in both the constructor and the GetQuote() method.

Note

You can create shared constructors by using the Shared keyword when declaring a constructor. A shared constructor is called once before any instance constructors.

Overloading Methods and Constructors

When a method is overloaded, a component contains two methods with exactly the same name. Many methods in the .NET Framework are overloaded, including the String.Replace() method, the Random.Next() method, and the Page.FindControl() method.

For example, here is a list of the three overloaded versions of the Random.Next() method:

  • Next()Returns a random number between 0 and 2,147,483,647.

  • Next(upperbound)Returns a number between 0 and the upper bound.

  • Next(lowerbound, upperbound)Returns a number between the lower bound and the upper bound.

Because all three methods do the same thing—they all return a random number—it makes sense to overload the Next() method. The methods differ only in their signatures. A method signature consists of the order and type of parameters that a method accepts. For example, you can’t overload two methods that have exactly the same set of parameters (even if the names of the parameters differ).

Overloading is useful when you want to associate related methods. Overloading is also useful when you want to provide default values for parameters. For example, the StoreProduct component in Listing 14.12 contains three overloaded versions of its SaveProduct() method.

Example 14.12. StoreProduct.vb

Public Class StoreProduct

    Public Sub SaveProduct(ByVal name As String)
        SaveProduct(name, 0, String.Empty)
    End Sub

    Public Sub SaveProduct(ByVal name As String, ByVal price As Decimal)
        SaveProduct(name, price, String.Empty)
    End Sub

    Public Sub SaveProduct(ByVal name As String, ByVal price As Decimal, ByVal description As String)
        ' Save name, price, description to database
    End Sub

End Class

You can call any of the three SaveProduct() methods in Listing 14.12 to save a new product. You can supply the new product with a name, a name and a price, or a name and a price and a description.

Visual Web Developer Note

When typing an overloaded method in Source view, the Intellisense pops up with all the different sets of parameters that you can use with the overloaded method. See Figure 14.4.

Typing an overloaded method in Visual Web Developer.

Figure 14.4. Typing an overloaded method in Visual Web Developer.

Because a constructor is just a special method, you also can use overloading when declaring constructors for a class. For example, the ProductConstructor class in Listing 14.13 contains three overloaded constructors that can be used to initialize the Product class.

Example 14.13. ProductConstructor.vb

Public Class ProductConstructor

    Public Sub New(ByVal name As String)
        Me.New(name, 0, String.Empty)
    End Sub

    Public Sub New(ByVal name As String, ByVal price As Decimal)
        Me.New(name, price, String.Empty)
    End Sub

    Public Sub New(ByVal name As String, ByVal price As Decimal, ByVal description As String)
        ' Use name, price, and description
    End Sub

End Class

When you instantiate the component in Listing 14.13, you can instantiate it in any of the following ways:

Dim objProduct As New ProductConstructor("Milk")

Dim objProduct As New ProductConstructor("Milk", 2.99D)

Dim objProduct As New ProductConstructor("Milk", 2.99D, "Whole Milk")

Declaring Namespaces

A namespace enables you to group logically related classes. You are not required to provide a class with a namespace. To this point, all the components that we have created have been members of the global namespace. However, several advantages result from grouping components into namespaces.

First, namespaces prevent naming collisions. If two companies produce a component with the same name, then namespaces provide you with a method of distinguishing the components.

Second, namespaces make it easier to understand the purpose of a class. If you group all your data access components into a DataAccess namespace and all your business logic components in a BusinessLogic namespace, then you can immediately understand the function of a particular class.

In an ASP.NET page, you import a namespace like this:

<%@ Import Namespace="System.Collections" %>

In a Visual Basic component, on the hand, you import a namespace like this:

Imports System.Collections

You can create your own custom namespaces and group your components into namespaces by using the Namespace statement. For example, the component in Listing 14.13 is contained in the AspUnleashed.SampleCode namespace.

Example 14.14. Namespaced.vb

Namespace AspNetUnleashed.SampleCode

    Public Class Namespaced

        Public Function SaySomething() As String
            Return "Something"
        End Function

    End Class

End Namespace

The file in Listing 14.14 uses the Namespace statement to group the Namespaced component into the AspUnleashed.SampleCode namespace. Components in different files can share the same namespace, and different components in the same file can occupy different namespaces.

The periods in a namespace name have no special significance. The periods are used to break up the words in the namespace, but you could use another character, such as an underscore character, instead.

Microsoft recommends a certain naming convention when creating namespaces:

CompanyName.TechnologyName[.Feature][.Design]

So, if your company is named Acme Consulting and you are building a data access component, you might add your component to the following namespace:

AcmeConsulting.DataAccess

Of course this is simply a naming convention. No serious harm will come to you if you ignore it.

Creating Partial Classes

You can define a single component that spans multiple files by taking advantage of a new feature of the .NET 2.0 Framework called partial classes.

For example, the files in Listings 14.15 and 14.16 contain two halves of the same component.

Example 14.15. FirstHalf.vb

Partial Public Class Tweedle

    Private _message As String = "THEY were standing under a tree," _
        & "each with an arm round the other's neck, and Alice knew" _
        & "which was which in a moment, because one of them had" _
        & """DUM"" embroidered on his collar, and the other ""DEE""."

End Class

Example 14.16. SecondHalf.vb

Partial Public Class Tweedle

    Public Function GetMessage() As String
        Return _message
    End Function

End Class

Notice that the private _message field is defined in the first file, but this private field is used in the GetMessage() method in the second file. When the GetMessage() method is called, it returns the value of the private field from the other class.

Both files define a class with the same name. The class declaration includes the keyword Partial. The Partial keyword marks the classes as partial classes.

Note

Partial classes are the basis for code-behind pages in the ASP.NET Framework. The code-behind file and the presentation page are two partial classes that get compiled into the same class.

Inheritance and MustInherit Classes

When one class inherits from a second class, the inherited class automatically includes all the non-private methods and properties of its parent class. In other words, what’s true of the parent is true of the child, but not the other way around.

Inheritance is used throughout the .NET Framework. For example, every ASP.NET page inherits from the base System.Web.UI.Page class. The only reason that you can use properties such as the IsPostback property in an ASP.NET page is that the page derives from the base Page class.

All classes in the .NET Framework derive from the base System.Object class. The Object class is the great-grandmother of every other class. This means that any methods or properties of the Object class, such as the ToString() method, are shared by all classes in the Framework.

You can take advantage of inheritance when building your own components. You indicate that one class inherits from a second class by using the Inherits keyword.

For example, the file in Listing 14.17 includes three components: a BaseProduct class, a ComputerProduct class, and a TelevisionProduct class.

Example 14.17. Inheritance.vb

Public Class BaseProduct

    Private _price As Decimal

    Public Property Price() As Decimal
        Get
            Return _price
        End Get
        Set(ByVal Value As Decimal)
            _price = Value
        End Set
    End Property

End Class

Public Class ComputerProduct
    Inherits BaseProduct

    Private _processor As String

    Public Property Processor() As String
        Get
            Return _processor
        End Get
        Set(ByVal Value As String)
            _processor = value
        End Set
    End Property

End Class

Public Class TelevisionProduct
    Inherits BaseProduct

    Private _isHDTV As Boolean

    Public Property IsHDTV() As Boolean
        Get
            Return _isHDTV
        End Get
        Set(ByVal Value As Boolean)
            _isHDTV = value
        End Set
    End Property

End Class

Notice that both the ComputerProduct and TelevisionProduct components inherit from the BaseProduct component. Because the BaseProduct class includes a Price property, both inherited components automatically inherit this property.

When inheriting one class from another, you also can override methods and properties of the base class. Overriding a method or property is useful when you want to modify the behavior of an existing class.

To override a property or method of a base class, the property or method must be marked with the Visual Basic .NET Overridable or MustOverride keyword. Only methods or properties marked with the Overridable or MustOverride keyword can be overridden.

For example, the file in Listing 14.18 contains two components: a ProductBase class and a OnSaleProduct class. The second class inherits from the first class and overrides its Price property. The Price property of the OnSaleProduct component divides the price by half.

Example 14.18. OnSaleProduct.vb

Public Class ProductBase

    Private _price As Decimal

    Public Overridable Property Price() As Decimal
        Get
            Return _price
        End Get
        Set(ByVal Value As Decimal)
            _price = value
        End Set
    End Property

End Class


Public Class OnSaleProduct
    Inherits ProductBase

    Public Overrides Property Price() As Decimal
        Get
            Return MyBase.Price / 2
        End Get
        Set(ByVal Value As Decimal)
            MyBase.Price = value
        End Set
    End Property

End Class

Notice that the MyBase keyword is used in Listing 14.18 to refer to the base class (the ProductBase class).

Finally, you can use the MustInherit keyword when declaring a class to mark the class as an abstract class. You cannot instantiate a MustInherit class. To use a MustInherit class, you must derive a new class from the MustInherit class and instantiate the derived class.

MustInherit classes are the foundation for the ASP.NET 2.0 Provider Model. Personalization, Membership, Roles, Session State, and Site Maps all use the Provider Model.

For example, the MembershipProvider class is the base class for all Membership Providers. The SqlMembershipProvider and ActiveDirectoryMembershipProvider classes both derive from the base MembershipProvider class.

Note

Chapter 21, “Using ASP.NET Membership,” discusses the MembershipProvider classes in detail. The MembershipProvider is responsible for saving and loading membership information such as application usernames and passwords.

The base MembershipProvider class is a MustInherit class. You cannot use this class directly in your code. Instead, you must use one of its derived classes. However, the base MembershipProvider class provides a common set of methods and properties that all MembershipProvider-derived classes inherit.

The base MembershipProvider class includes a number of methods and properties marked as MustOverride. A derived MembershipProvider class is required to override these properties and methods.

The file in Listing 14.18 contains two components. The first component, the BaseEmployee component, is a MustInherit class that contains a MustOverride property named Salary. The second component, the SalesEmployee, inherits the BaseEmployee component and overrides the Salary property.

Example 14.18. Employees.vb

Public MustInherit Class BaseEmployee

    Public MustOverride ReadOnly Property Salary() As Decimal

    Public ReadOnly Property Company() As String
        Get
            Return "Acme Software"
        End Get
    End Property

End Class

Public Class SalesEmployee
    Inherits BaseEmployee

    Public Overrides ReadOnly Property Salary() As Decimal
        Get
            Return 67000.23D
        End Get
    End Property

End Class

Declaring Interfaces

An interface is a list of properties and methods that a class must implement. If a class implements an interface, then you know that the class includes all the properties and methods contained in the interface.

For example, the file in Listing 14.19 contains an interface named IProduct and two components named MusicProduct and BookProduct.

Example 14.19. Products.vb

Public Interface IProduct

    ReadOnly Property Price() As Decimal

    Sub SaveProduct()

End Interface


Public Class MusicProduct
    Implements IProduct

    Public ReadOnly Property Price() As Decimal Implements IProduct.Price
        Get
            Return 12.99D
        End Get
    End Property

    Public Sub SaveProduct() Implements IProduct.SaveProduct
        ' Save Music Product
    End Sub

End Class


Public Class BookProduct
    Implements IProduct

    Public ReadOnly Property Price() As Decimal Implements IProduct.Price
        Get
            Return 23.99D
        End Get
    End Property

    Public Sub SaveProduct() Implements IProduct.SaveProduct
        ' Save Book Product
    End Sub

End Class

The declaration of both components in Listing 14.17 includes the Implements keyword. Both components implement the IProduct interface. Notice, furthermore, that both the SaveProduct() method and the Price property include an Implements clause. The Implements clause associates a method or property in the derived class with a method or property contained in the interface.

Interfaces are similar to MustInherit classes with two important differences. First, a component can inherit from only one class. On the other hand, a component can implement many different interfaces.

Second, a MustInherit class can contain application logic. You can add methods to a MustInherit class that all derived classes inherit and can use. An interface, on the other hand, cannot contain any logic. An interface is nothing more than a list of methods and properties.

Using Access Modifiers

Visual Basic .NET supports the following access modifiers (also called access levels), which you can use when declaring a class, method, or property:

  • Public—A Public class, method, or property has no access restrictions.

  • Protected—A Protected method or property can be accessed only within the class itself or a derived class.

  • Friend—A Friend class, method, or property can be accessed only by a component within the same assembly (dll file). Because ASP.NET pages are compiled into different assemblies than the contents of the App_Code folder, you cannot access a Friend member of a class outside of the App_Code folder.

  • Protected Friend—A Protected Friend method or property can be accessed within the class itself or a derived class, or any other class located in the same assembly.

  • Private—A Private class, method, or property can be accessed only within the class itself.

Using access modifiers is useful when you are developing a component library that might be used by other members of your development team (or your future self). For example, you should mark all methods that you don’t want to expose from your component as private.

Intellisense and Components

Visual Web Developer automatically pops up with Intellisense when you type the names of classes, properties, or methods in Source view. You can add Intellisense to your custom components to make it easier for other developers to use your components.

If you add XML comments to a component, then the contents of the XML comments appear automatically in Intellisense. For example, the component in Listing 14.20 includes XML comments for its class definition, property definitions, and method definition (see Figure 14.5).

Adding comments to a component.

Figure 14.5. Adding comments to a component.

Example 14.20. Employee.vb

''' <summary>
''' Represents an employee of Acme.com
''' </summary>
Public Class Employee

    Private _firstName As String
    Private _lastName As String

    ''' <summary>
    ''' The employee first name
    ''' </summary>
    Public ReadOnly Property FirstName() As String
        Get
            Return _firstName
        End Get
    End Property

    ''' <summary>
    ''' The employee last name
    ''' </summary>
    Public ReadOnly Property LastName() As String
        Get
            Return _lastName
        End Get
    End Property


    ''' <summary>
    ''' Returns an employee from the database
    ''' </summary>
    ''' <param name="id">The unique employee identifier</param>
    ''' <returns>An instance of the Employee class</returns>
    Public Shared Function getEmployee(ByVal id As Integer) As Employee
        Return Nothing
    End Function

    ''' <summary>
    ''' Initializes an employee
    ''' </summary>
    ''' <param name="firstName">First Name</param>
    ''' <param name="lastName">Last Name</param>
    Public Sub New(ByVal firstName As String, ByVal lastName As String)
        _firstName = firstName
        _lastName = lastName
    End Sub

End Class

Note

You can generate an XML documentation file—a file that contains all the XML comments—for the components contained in a folder by using the /doc switch with the Visual Basic command-line compiler. The Visual Basic command-line compiler is discussed in the second part of this chapter, “Building Component Libraries.”

Using ASP.NET Intrinsics in a Component

When you add code to an ASP.NET page, you are adding code to an instance of the Page class. The Page class exposes several ASP.NET intrinsic objects such as the Request, Response, Cache, Session, and Trace objects.

If you want to use these objects within a component, then you need to do a little more work. Realize that when you create a component, you are not creating an ASP.NET component. In this chapter, we are creating .NET components, and a .NET component can be used by any type of .NET application, including a Console application or Windows Forms application.

To use the ASP.NET instrinsics in a component, you need to get a reference to the current HtppContext. The HttpContext object is the one object that is available behind the scenes through the entire page processing lifecycle. You can access the HttpContext object from any user control, custom control, or component contained in a page.

Note

The HttpContext object includes an Items collection. You can add anything to the Items collection and share the thing among all the elements contained in a page.

To get a reference to the current HttpContext object, you can use the shared Current property included in the HttpContext class. For example, the component in Listing 14.21 uses the HttpContext object to use both the Session and Trace objects.

Example 14.21. Preferences.vb

Imports System.Web

Public Class Preferences

    Public Shared Property FavoriteColor() As String
        Get
            Dim context As HttpContext = HttpContext.Current
            context.Trace.Warn("Getting FavoriteColor")
            If context.Session("FavoriteColor") Is Nothing Then
                Return "Blue"
            Else
                Return CType(context.Session("FavoriteColor"), String)
            End If
        End Get
        Set(ByVal Value As String)
            Dim context As HttpContext = HttpContext.Current
            context.Trace.Warn("Setting FavoriteColor")
            context.Session("FavoriteColor") = value
        End Set
    End Property

End Class

The Preferences component contains a single property named FavoriteColor. The value of this property is stored in Session state. Anytime this property is modified, the Trace object writes a warning.

You can use the Preferences component in the page contained in Listing 14.22.

Example 14.22. ShowPreferences.aspx

<%@ Page Language="VB" trace="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
  "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<script runat="server">

    Sub Page_PreRender()
        body1.Style("background-color") = Preferences.FavoriteColor
    End Sub

    Protected Sub btnSelect_Click(ByVal sender As Object, ByVal e As EventArgs)
        Preferences.FavoriteColor = ddlFavoriteColor.SelectedItem.Text
    End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <style type="text/css">
        .content
        {
            width:80%;
            padding:20px;
            background-color:white;
        }
    </style>
    <title>Show Preferences</title>
</head>
<body id="body1" runat="server">
    <form id="form1" runat="server">
    <div class="content">

    <h1>Show Preferences</h1>

    <asp:DropDownList
        id="ddlFavoriteColor"
        Runat="server">
        <asp:ListItem Text="Blue" />
        <asp:ListItem Text="Red" />
        <asp:ListItem Text="Green" />
    </asp:DropDownList>
    <asp:Button
        id="btnSelect"
        Text="Select"
        Runat="server" OnClick="btnSelect_Click" />

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

After you open the page in Listing 14.22, you can select your favorite color from the DropDownList control. Your favorite color is stored in the Preferences object (see Figure 14.6).

Selecting a favorite color.

Figure 14.6. Selecting a favorite color.

Building Component Libraries

One of the advertised benefits of using components is code reuse. You write a method once, and then you never need to write the same method ever again.

One problem with the components that have been created to this point is that they have all been application specific. In other words, you cannot reuse the components across multiple websites without copying all the source code from one App_Code folder to another.

If you want to share components among multiple websites, then you can no longer take advantage of dynamic compilation. To share components, you need to compile the components explicitly in a separate assembly.

Compiling Component Libraries

You can use a number of methods to compile a set of components into an assembly:

  • Use the command-line compiler

  • Use Visual Basic Express

  • Use Visual Studio .NET 2005

These options are explored in turn.

Using the Visual Basic .NET Command-Line Compiler

You can use the Visual Basic command-line compiler to compile a source code file, or set of source code files, into an assembly. The Visual Basic command-line compiler is located at the following path:

C:WINDOWSMicrosoft.NETFramework[version]vbc.exe

Note

If you have installed the .NET Framework 2.0 SDK, then you can open the SDK Command Prompt from the Microsoft .NET Framework SDK v2.0 program group. When the command prompt opens, the path to the Visual Basic .NET compiler is added to the environment automatically.

You can use the vbc.exe tool to compile any Visual Basic source file like this:

vbc /t:library SomeFile.vb

The /t (target) option causes the compiler to create a component library and not a Console or Windows application. When you execute this command, a new file named SomeFile.dll is created, which is the compiled assembly.

As an alternative to compiling a single file, you can compile all the source code files in a folder (and every subfolder) like this:

vbc /t:library /recurse:*.vb /out:MyLibrary.dll

The /recurse option causes the compiler to compile the contents of all the subfolders. The /out option provides a name for the resulting assembly.

You need to know about two other compiler options:

  • /importsEnables you to provide a comma-delimited list of namespaces to import.

  • /referenceEnables you to provide a comma-delimited list of assemblies to reference.

When the source code files are compiled dynamically in the App_Code folder, several imports and references are used by default. For example, the System.Collections, System.Web, and System.Web.UI.WebControls namespaces are imported automatically. When compiling from the command line, you need to either add Imports statements to your source code files or list these namespaces, using the /imports compiler option.

Furthermore, several assembly references are added automatically during dynamic compilation, including System.Web.dll and System.Data.dll. When compiling from the command line, you need to add these references explicitly if you are using a class from one of these assemblies.

Note

You can determine the assembly and namespace associated with any class in the .NET Framework by looking up the main entry for the class in the .NET Framework SDK Documentation.

Visual Web Developer Tip

You can add the vbc command-line compiler as an external tool to Visual Web Developer. That way, you can simply select a menu option to compile the contents of the App_Code folder automatically into an assembly. To add a new external tool, select the menu option Tools, External Tools (see Figure 14.7).

Adding the Visual Basic Compiler to External Tools.

Figure 14.7. Adding the Visual Basic Compiler to External Tools.

Using Visual Basic .NET Express

You can download a trial edition of Visual Basic .NET Express from the MSDN website (http://msdn.microsoft.com). Visual Basic .NET Express enables you to build Windows applications, Console applications, and class libraries.

To create a class library that you can use with an ASP.NET application, you create a Class Library project in Visual Basic .NET Express (see Figure 14.8). When you build the project, a new assembly is created.

Creating a Class Library in Visual Basic .NET Express.

Figure 14.8. Creating a Class Library in Visual Basic .NET Express.

If you need to use ASP.NET classes in your class library, such as the HttpContext class, then you need to add a reference to the System.Web.dll assembly to your Class Library project. Select the menu option Project, Add Reference and add the System.Web.dll from beneath the .NET tab (see Figure 14.9).

Adding a reference to System.Web.dll.

Figure 14.9. Adding a reference to System.Web.dll.

Note

If you are a C# developer, then you can download Visual C# Express from the MSDN Website (http://msdn.microsoft.com).

Using Visual Studio .NET 2005

The easiest way to create a class library that you can share among multiple ASP.NET applications is to use Visual Studio .NET 2005 instead of Visual Web Developer. Visual Studio .NET 2005 was designed to enable you to easily build enterprise applications. Building class libraries is one of the features you get in Visual Studio .NET 2005 that you don’t get in Visual Web Developer Express.

Visual Studio .NET 2005 enables you to add multiple projects to a single solution. For example, you can add both an ASP.NET project and a Class Library project to the same solution. When you update the Class Library project, the ASP.NET project is updated automatically (see Figure 14.10).

A solution that contains multiple projects.

Figure 14.10. A solution that contains multiple projects.

Adding a Reference to a Class Library

Now that you understand how you can create a class library in a separate assembly, you need to know how you can use this class library in another project. In other words, how do you use the components contained in an assembly within an ASP.NET page?

There are two ways to make an assembly available to an ASP.NET application. You can add the assembly to the application’s /Bin folder or you can add the assembly to the Global Assembly Cache.

Adding an Assembly to the Bin Folder

In general, the best way to use an assembly in an ASP.NET application is to add the assembly to the application’s root Bin folder. There is nothing magical about this folder. The ASP.NET Framework automatically checks this folder for any assemblies. If the folder contains an assembly, the assembly is referenced automatically by the ASP.NET application when it is compiled dynamically.

If you are using Visual Web Developer, then you can select the menu option Website, Add Reference to add a new assembly to your application’s Bin folder (see Figure 14.11). Alternatively, you can simply copy an assembly into this folder. (If the folder doesn’t exist, just create it.)

Adding an assembly reference with Visual Web Developer.

Figure 14.11. Adding an assembly reference with Visual Web Developer.

When you add an assembly to an ASP.NET application’s Bin folder, the assembly is scoped to the application. This means that you can add different versions of the same assembly to different applications without worrying about any conflicts.

Furthermore, if you add an assembly to the Bin folder, then you can take advantage of XCopy deployment. In other words, if you need to move your website to a new server, then you can simply copy all the files in your website from one server to another. As long as you copy your Bin folder, the assembly is available at the new location.

Adding an Assembly to the Global Assembly Cache

All the assemblies that make up the .NET Framework class library are contained in the Global Assembly Cache. For example, the Random class is located in the System.dll assembly, and the System.dll assembly is contained in the Global Assembly Cache. Any assembly located in the Global Assembly Cache can be referenced by any application running on a server.

The Global Assembly Cache’s physical location is at the following path:

C:WINDOWSassembly

Before you can add an assembly to the Global Assembly Cache, you must add a strong name to the assembly. A strong name is similar to a GUID. You use a strong name to provide your assembly with a universally unique identifier.

Note

Technically, a strong name consists of the name, version number, and culture of the assembly. The strong name also includes the public key from a public/private key pair. Finally, the strong name includes a hash of the assembly’s contents so that you know whether the assembly has been modified.

You can generate a strong name by using the sn.exe command-line tool like this:

sn.exe -k KeyPair.snk

Executing this command creates a new file named KeyPair.snk, which includes a new random public/private key pair.

Warning

Protect your key file. You should not reveal the private key to anyone.

You can compile an assembly that includes a strong name by executing the Visual Basic .NET command-line compiler like this:

vbc /t:library /keyfile:KeyPair.snk /recurse:*.vb /out:MyLibrary.dll

The resulting assembly is strongly named with the public key from the KeyPair.snk file. The /keyfile option associates the key file with the assembly. In this case, the name of the resulting assembly is MyLibrary.dll.

An alternative method of associating a strong name with an assembly is to use the <Assembly: AssemblyKeyFile> attribute. You can add this attribute to any of the source files that get compiled into the assembly. For example, you can drop the file in Listing 14.23 into the folder that you are compiling and it associates the public key from the KeyPair.snk file with the compiled assembly.

Example 14.23. AssemblyInfo.vb

Imports System.Reflection

<Assembly: AssemblyKeyFile("KeyPair.snk")>
<Assembly: AssemblyVersion("0.0.0.0")>

The file in Listing 14.23 actually includes two attributes. The first attribute associates the KeyPair.snk public key with the assembly. The second attribute associates a version number with the assembly. The version number consists of four sets of numbers: the major version, minor version, build number, and the revision number.

After you add the file in Listing 14.23 to a folder that contains the source code for your components, use the following command to compile the folder:

vbc /t:library /recurse:*.vb /out:MyLibrary.dll

After you associate a strong name with an assembly, you can use the GacUtil.exe command-line tool to add the assembly to the Global Assembly Cache. Executing the following statement from a command prompt adds the MyLibrary.dll assembly to the Global Assembly Cache:

GacUtil.exe /i MyLibrary.dll

You can verify that the MyLibrary.dll assembly has been added successfully to the Global Assembly Cache by opening your Global Assembly Cache folder located at the following path:

C:WINDOWSassembly

You should see the MyLibrary.dll assembly listed in the Assembly Name column (see Figure 14.12). Note the Version and the PublicKeyToken columns. You need to know the values of these columns to use the assembly in an application.

Viewing the Global Assembly Cache.

Figure 14.12. Viewing the Global Assembly Cache.

After you install an assembly in the Global Assembly Cache, you can use the assembly in your ASP.NET Pages and App_Code components by adding a reference to the assembly in your web configuration file. The web configuration file in Listing 14.24 adds the MyLibrary.dll assembly to your application.

Example 14.24. Web.Config

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation>
      <assemblies>
        <add assembly="MyLibrary,Version=0.0.0.0,Culture=neutral,
          PublicKeyToken=250c66fc9dd31989"/>
      </assemblies>
    </compilation>
  </system.web>
</configuration>

The web configuration file in Listing 14.24 adds the MyLibrary assembly. Notice that you must supply the Version, Culture, and PublicKeyToken associated with the assembly. You need to substitute the correct values for these properties in Listing 14.24 before you use the file with an assembly that you have compiled. (Remember that you can get these values by opening the c:WINDOWSassembly folder.)

Note

When using Visual Basic Express or Visual Studio .NET 2005, you can create a strong name automatically and associate the strong name with an assembly. Right-click the name of your project in the Solution Explorer window and select Properties. Next, select the tab labeled Signing.

In general, you should avoid adding your assemblies to the Global Assembly Cache because using the Global Assembly Cache defeats XCopy deployment. Using the Global Assembly Cache makes it more difficult to back up an application. It also makes it more difficult to move an application from one server to another.

Architectural Considerations

If you embark on a large ASP.NET project, you’ll quickly discover that you spend more time writing code for components than writing code for your pages. This is not a bad thing. Placing as much of your application logic as possible in components makes it easier to maintain and extend your application.

However, the process of organizing the components itself can become time consuming. In other words, you start to run into architectural issues concerning the best way to design your web application.

The topic of architecture, like the topics of politics and religion, should not be discussed in polite company. People have passionate opinions about architecture and discussions on this topic quickly devolve into people throwing things. Be aware that any and all statements about proper architecture are controversial.

With these disclaimers out of the way, in this section I provide you with an overview of one of the most common architectures for ASP.NET applications. In this section, you learn how to build a three-tiered ASP.NET application.

Building Multi-tier Applications

One very common architecture for an application follows an n-tier design model. When using an n-tier architecture, you encapsulate your application logic into separate layers.

In particular, it is recommended that an application should be divided into the following three application layers:

  • User Interface Layer

  • Business Logic Layer

  • Data Access Layer

The idea is that the User Interface layer should contain nothing but user interface elements such as HTML and ASP.NET controls. The User Interface layer should not contain any business logic or data access code.

The Business Logic layer contains all your business rules and validation code. It manages all data access for the User Interface Layer.

Finally, the Data Access Layer contains all the code for interacting with a database. For example, all the code for interacting with Microsoft SQL Server should be encapsulated in this layer.

The advantage of encapsulating your application logic into different layers is that it makes it easier to modify your application without requiring you to rewrite your entire application. Changes in one layer can be completely isolated from the other layers.

For example, imagine that (one fine day) your company decides to switch from using Microsoft SQL Server to using Oracle as their database server. If you have been careful to create an isolated Data Access Layer, then you would need to rewrite only your Data Access Layer. It might be a major project, but you would not need to start from scratch.

Or, imagine that your company decides to create a Windows Forms version of an existing ASP.NET application. Again, if you have been careful to isolate your User Interface Layer from your Business Logic Layer, then you can extend your application to support a Windows Forms Interface without rewriting your entire application. The Windows Forms application can use your existing Business Logic and Data Access layers.

Note

I spend my working life training companies on implementing ASP.NET applications. Typically, a company is migrating a web application written in some other language such as Java or ASP Classic to the ASP.NET Framework. It always breaks my heart to see how much code is wasted in these transitions (thousands of man hours of work lost). If you are careful in the way that you design your ASP.NET application now, you can avoid this sorry fate in the future.

I realize that this is all very abstract, so let’s examine a particular sample. We’ll create a simple product management system that enables you to select, insert, update, and delete products. However, we’ll do it the right way by dividing the application into distinct User Interface, Business Logic, and Data Access layers.

Creating the User Interface Layer

The User Interface layer is contained in Listing 14.25. Notice that the User Interface layer consists of a single ASP.NET page. This page contains no code whatsoever.

Example 14.25. Products.aspx

<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
  "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <style type="text/css">
    html
    {
        background-color:silver;
    }
    .content
    {
        padding:10px;
        background-color:white;
    }
    .products
    {
        margin-bottom:20px;
    }
    .products td,.products th
    {
        padding:5px;
        border-bottom:solid 1px blue;
    }
    a
    {
        color:blue;
    }
    </style>
    <title>Products</title>
</head>
<body>
    <form id="form1" runat="server">
    <div class="content">

    <asp:GridView
        id="grdProducts"
        DataSourceID="srcProducts"
        DataKeyNames="Id"
        AutoGenerateEditButton="true"
        AutoGenerateDeleteButton="true"
        AutoGenerateColumns="false"
        CssClass="products"
        GridLines="none"
        Runat="server">
        <Columns>
        <asp:BoundField
            DataField="Id"
            ReadOnly="true"
            HeaderText="Id" />
        <asp:BoundField
            DataField="Name"
            HeaderText="Name" />
        <asp:BoundField
            DataField="Price"
            DataFormatString="{0:c}"
            HeaderText="Price" />
        <asp:BoundField
            DataField="Description"
            HeaderText="Description" />
        </Columns>
    </asp:GridView>


    <fieldset>
    <legend>Add Product</legend>
    <asp:DetailsView
        id="dtlProduct"
        DataSourceID="srcProducts"
        DefaultMode="Insert"
        AutoGenerateInsertButton="true"
        AutoGenerateRows="false"
        Runat="server">
        <Fields>
        <asp:BoundField
            DataField="Name"
            HeaderText="Name:" />
        <asp:BoundField
            DataField="Price"
            HeaderText="Price:"/>
        <asp:BoundField
            DataField="Description"
            HeaderText="Description:" />
        </Fields>
    </asp:DetailsView>
    </fieldset>


    <asp:ObjectDataSource
        id="srcProducts"
        TypeName="AcmeStore.BusinessLogicLayer.Product"
        SelectMethod="SelectAll"
        UpdateMethod="Update"
        InsertMethod="Insert"
        DeleteMethod="Delete"
        Runat="server" />

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

The page in Listing 14.25 contains a GridView, DetailsView, and ObjectDataSource control. The GridView control enables you to view, update, and delete the products contained in the Products database table (see Figure 14.13). The DetailsView enables you to add new products to the database. Both controls use the ObjectDataSource as their data source.

The Products.aspx page.

Figure 14.13. The Products.aspx page.

Note

The next chapter is entirely devoted to the ObjectDataSource control.

The page in Listing 14.25 does not interact with a database directly. Instead, the ObjectDataSource control is used to bind the GridView and DetailsView controls to a component named AcmeStore.BusinessLogicLayer.Product. The Product component is contained in the Business Logic layer.

Note

The page in Listing 14.25 does not contain any validation controls. I omitted adding validation controls for reasons of space. In a real application, you would want to toss some RequiredFieldValidator and CompareValidator controls into the page.

Creating the Business Logic Layer

The ASP.NET pages in your application should contain a minimum amount of code. All your application logic should be pushed into separate components contained in either the Business Logic or Data Access layers.

Your ASP.NET pages should not communicate directly with the Data Access layer. Instead, the pages should call the methods contained in the Business Logic layer.

The Business Logic layer consists of a single component named Product, which is contained in Listing 14.26. (A real-world application might contain dozens or even hundreds of components in its Business Logic layer.)

Example 14.26. BLL/Product.vb

Imports System
Imports System.Collections.Generic
Imports AcmeStore.DataAccessLayer

Namespace AcmeStore.BusinessLogicLayer

    ''' <summary>
    ''' Represents a store product and all the methods
    ''' for selecting, inserting, and updating a product
    ''' </summary>
    Public Class Product

        Private _id As Integer = 0
        Private _name As String = String.Empty
        Private _price As Decimal = 0
        Private _description As String = String.Empty

        ''' <summary>
        ''' Product Unique Identifier
        ''' </summary>
        Public ReadOnly Property Id() As Integer
            Get
                Return _id
            End Get
        End Property

        ''' <summary>
        ''' Product Name
        ''' </summary>
        Public ReadOnly Property Name() As String
            Get
                Return _name
            End Get
        End Property

        ''' <summary>
        ''' Product Price
        ''' </summary>
        Public ReadOnly Property Price() As Decimal
            Get
                Return _price
            End Get
        End Property

        ''' <summary>
        ''' Product Description
        ''' </summary>
        Public ReadOnly Property Description() As String
            Get
                Return _description
            End Get
        End Property

        ''' <summary>
        ''' Retrieves all products
        ''' </summary>
        Public Shared Function SelectAll() As List(Of Product)
            Dim dataAccessLayer As SqlDataAccessLayer = New SqlDataAccessLayer()
            Return dataAccessLayer.ProductSelectAll()
        End Function

        ''' <summary>
        ''' Updates a particular product
        ''' </summary>
        ''' <param name="id">Product Id</param>
        ''' <param name="name">Product Name</param>
        ''' <param name="price">Product Price</param>
        ''' <param name="description">Product Description</param>
        Public Shared Sub Update(ByVal id As Integer, ByVal name As String, ByVal price As Decimal, ByVal description As String)
            If id < 1 Then
                Throw New ArgumentException("Product Id must be greater than 0", "id")
            End If

            Dim productToUpdate As Product = New Product(id, name, price, description)
            productToUpdate.Save()
        End Sub

        ''' <summary>
        ''' Inserts a new product
        ''' </summary>
        ''' <param name="name">Product Name</param>
        ''' <param name="price">Product Price</param>
        ''' <param name="description">Product Description</param>
        Public Shared Sub Insert(ByVal name As String, ByVal price As Decimal, ByVal description As String)
            Dim NewProduct As Product = New Product(name, price, description)
            NewProduct.Save()
        End Sub


        ''' <summary>
        ''' Deletes an existing product
        ''' </summary>
        ''' <param name="id">Product Id</param>
        Public Shared Sub Delete(ByVal id As Integer)
            If id < 1 Then
                Throw New ArgumentException("Product Id must be greater than 0", "id")
            End If

            Dim dataAccessLayer As SqlDataAccessLayer = New SqlDataAccessLayer()
            dataAccessLayer.ProductDelete(id)
        End Sub

        ''' <summary>
        ''' Validates product information before saving product
        ''' properties to the database
        ''' </summary>
        Private Sub Save()
            If String.IsNullOrEmpty(_name) Then
                Throw New ArgumentException("Product Name not supplied", "name")
            End If
            If _name.Length > 50 Then
                Throw New ArgumentException("Product Name must be less than 50 characters", "name")
            End If
            If String.IsNullOrEmpty(_description) Then
                Throw New ArgumentException("Product Description not supplied", "description")
            End If

            Dim dataAccessLayer As SqlDataAccessLayer = New SqlDataAccessLayer()
            If _id > 0 Then
                dataAccessLayer.ProductUpdate(Me)
            Else
                dataAccessLayer.ProductInsert(Me)

            End If
        End Sub

        ''' <summary>
        ''' Initializes Product
        ''' </summary>
        ''' <param name="name">Product Name</param>
        ''' <param name="price">Product Price</param>
        ''' <param name="description">Product Description</param>
        Public Sub New(ByVal name As String, ByVal price As Decimal, ByVal description As String)
            Me.New(0, name, price, description)
        End Sub


        ''' <summary>
        ''' Initializes Product
        ''' </summary>
        ''' <param name="id">Product Id</param>
        ''' <param name="name">Product Name</param>
        ''' <param name="price">Product Price</param>
        ''' <param name="description">Product Description</param>
        Public Sub New(ByVal id As Integer, ByVal name As String, ByVal price As Decimal, ByVal description As String)
            _id = id
            _name = name
            _price = price
            _description = description
        End Sub

    End Class
End namespace

The Product component contains four public methods named SelectAll(), Update(), Insert(), and Delete(). All four of these methods use the SqlDataAccessLayer component to interact with the Products database table. The SqlDataAccessLayer is contained in the Data Access Layer.

For example, the SelectAll() method returns a collection of Product objects. This collection is retrieved from the SqlDataAccessLayer component.

The Insert(), Update(), and Delete() methods validate their parameters before passing the parameters to the Data Access layer. For example, when you call the Insert() method, the length of the Name parameter is checked to verify that it is less than 50 characters.

Notice that the Business Logic layer does not contain any data access logic. All this logic is contained in the Data Access layer.

Creating the Data Access Layer

The Data Access layer contains all the specialized code for interacting with a database. The Data Access layer consists of the single component in Listing 14.27. (A real-world application might contain dozens or even hundreds of components in its Data Access Layer.)

Example 14.27. SqlDataAccessLayer.vb

Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.Configuration
Imports System.Collections.Generic
Imports AcmeStore.BusinessLogicLayer

Namespace AcmeStore.DataAccessLayer

    ''' <summary>
    ''' Data Access Layer for interacting with Microsoft
    ''' SQL Server 2005
    ''' </summary>
    Public Class SqlDataAccessLayer
        Private Shared ReadOnly _connectionString As String = String.Empty

        ''' <summary>
        ''' Selects all products from the database
        ''' </summary>
        Public Function ProductSelectAll() As List(Of Product)
            ' Create Product collection
            Dim colProducts As New List(Of Product)()

            ' Create connection
            Dim con As SqlConnection = New SqlConnection(_connectionString)

            ' Create command
            Dim cmd As SqlCommand = New SqlCommand()
            cmd.Connection = con
            cmd.CommandText = "SELECT Id,Name,Price,Description FROM Products"

            ' Execute command
            Using con
                con.Open()
                Dim reader As SqlDataReader = cmd.ExecuteReader()
                While reader.Read()
                    colProducts.Add(New Product( _
                        CType(reader("Id"), Integer), _
                        CType(reader("Name"), String), _
                        CType(reader("Price"), Decimal),_
                        CType(reader("Description"), String)))
                End While
            End Using
            Return colProducts
        End Function

        ''' <summary>
        ''' Inserts a new product into the database
        ''' </summary>
        ''' <param name="newProduct">Product</param>
        Public Sub ProductInsert(ByVal NewProduct As Product)
            ' Create connection
            Dim con As SqlConnection = New SqlConnection(_connectionString)

            ' Create command
            Dim cmd As SqlCommand = New SqlCommand()
            cmd.Connection = con
            cmd.CommandText = "INSERT Products (Name,Price,Description) VALUES (@Name,@Price,@Description)"

            ' Add parameters
            cmd.Parameters.AddWithValue("@Name", NewProduct.Name)
            cmd.Parameters.AddWithValue("@Price", NewProduct.Price)
            cmd.Parameters.AddWithValue("@Description", NewProduct.Description)

            ' Execute command
            Using con
                con.Open()
                cmd.ExecuteNonQuery()
            End Using
        End Sub

        ''' <summary>
        ''' Updates an existing product into the database
        ''' </summary>
        ''' <param name="productToUpdate">Product</param>
        Public Sub ProductUpdate(ByVal productToUpdate As Product)
            ' Create connection
            Dim con As SqlConnection = New SqlConnection(_connectionString)

            ' Create command
            Dim cmd As SqlCommand = New SqlCommand()
            cmd.Connection = con
            cmd.CommandText = "UPDATE Products SET Name=@Name,Price=@Price,Description=@Description WHERE Id=@Id"

            ' Add parameters
            cmd.Parameters.AddWithValue("@Name", productToUpdate.Name)
            cmd.Parameters.AddWithValue("@Price", productToUpdate.Price)
            cmd.Parameters.AddWithValue("@Description", productToUpdate.Description)
            cmd.Parameters.AddWithValue("@Id", productToUpdate.Id)

            ' Execute command
            Using con
                con.Open()
                cmd.ExecuteNonQuery()
            End Using
        End Sub

        ''' <summary>
        ''' Deletes an existing product in the database
        ''' </summary>
        ''' <param name="id">Product Id</param>
        Public Sub ProductDelete(ByVal Id As Integer)
            ' Create connection
            Dim con As SqlConnection = New SqlConnection(_connectionString)

            ' Create command
            Dim cmd As SqlCommand = New SqlCommand()
            cmd.Connection = con
            cmd.CommandText = "DELETE Products WHERE Id=@Id"

            ' Add parameters
            cmd.Parameters.AddWithValue("@Id", Id)

            ' Execute command
            Using con
                con.Open()
                cmd.ExecuteNonQuery()
            End Using
        End Sub

        ''' <summary>
        ''' Initialize the data access layer by
        ''' loading the database connection string from
        ''' the Web.Config file
        ''' </summary>
        Shared Sub New()
            _connectionString = WebConfigurationManager.ConnectionStrings("Store").ConnectionString
            If String.IsNullOrEmpty(_connectionString) Then
                Throw New Exception("No connection String configured in Web.Config file")
            End If
        End Sub
    End Class
End Namespace

The SqlDataAccessLayer component in Listing 14.27 grabs the database connection string that it uses when communicating with Microsoft SQL Server in its constructor. The connection string is assigned to a private field so that it can be used by all the component’s methods.

The SqlDataAccessLayer component has four public methods: ProductSelectAll(), ProductInsert(), ProductUpdate(), and ProductDelete(). These methods use the ADO.NET classes from the System.Data.SqlClient namespace to communicate with Microsoft SQL Server.

Note

We discuss ADO.NET in Chapter 16, “Building Data Access Components.”

Notice that the SqlDataAccessLayer component is not completely isolated from the components in the Business Logic Layer. The ProductSelectAll() method builds a collection of Product objects, which the method returns to the Business Logic layer. You should strive to isolate each layer as much as possible. However, in some cases, you cannot completely avoid mixing objects from different layers.

Summary

In this chapter, you learned how to build components in the .NET Framework. In the first part, you were given an overview of component building. You learned how to take advantage of dynamic compilation by using the App_Code folder. You also learned how to create component properties, methods, and constructors. You also examined several advanced topics related to components such as overloading, inheritance, MustInherit classes, and interfaces.

In the second half of this chapter, you learned how to build component libraries. You saw different methods for compiling a set of components into an assembly. You also examined how you can add components to both an application’s Bin folder and the Global Assembly Cache.

Finally, you had a chance to consider architectural issues related to building applications with components. You learned how to build a three-tiered application, divided into isolated User Interface, Business Logic, and Data Access layers.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset