Database Access in ASP.NET

for RuBoard

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 ways ”for 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. [15]

[15] The component could be hidden behind a Web Service, which will be illustrated in Chapter 11. We can still use data binding in such a scenario, by binding to an array list.

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 case study code, beginning with Step 1, provides an illustration. You may wish to bring up Step 1 of the case study and examine the code in CaseStudy\Step1\ MakeReservations.aspx.cs . 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.

 ArrayList cities = hotelBroker.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 9, 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 9. The example Web page is DataGridControl/ShowHotels.aspx . As usual, you should use IIS to configure the folder DataGridControl 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 10-39. When you work with Web Forms controls you can easily change styles, such as fonts and colors, by setting properties appropriately.

Figure 10-39. Displaying hotels in the Acme database using a DataGrid control.

graphics/10fig39.gif

The relevant C# code is in the files Global.asax.cs and ShowHotels. aspx.cs . 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.

 // Global.asax.cs  using System;  using System.Collections;  using System.ComponentModel;  using System.Web;  using System.Web.SessionState;  using OI.NetCs.Acme;  namespace DataGridControl  {     public class Global : System.Web.HttpApplication     {  public static HotelBroker hotelBroker;  protected void Application_Start(Object sender,                                         EventArgs e)        {  hotelBroker = new HotelBroker();  }        ... 

In the Page_Load method we get the hotels from the Hotel Broker, call a helper method, CreateDataSource , to obtain an ICollection interface reference (the data binding is very general, and any collection can be used), assign the data source, and bind. We are using the DataTable to hold data obtained from the middle-tier component.

 private void Page_Load(object sender, System.EventArgs e)  {     if (!IsPostBack)     {        // Need to load this data only once.        ArrayList array = Global.hotelBroker.GetHotels();        dgHotels.DataSource= CreateDataSource(array);        dgHotels.DataBind();     }  } 

It is in the helper method CreateDataSource that the interesting work is done. A data table is created and populated with hotel data obtained from the Hotel Broker.

 private ICollection CreateDataSource(ArrayList array)  {     if (array == null)     {        return null;     }     DataTable dt = new DataTable();     DataRow dr;     dt.Columns.Add(new DataColumn("City", typeof(string)));     dt.Columns.Add(new DataColumn("Hotel", typeof(string)));     dt.Columns.Add(new DataColumn("Rooms", typeof(int)));     dt.Columns.Add(new DataColumn("Rate", typeof(decimal)));     foreach(HotelListItem hotel in array)     {        dr = dt.NewRow();        dr[0] = hotel.City.Trim();        dr[1] = hotel.HotelName.Trim();        dr[2] = hotel.NumberRooms;        dr[3] = hotel.Rate;        dt.Rows.Add(dr);     } 

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 9.

AcmeCustomerDatabase

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:

  • LoginName

  • Password

  • HotelBrokerCustomerId

  • AirlineBrokerCustomerId

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.

To set up the database, all you need to do is to run the script acmedb.sql , which is located in the directory AcmeScript . This script assumes you have SQL Server installed on partition c: . If your installation is in a different partition, edit the script accordingly .

AcmeLibDb Component

The directory AcmeLibDb contains a class library project for building an AcmeLib component that encapsulates access to the AcmeCustomerDatabase. This component also wraps access to HotelBroker and Customers , providing the Web pages with a very easy programming model.

Acme Web Site (Step 3)

The Step 3 version of the Acme Web site is in CaseStudy\Step3 . As usual, you will need to use IIS to configure this directory as an application. You can start it from the URL http://localhost/netcs/CaseStudy/Step3/Login.aspx

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.

for RuBoard


Application Development Using C# and .NET
Application Development Using C# and .NET
ISBN: 013093383X
EAN: 2147483647
Year: 2001
Pages: 158

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net