Database Access in ASP.NET
A great deal of practical Web application development involves accessing data in various kinds of databases. A great thing about the .NET Framework is that it is very easy to encapsulate a database, allowing the rest of the program to work with data in a very generic way, without worrying about where it came from. In this section we discuss data binding in Web Forms controls, and we then present a database version of our Acme Travel Agency Web site.
Data Binding in ASP.NET
ASP.NET makes it easy to display data from various data sources by permitting a Web Forms control to be bound to data source. The data source can be specified in a variety of waysfor example, by directly giving a connection string to a database. This form of data binding is quite convenient in a two-tier type of application, where the presentation layer talks directly to the database. In three-tier applications it is more convenient to bind to some data structure that is returned by a middle-tier component, which does the actual connection to the database. Our Acme case study illustrates this approach. The Hotel.dll and Customer.dll components encapsulate access to a SQL Server database through the HotelBroker and Customers classes. Methods such as GetCities return an ArrayList, and the array list can be bound to a Web Forms control.13 We will look at two examples of data binding. The first, mentioned earlier in the chapter, illustrates binding to an ArrayList. The second illustrates binding to a DataTable through a DataView.
BINDING TO AN ARRAYLIST
It is extremely simple to bind to an array list. The AcmeWeb example, beginning with Step 0, provides an illustration. You may wish to bring up Step 0 and examine the code in AcmeWeb\Step0\WebForm1.aspx.vb. When the page is loaded, the DropDownList control listCities is initialized to display all the cities in the database of the hotel broker. The GetCities method returns the cities as strings in an array list. The following code will then cause the cities to be displayed in the dropdown.
broker = Global.broker Dim cities As ArrayList = broker.GetCities() listCities.DataSource = cities ... DataBind()
The DataBind method of the Page class causes all the Web Forms controls on the page to be bound to their data sources, which will cause the controls to be populated with data from the data sources. You could also call the DataBind method of a particular control.
BINDING TO A DATATABLE
As we saw in Chapter 13, ADO.NET defines a very useful class, the DataTable, which can be used to hold data from a variety of data sources. Once created, a data table can be passed around and used in a variety of contexts. One very useful thing you can do with a data table is to bind it to a Web Forms control. Since a data table is self-describing, the control can automatically display additional information, such as the names of the columns. We illustrate with the DataGrid control.
To run this example, you need to have SQL Server or MSDE installed on your system, and you should also have set up the Acme database, as described in Chapter 13. The example Web page is DataGridControl/ ShowHotels.aspx. As usual, you should use IIS to configure the folder Data-GridControl as an application. This page will display all the hotels in the Acme database in a data grid, with appropriate headings, as illustrated in Figure 1439. When you work with Web Forms controls you can easily change styles, such as fonts and colors, by setting properties appropriately.
Figure 14-39 Displaying hotels in the Acme database using a DataGrid control.
The relevant VB.NET code is in the files Global.asax.vb and ShowHo-tels.aspx.vb. The first thing we need to do is to create an instance of the HotelBroker class. We create a single instance, once, when the application starts up. We save this instance as a public shared variable.
' Global.asax.vb Imports System.Web Imports System.Web.SessionState Imports OI.NetVb.Acme Public Class Global Inherits System.Web.HttpApplication #Region " Component Designer Generated Code " ... Public Shared broker As HotelBroker Sub Application_Start(ByVal sender As Object, _ ByVal e As EventArgs) broker = New HotelBroker() End Sub ...
In the Page_Load method (in file ShowHotels.aspx.vb) we get the hotels from the Hotel Broker, call a helper method to obtain the data source, assign the data source, and bind. We are using the DataTable to hold data obtained from the middle-tier component.
Private Function CreateDataSource( _ ByVal list As ArrayList) As ICollection If list Is Nothing Then Return Nothing End If Dim dt As New DataTable() Dim dr As DataRow dt.Columns.Add(New DataColumn("City", GetType(String))) dt.Columns.Add(New DataColumn("Hotel", GetType(String))) dt.Columns.Add(New DataColumn("Rooms", _ GetType(Integer))) dt.Columns.Add(New DataColumn("Rate", GetType(Decimal))) Dim hi As HotelListItem For Each hi In list dr = dt.NewRow() dr(0) = hi.City.Trim() dr(1) = hi.HotelName.Trim() dr(2) = hi.NumberRooms dr(3) = hi.Rate dt.Rows.Add(dr) Next Dim dv As New DataView(dt) Return dv End Function
Acme Travel Agency Case Study (Database Version)
We have illustrated many concepts of ASP.NET with our Acme Travel Agency case study. For simplicity we used a version of the case study that stored all data as collections in memory. This way you did not have to worry about having a database set up properly on your system, so you could focus on just ASP.NET. Also, the results are always deterministic, since sample data is hardcoded.
Now, however, we would like to look at the "real" case study, based upon our HotelBroker database, and the database version of the Hotel.dll and Customer.dll components created in Chapter 13.
The Acme Travel Agency maintains its own database of customers. Customers register with Acme through the Web site. The following information is stored in Acme's database:
Currently we use LoginName (corresponding to what we called "UserId" earlier in the chapter) and HotelBrokerCustomerId. The AirlineBrokerCustomerId field will facilitate Acme adding an airplane reservation system later. A Password field is also provided for possible future use.
The AcmeCustomer database should have been set up as part of the database setup from Chapter 13. To set up the AcmeCustomer database (or restore it to its original state), all you need to do is to run the script acmedb.sql, which is located in the Databases directory from Chapter 13. This script assumes you have SQL Server installed on partition c:. If your installation is in a different partition, edit the script accordingly.
ACME WEB SITE (CASE STUDY)
The Case Study version of the Acme Web site is in the CaseStudy folder for this chapter. As usual, you will need to use IIS to configure this directory as an application. You can start from the home page for this chapter, or directly from the URL
You should find the code very easy to understand, because it relies on the same interfaces as the implementation we used earlier based on collections. The database code for accessing the AcmeCustomer database is in the file Acme.vb.