Chapter 23 - Component-Based Programming PDF

Title Chapter 23 - Component-Based Programming
Author USER COMPANY
Course Asp.Net With C#
Institution University of Mumbai
Pages 32
File Size 967.7 KB
File Type PDF
Total Downloads 45
Total Views 468

Summary

CHAPTER 23 Component-Based Programming C omponent-based programming is a simple, elegant idea. When used properly, it allows your code to be more organized, consistent, and reusable. It’s also incredibly easy to implement in a .NET application, because you never need to use the Windows registry or p...


Description

CHAPT ER

23

Component-Based Programming C

omponent-based programming is a simple, elegant idea. When used properly, it allows your code to be more organized, consistent, and reusable. It’s also incredibly easy to implement in a .NET application, because you never need to use the Windows registry or perform any special configuration. A component, at its simplest, is one or more classes that are compiled into a separate DLL assembly file. These classes provide some unit of logically related functionality. You can access a component in a single application, or you can share the component between multiple applications. Your web pages (or any other .NET application) can use the classes in your components in the same way they use any other .NET class. Best of all, your component is encapsulated, which means it provides exactly the features your code requires and hides all the other messy details. When combined with careful organization, component-based programming is the basis of good ASP.NET application design. In this chapter, you’ll examine how you can create components (and why you should) and consider examples that show you how to encapsulate database functionality with a well-written business object. You’ll also learn how to bind your database component to the web controls on a page using the ObjectDataSource.

Why Use Components? To master ASP.NET development you need to become a skilled user of the .NET class library. So far, you’ve learned how to use .NET components designed for reading files, communicating with databases, calling web services, and storing information about the user. Though these class library ingredients are powerful, they aren’t customizable, which is both an advantage and a weakness. For example, if you want to retrieve data from a SQL Server database, you need to weave database details (such as SQL queries) directly into your code-behind class or (if you’re using the SqlDataSource) into the .aspx markup portion of your web page file. Either way if the structure of the database changes even slightly, you could be left with dozens of pages to update and retest. To solve these problems, you need to create an extra layer between your web page code and the database. This extra layer takes the form of a custom component. This database scenario is only one of the reasons you might want to create your own components. Component-based programming is really just a logical extension of good codeorganizing principles, and it offers a long list of advantages:

789

790

C HA PT ER 23  C O MPO NENT- BA SED PRO G RA MMING

Safety: Because the source code isn’t contained in your web page, you can’t modify it. Instead, you’re limited to the functionality your component provides. For example, you could configure a database component to allow only certain operations with specific tables, fields, or rows. This is often easier than setting up complex permissions in the database. Because the application has to go through the component, it needs to play by its rules. Better organization: Components move the clutter out of your web page code. It also becomes easier for other programmers to understand your application’s logic when it’s broken down into separate components. Without components, commonly used code has to be copied and pasted throughout an application, making it extremely difficult to change and synchronize. Easier troubleshooting: It’s impossible to oversell the advantage of components when testing and debugging an application. Component-based programs are broken down into smaller, tighter blocks of code, making it easier to isolate exactly where a problem is occurring. It’s also easier to test individual components separate from the rest of your web application. More manageability: Component-based programs are much easier to enhance and modify because the component and web application code can be modified separately. Taken to its extreme, this approach allows you to have one development team working on the component and another team coding the website that uses the component. Code reuse: Components can be shared with any ASP.NET application that needs the component’s functionality. Even better, any .NET application can use a component, meaning you could create a common “backbone” of logic that’s used by a web application and an ordinary Windows application. Simplicity: Components can provide multiple related tasks for a single client request (writing several records to a database, opening and reading a file in one step, or even starting and managing a database transaction). Similarly, components hide details—an application programmer can use a database component without worrying about the database name, the location of the server, or the user account needed to connect. Even better, you can perform a search using certain criteria, and the component itself can decide whether to use a dynamically generated SQL statement or stored procedure.

Component Jargon Component-based programming is sometimes shrouded in a fog of specialized jargon. Understanding these terms helps sort out exactly what a component is supposed to do, and it also allows you to understand MSDN articles about application design. If you’re already familiar with the fundamentals of components, feel free to skip ahead.

Three-Tier Design The idea of three-tier design is that the functionality of most complete applications can be divided into three main levels (see Figure 23-1). The first level is the user interface (or

C HA PT ER 23  C O MPO NENT- BA SED PRO G RA MMING

presentation tier), which displays controls and receives and validates user input. All the event handlers in your web page are in this first level. The second level is the business tier, where the application-specific logic takes place. For an e-commerce site, application-specific logic includes rules such as how shipping charges are applied to an order, when certain promotions are valid, and what customer actions should be logged. It doesn’t involve generic .NET details such as how to open a file or connect to a database. The third level is the data tier, where you place the logic that stores your information in files, a database, or some other data store. The third level contains logic about how to retrieve and update data, such as SQL queries or stored procedures.

Figure 23-1. Three-tier design

791

792

