ASP.NET VERSIONS: 2.0
One of the new features of ASP.NET 2.0 is the ability to create reusable components and use them without having to compile them even once. This is made possible by the addition of the new pre-defined directory named Code. The Code directory is a special directory used to store all the reusable components. Any reusable component placed in this directory will be automatically referenced and made available to all the pages in the Web site. ASP.NET 2.0 not only makes creating reusable components easier, but also allows you to easily consume them by providing a new data source control named ObjectDataSource. Using the ObjectDataSource control you can easily bind the output of an object s method directly to data-bound controls such as DropDownList, GridView, and so on. This article will discuss how to create a reusable component and then demonstrate how to consume that from an ASP.NET page.
Designing an n-tier client/server architecture can be much more complex than developing a two-tier architecture. However, the n-tier architecture produces a far more flexible and scalable application. In a two-tier architecture, the client and the server are the only layers. Both the presentation layer and the middle layer are handled by the client, with the database layer handled by the server. In an n-tier architecture, the client still handles the presentation layer but the middle layer and database layer are handled by one or more servers. The middle layer functions as a broker between the other two layers, sending the client s data requests to the database layer. The client is freed of application layer tasks, which eliminates the need for powerful client technology. In addition, costly database connections are optimized through the middle layer funneling users to a limited set of resources.
ASP.NET 2.0 provides native support for n-tier application design by providing the ObjectDataSource control, which is one of the most compelling new entries in the ASP.NET 2.0 arsenal of controls and components. It promotes the use of a strong object model in the middle tier of distributed applications and makes it easier than ever to set up a direct link between business logic and the presentation layer.
The Code directory, like the bin directory, is a special directory used by ASP.NET, but with the following exceptions: While the bin directory is designed for storing pre-compiled assemblies used by your application, the Code directory is designed for storing class files to be compiled dynamically at run time. This allows you to store classes for business logic components, data access components, and so on in a single location in your application, and use them from any page. Because the classes are compiled dynamically at run time and automatically referenced by the application containing the Code directory, you don t need to build the project before deploying it, nor do you need to explicitly add a reference to the class. ASP.NET monitors the Code directory and when new components are added, it dynamically compiles them. This makes it possible for you to easily make changes to a component and deploy it with a simple XCOPY or with a drag-and-drop operation. In addition to simplifying the deployment and referencing of components, the Code directory also greatly simplifies the creation and accessing of resource files (.resx) used in localization, as well as automatically generating and compiling proxy classes for WSDL files (.wsdl).
To better illustrate how this works, let s take a look at an example that demonstrates how to create a data access layer component and then invoke its methods from an ASP.NET page.
Implementing Master-Detail Capability
The following example will demonstrate how to implement master-detail display capabilities by using the data access components in conjunction with the declarative attributes of the ObjectDataSource, GridView, and DropDownList controls. In this example, you display the list of categories in the Northwind database in a DropDownList control and the products present in that category in a GridView control. When the user selects a different category from the DropDownList, the GridView control will be refreshed to display those products present in that newly selected category. Before creating the ASP.NET page, let s first create the data access layer component that retrieves the categories and products information from the Northwind database.
Creating the Data Access Components
Let s first create a new ASP.NET Web site by selecting New Web Site from the File menu. In the New Web Site dialog box, click on the Browse button. In the Choose Location dialog box, select Local IIS in the left navigation pane and in the right navigation pane, create three virtual directories (MyProjects, aspnetPro, ReusableComponents) in the same hierarchy and click Open. Now in the New Web Site dialog box, the location should read http://localhost/MyProjects/aspnetPro/ReusableComponents.
After the Web site is created, create a new Data Component by right-clicking on the Web site and selecting Add New Item from the context menu. In the Add New Item dialog box, select Data Component from the list of templates. Change the name of the file to CategoriesDataComponent.xsd and click Add. When you click Add, you will be prompted if you want to place the component inside the Code directory. Click OK in the prompt; this will bring up the Data Component Configuration Wizard. Steps to be followed in the Data Component Configuration Wizard are as follows:
1) Click Next in the first step.
2) Clicking Next will bring up the Choose Your Data Connection dialog box. In this dialog box, specify the connection string as shown in Figure 1.
3) In this step, you will be prompted if you want to save the connection string to the application configuration file. Uncheck the checkbox that says Yes, the save connection as. Click Next.
4) This will bring up the Choose a Command Type dialog box. In this step, the wizard will ask you to choose the command type. Select Use SQL Statements from the list of options and click Next.
5) Clicking Next brings up the Generate the SQL Statements dialog box, wherein you need to either type in the SQL statement or build the SQL statement using the Query Builder. For this example, simply type in Select * from Categories in the SQL Statement textbox and click Next.
6) This will produce the Choose Methods to Generate dialog box, wherein you can specify the list of methods you want to add to the data component (see Figure 2). In this dialog box, simply change the Method Name from GetData to GetCategories in the Return a DataTable option and leave all other values. Click Next.
7) Now you will be presented with the View Wizard Results dialog box; click Finish. This will result in a data component named CategoriesTableAdapter being created.
8) Now create one more data component by selecting Add New Item (from the Web site context menu); name the component ProductsDataComponent.xsd.
9) In all the prompts, specify information similar to the previous example. However, in the Generate SQL Statements dialog box, specify Select * from Products Where CategoryID = @CategoryID in the SQL Statement textbox and click Next (see Figure 3).
10) This will result in the Choose Methods to Generate dialog box, wherein you can specify the list of methods you want to add to the data component. In this dialog box, simply change the Method Name from GetData to GetProducts in the Return a DataTable option and leave all other values. Click Next.
11) Now you will be presented with the View Wizard Results dialog box. Click Finish in this dialog box. This will result in a data component named ProductsTableAdapter being created.
Figure 1: Specifying the connection string in the Data Component Wizard.
Figure 2: Specifying the methods for the Data Component.
Figure 3: Specifying the SQL statement in the Data Component Wizard.
That s all there is to creating a data access component using the Data Component Configuration Wizard. All you had to do is provide the wizard with certain information and Visual Studio hides all the complexities of creating the underlying code for you. Now that you ve created the component, let s examine and understand the steps involved in consuming the component.
Consuming the Component from an ASP.NET Page
When you are creating a distributed ASP.NET application, you will most likely split your application into multiple layers, such as presentation, business, and data access. This approach will result in an extensible application that can be easily maintained and enhanced over a period of time. ASP.NET complements this type of application design by providing a new ObjectDataSource control that can be used to directly bind an object s methods to data-bound controls, such as GridView, DataList, DropDownList, and so on. This approach provides for clean separation and encapsulation of code, thereby eliminating the need to write data access layer code in the presentation layer.
Now that you have an understooding of how to create the reusable component, let s create an ASP.NET page that leverages the components created in the previous step. Listing One shows an ASP.NET page named Products.aspx that implements master-detail capabilities by taking advantage of the ObjectDataSource control.
Let s walk through the of code shown in Listing One, which starts by declaring an ObjectDataSource named CategoriesSource. Before looking at the code, let s understand the two important attributes of the ObjectDataSource control. The TypeName attribute allows you to specify the name of the class to which you want to bind this control. The SelectMethod attribute allows you to specify the name of the method to invoke in the class. You use these methods to specify the name of the class and its method to which to bind the ObjectDataSource control. For CategoriesSource, set these attributes to CategoriesTableAdapter and GetCategories, which were created by the data access component in the previous step.
Then you bind the data in this CategoriesSource control to a DropDownList control named DropDownList1 by setting the DataSourceID attribute of the DropDownList to CategoriesSource. After that, declare one more ObjectDataSource control named ProductsSource. Basically, this control will be directly bound to the output of the GetProducts method. As mentioned before, the GetProducts method takes a category id as an argument and returns all the products in that category. To be able to invoke this method, the ProductsSource control should be able to pass in the selected category id from the DropDownList. You specify the value for the SQL query parameter using the SelectParameters template. In this case, you want to retrieve the value of the category identifier using the SelectedValue property of the DropDownList. To do this, set the FormField attribute of the FormParameter template to the name of the DropDownList. This allows the category id selected in the categories DropDownList to be used as an argument to the query. You also set the default value of 1 for the CategoryID using the DefaultValue property. This default value will be used when the page is requested the first time. In this example, you have used the FormParameter template to specify the parameter values for an object s method. Apart from ControlParameter, you can also use any one of the following parameter objects to provide values for the parameterized query:
- QueryStringParameter. Using this template, you can get the value of the parameter from a key-value combination in the current query string.
- SessionParameter. Allows you to get the parameter value from a specified Session variable.
- CookieParameter. Allows you to get the parameter value from a specified cookie.
- ControlParameter. Allows you to get the parameter value from a control on the page.
As you can see, you have accomplished all of these declaratively without writing even a single line of code. If you execute the code by navigating to the page using the browser, you will see an output as shown in Figure 4.
Figure 4: Output of the master-details page.
In Figure 4, when you change the categories from the DropDownList, the GridView will be refreshed to display the appropriate products that belong to a specific category.
Code Directory vs. Bin Directory
With the introduction of this new Code directory, you might be wondering when to use this directory when compared to the bin directory. If you have an assembly that you want to use in your Web site, create a bin subdirectory and then copy the .dll to that subdirectory. If you are creating reusable components that you want to use from your ASP.NET pages, all you need to do is create those components under the Code directory. Whenever a change occurs in the Code directory, ASP.NET will dynamically recompile the components and automatically make it available to all the pages in the Web site. Note that you should put only components into the Code subdirectory. You should not put pages, Web user controls, or other non-code files containing non-code elements into this subdirectory.
This article provided a thorough discussion on the steps to be followed for creating a reusable component in ASP.NET 2.0 and then consuming it from an ASP.NET page. In this article, you also learned how the ObjectDataSource control supports n-tier application design by allowing you to directly bind the output of an object s method directly to the controls in an ASP.NET page.
The sample code in this article is available for download.
Thiru Thangarathinam works at Intel Corp. in Chandler, AZ. He specializes in architecting, designing, and developing distributed enterprise class applications using .NET-related technologies. He has co-authored a number of books in .NET-related technologies. He has also been a frequent contributor to leading technology-related online publications. He can be reached at mailto:[email protected].
<%@ Page Language="VB" %>
End Listing One