C HA PT ER 23  C O MPO NENT- BA SED PRO G RA MMING

The important detail about three-tier design is that information travels from only one level to an adjacent level. In other words, your web page code shouldn’t connect directly to the database to retrieve information. Instead, it should go through a component in the business tier that connects to the database and returns the data. This basic organization principle can’t always be adhered to, but it’s a good model to follow. When you create a component it’s almost always used in the second level to bridge the gap between the data and the user interface. In other words, if you want to fill a list of product categories in a list box, your user interface code calls a component, which gets the list from the database and then returns it to your code. Your web page code is isolated from the database—and if the database structure changes, you need to change one concise component instead of every page on your site.

Encapsulation If three-tier design is the overall goal of component-based programming, encapsulation is the best rule of thumb. Encapsulation is the principle that you should create your application out of “black boxes” that hide information. So, if you have a component that logs a purchase on an e-commerce site, that component handles all the details and allows only the essential variables to be specified. For example, this component might accept a user ID and an order item ID and then handle all the other details. The calling code doesn’t need to worry about how the component works or where the data is coming from—it just needs to understand how to use the component. (This principle is described in a lot of picturesque ways. For example, you know how to drive a car because you understand its component interface—the steering wheel and pedals— not because you understand the low-level details about internal combustion and the engine. As a result, you’re able to transfer your knowledge to many different types of automobiles, even if they have dramatically different internal workings.)

Business Objects The term business object often means different things to different people. Generally, business objects are the components in the second level of your application that provide the extra layer between your code and the data source. They are called business objects because they enforce business rules. For example, if you try to submit a purchase order without any items, the appropriate business object will throw an exception and refuse to continue. In this case, no .NET error has occurred—instead, you’ve detected the presence of a condition that shouldn’t be allowed according to your application’s logic. In this chapter’s examples, business objects are also going to contain data access code. In an extremely complicated, large, and changeable system, you might want to further subdivide components and actually have your user interface code talking to a business object, which in turn talks to another set of objects that interact with the data source. However, for most programmers, this extra step is overkill, especially with the increased level of sophistication ADO.NET provides.

Data Objects The term data object is also used in a variety of ways. In this book, data objects are simply packages of data that you use to send information between your web page and your business

C HA PT ER 23  C O MPO NENT- BA SED PRO G RA MMING

objects. For example, you might create a data class named Employee that represents the information from one record in an Employees table, complete with properties like FirstName, LastName, and DateOfBirth. A typical data object is filled with properties, but provides no methods.

Components and Classes Technically, a component is just a collection of one or more classes (and possibly other .NET types, such as structures and enumerations) that are compiled together as a unit. For example, Microsoft’s System.Web.dll is a single (but very large) component that provides the types found in many of the namespaces that start with System.Web. So far, the code examples in this book have used only a few kinds of classes—mainly custom web page classes that inherit from System.Web.UI.Page and contain mostly eventhandling procedures. Component classes, on the other hand, usually won’t include any user interface logic (which would limit their use unnecessarily) and don’t need to inherit from an existing class. They are more similar to the custom web service classes described in Part 4 of this book, which collect related features together in a series of utility methods.

Creating a Component To create a component, you create a new class library project in Visual Studio. Just select File Ê New Ê Project, and choose the Class Library project template in the New Project dialog box (see Figure 23-2). You’ll need to choose a file location and a project name.

Figure 23-2. Creating a component in Visual Studio

793

794

C HA PT ER 23  C O MPO NENT- BA SED PRO G RA MMING

Rather than just choosing File Ê New Project to create the class library, you can add it to the same solution as your website. This makes it easy to debug the code in your component while you’re testing it with a web page. (On its own, there’s no way to run a component, so there’s no way to test it.) To create a new class library in an existing web solution, start by opening your website, and then choose File Ê Add Ê New Project. Specify the directory and project name in the Add New Project dialog box. Figure 23-3 shows a solution with both a website and a class library named Components. The website is in bold in the Solution Explorer to indicate that it runs on start-up (when you click the Start button).

Figure 23-3. A solution with a website and class library project To make it easy to open this solution, you might want to take a moment to save it. Click the solution name (which is “Components” in Figure 23-3) in the Solution Explorer. Then choose File Ê Save [SolutionName] As. You can open this .sln file later to load both the website and class library project. You can compile your class library at any point by right-clicking the project in the Solution Explorer and choosing Build. This creates a DLL assembly file (Components.dll). You can’t run this file directly, because it isn’t an application, and it doesn’t provide any user interface.

Note Unlike web pages and web services, you must compile a component before you can use it. Components aren’t hosted by the ASP.NET service and IIS; thus, they can’t be compiled automatically when they are needed. However, you can easily recompile your component in Visual Studio (and depending on the references and project settings you use, Visual Studio may perform this step automatically when you launch your web application in the design environment).

Classes and Namespaces Once you’ve created your class library project, you’re ready to add classes in a .cs file. Class library projects begin with one file named Class1.cs, which you can use, delete, or rename. You can also add more class files simply by right-clicking on the project in the Solution Explorer

C HA PT ER 23  C O MPO NENT- BA SED PRO G RA MMING

and choosing Add Ê Class. The only difference between class library projects and web applications is that your class files won’t be placed in an App_Code subdirectory. Here’s an example that creates a class named SimpleTest: public class SimpleTest { // (Code goes here, inside one or more methods.) } Remember, a component can contain more than one class. You can create these other classes in the same file, or you can use separate files for better organization. In either case, all the classes and source code files are compiled together into one assembly: public class SimpleTest { ... } public class SimpleTest2 { ... } Usually, classes are placed inside a namespace block. That means your code will actually look like this: namespace Components { public class SimpleTest { // (Class code omitted.) } public class SimpleTest2 { // (Class code omitted.) } } When you add a new class file to a class library, C# automatically adds a namespace block using the default namespace for your project. The classes in your component are automatically organized into a namespace that’s named after your project. For example, if you’ve created a project named Components, the SimpleTest and SimpleTest2 classes will be in the Components namespace (shown here), and their fully qualified names will be Components.SimpleTest and Components.SimpleTest2. You need to know the fully qualified name in order to use your classes in another application, because other applications won’t share the same namespace. If you don’t like the default namespace, you can edit the namespace name in all your code files. However, there’s an easier way—you can simply ask Visual Studio to change the default namespace for your project. That way, whenever you add a new class file to your project, Visual Studio will insert a namespace block that uses the namespace name you want. To change the default namespace, begin by right-clicking the project in the Solution Explorer and choosing Properties. You’ll see a multitabbed display of application settings. Choose the Application tab and then edit the namespace in the Default Namespace text box. You can also

795

796

C HA PT ER 23  C O MPO NENT- BA SED PRO G RA MMING

use the Assembly Name text box in this window to configure the name that is given to the compiled assembly file. If you have a complex component, you might choose to subdivide it into nested namespaces. For example, you might have a namespace named Components.Database and another named Components.Validation. To create a nested namespace inside the default project namespace, you use a namespace block like this: namespace Components { namespace Database { public class SimpleDatabaseTest { // (Class code omitted.) } } }

Tip The general rule for naming namespaces is to use the company name followed by the technology name and optionally followed by a feature-specific division, as in CompanyName.TechnologyName.Feature. Example namespaces that follow this syntax include Microsoft.Media and Microsoft.Media.Audio. These namespace conventions dramatically reduce the possibility that more than one company might release components in the same namespaces, which would lead to naming conflicts. The only exception to the naming guidelines is in the base assemblies that are part of .NET. They use namespaces that begin with System.

Class Members To add functionality to your class, add public methods or properties. The web page code can then call these members to retrieve information or perform a task. The following example shows one of the simplest possible components, which does nothing more than return a string to the calling code: public class SimpleTest { public string GetInfo(string param) { return "You invoked SimpleTest.GetInfo() with '" + param + "'"; } }

C HA PT ER 23  C O MPO NENT- BA SED PRO G RA MMING

public class SimpleTest2 { public string GetInfo(string param) { return "You invoked SimpleTest2.GetInfo() with '" + param + "'"; } } In the following sections, you’ll learn how to use this component in a web application. A little later, you’ll graduate to a more complex, practical component.

Adding a Reference to the Component Using the component in an actual ASP.NET page is easy. Essentially, your website needs a copy of your component in its Bin directory. ASP.NET automatically monitors this directory and makes all of its classes available to any web page in the application. To create this copy, you use a Visual Studio feature called references. Here’s how it works: First, select your website in the Solution Explorer. Then, select Website Ê Add Reference from the menu. This brings you to the Add Reference dialog box. (Don’t choose Add Web Reference, which is used to connect an application to a web service, and has little in common with the similarly named Add Reference command.) You can take one of two approaches in the Add Reference dialog box: Add a project reference: If your class library project is in the same solution, use the Projects tab. This shows you a list of all the class library projects in your current solution (see Figure 23-4). Select the class library, and click OK. Add an assembly reference: If your class library is in a different solution, or you have the compiled DLL file only (perhaps the component was created by another developer), use the Browse tab (see Figure 23-5). Browse through your directories until you find the DLL file, select it, and click OK.

Note If you’re using an assembly reference, you need to compile your component first (choose Build Ê Build Solution from the Visual Studio menu) before you can add the reference.

797

798

C HA PT ER 23  C O MPO NENT- BA SED PRO G RA MMING

Figure 23-4. Adding a project reference

Figure 23-5. Adding an assembly reference Either way, .NET copies the compiled DLL file to the Bin subdirectory of your web application (see Figure 23-6). Visual Studio also takes extra care to make sure that you keep using the most up-to-date version of the component. If you change the component and recompile it, Visual Studio will notice the change. The next time you run your web application, Visual Studio will automatically copy the new component to the Bin subdirectory.

C HA PT ER 23  C O MPO NENT- BA SED PRO G RA MMING

If you’re using a projec...


Similar Free PDFs