Professional ASP.NET 2.0 XML phần 7 pot

60 314 0
Professional ASP.NET 2.0 XML phần 7 pot

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

13_596772 ch10.qxd 12/13/05 11:19 PM Page 334 Building an Airline Reservation System Using ASP.NET 2.0 and SQL Server 2005 So far in this book, you have learned about XML DOM, XML support in ADO.NET, XSLT features in .NET, XML data display, and XML support in SQL Server 2005. This chapter focuses on incorpo- rating these features in a real-world Web site. This case study not only discusses the application of these features in a Web site but also demonstrates the best practices of using these features. Toward this end, this chapter discusses and showcases the following features: ❑ How to design and develop an N-tier Web site using the XML features of ASP.NET 2.0 and SQL Server 2005. To support this design, this chapter discusses how to encapsulate the data access logic in the form of reusable components. ❑ How to work with an XML data type column by persisting data in it using ADO.NET ❑ How to utilize the XSD schemas support provided by SQL Server 2005 to validate XML data ❑ How to transform the XML data into HTML using the XSLT features of .NET 2.0 ❑ How to display the XML data using an XmlDataSource control with a GridView control ❑ How to read and write XML data using XmlReader and XmlWriter classes ❑ How to validate XML data using XSD schemas 14_596772 ch11.qxd 12/13/05 11:19 PM Page 335 Overview of the Case Study For this case study, consider an airline reservations system. This airline system provides the basic fea- tures of an online reservation system. Some of the features include searching for flights based on specific search criteria and booking tickets for a particular flight. It also provides for the users to have member- ship in the site by registering themselves with the site. Architecture of System Figure 11-1 illustrates the proposed architecture of the online reservation system. Figure 11-1 As shown in Figure 11-1, the Web site primarily depends on the middle tier .NET component (AirlineReservationsLib) for all of its functionalities. When the user comes to the site and performs oper- ations such as searching for flights, the Web site invokes the methods of the .NET component to carry out those tasks. Before looking at the implementation of the architecture, it is important to examine the business processes supported by the ShoppingAssistant. Business Processes Although the scope of the case study is to show how to effectively utilize XML features of ASP.NET 2.0 and SQL Server 2005 to build a Web site, it is imperative that you review the business processes before Architecture of Online Reservation Web Site Browser AirlineReservation Web Site Data Access Layer Internet SQL Server 2005 Database 336 Chapter 11 14_596772 ch11.qxd 12/13/05 11:19 PM Page 336 choosing the best approach. The business processes that the online reservation system is going to have to enable are as follows: ❑ Login process— The login system allows the users to identify themselves to the system. The user must provide a valid user id and a valid password to be able to log onto the system. After logged in, the user can carry out tasks such as searching for flights and booking tickets. ❑ New user registration process — If you are a new user, you have the opportunity to become a member of the site by filling out the online forms and selecting the desired preferences. In this step, the user is asked to create a unique user id, which is used to identify the user in the sys- tem. The user is also required to choose a password of his choice to protect their membership and prevent someone else from using their account. And the user also can fill out relevant details like name, address, and so on. After the user enters all the details, the user’s profile is stored in the database for later retrieval. ❑ Search flights process — As the name suggests, this process allows the user to search for flights. ❑ Book tickets process— In this process, the user can book the tickets for a specified flight. ❑ Logout process— Allows the user to log out of the site, thereby terminating the session. Limitations This case study is not aimed at demonstrating how to build and deploy a real-world online reservation system. The intended purpose is to show how to tie different XML features of ASP.NET together. For that reason, many issues are not addressed in this example, including: ❑ Security — No regard is taken to security in the implementation of the Web services in this example. ❑ Payment — Obviously in this example no real bookings are made and none of the issues con- cerned with payment are handled. Implementation Now that you have understood the business processes involved, examine the individual building blocks that are required for implementing this solution. For the purposes of this example, the discussion of the remaining part of the case study will be split into the following sections. ❑ Database design ❑ Implementation of .NET component (AirlineReservationsLib) ❑ Implementation of Web site To start with, consider the database design that is required to support the Web site. Database Design The database, called AirlineReservation, used in this case study has minimum number of tables required to implement this solution. The AirlineReservation database consists of six tables. The entity relationship diagram for the database is as follows: 337 Building an Airline Reservation System 14_596772 ch11.qxd 12/13/05 11:19 PM Page 337 Figure 11-2 The structure of these tables is shown in Table 11-1, starting with Flights table. Table 11-1. Structure of Flights Table Name Data Type Length AllowNull Description flight_id int 4 No Represents the flight id flight_number char 10 No Represents the flight number destination varchar 50 No Destination location starting_from varchar 50 No Starting location departure_date Datetime 8 No Departure date arrival_date Datetime 8 No Arrival date aircraft_type varchar 50 Yes Type of the air craft price money 8 Yes Price 338 Chapter 11 14_596772 ch11.qxd 12/13/05 11:19 PM Page 338 The Travel_Class table is defined in Table 11-2. Table 11-2. Structure of Travel_Class Table Name Data Type Length AllowNull Description travel_class_id int 4 No Represents the travel class id travel_class_code char 1 No Represents the different travel class codes travel_class_ varchar 50 No Provides a description of the travel description class The stored procedure named SearchFlight is used to search for flights based on the following parame- ters: starting location, destination, arrival date, departure date, and the type of travel class. CREATE Procedure dbo.SearchFlight @startingFrom varchar(50), @destination varchar(50), @arrivalDate datetime, @departureDate datetime, @travelClassID int As Begin set nocount on select F.*,TC.travel_class_id from flights F inner join travel_class_seat_capacity TCSC on TCSC.flight_id = F.flight_id inner join travel_class TC on TC.travel_class_id = TCSC.travel_class_id where F.starting_from = @startingFrom and F.destination = @destination and F.arrival_date = @arrivalDate and F.departure_date = @departureDate and TC.travel_class_id = @travelClassID and TCSC.number_of_seats > 0 End Table 11-3 describes the structure of the Travel_Class_Capacity table. Table 11-3. Structure of Travel_Class_Capacity Table Name Data Type Length AllowNull Description flight_id int 4 No Represents the flight id travel_class_id int 4 No Represents the travel class id number_of_seats Int 4 No Number of seats available in a particular flight The Bookings table is defined as follows in Table 11-4. 339 Building an Airline Reservation System 14_596772 ch11.qxd 12/13/05 11:19 PM Page 339 Table 11-4. Structure of Bookings Table Name Data Type Length AllowNull Description booking_id int 4 No Represents the booking id flight_id int 4 No Represents the flight id passenger_id int 4 No Specifies the passenger id travel_class_id int 4 No Specifies the travel class id date_booking_made datetime 8 No Specifies the date of booking To create a new booking in the bookings table, a stored procedure named InsertBooking is utilized. CREATE procedure dbo.InsertBooking @flightID int, @passengerID varchar(20), @travelClassID int, @bookingID int output As Begin Set nocount on Insert into Bookings(flight_id,passenger_id,travel_class_id) Values(@flightID,@passengerID,@travelClassID) Select @bookingID = @@identity End The definition of Stocks table is shown in Table 11-5. Table 11-5 Structure of Stocks Table Name Data Type Length AllowNull Description name Char 4 No Represents the company symbol price Varchar 10 No Represents the stock price The stored procedure GetStockQuote retrieves the stock quote based on the supplied symbol. Create procedure GetStockQuote @Name char(4) As Begin set nocount on select * from Stocks where Name = @Name FOR XML AUTO, Elements End The Users table that is meant for storing the details of the logged on users is shown in Table 11-6. 340 Chapter 11 14_596772 ch11.qxd 12/13/05 11:19 PM Page 340 Table 11-6. Structure of Users Table Name Data Type Length AllowNull Description UserID varchar 20 No Represents the User ID Password varchar 10 No Represents the password assigned to a user Name varchar 128 No Represents the name of the logged on user Address varchar 128 Yes Represents the address of the user Phone xml N/A Yes Typed XML column that represents the phone numbers XML format City varchar 50 Yes Represents the city State char 2 Yes Represents the state Zip char 9 Yes Represents the zip code As you can see from Table 11-6, the Phone column is a typed column that has an XML schema associated with it. The DDL for creating the schema used by this column is as follows: CREATE XML Schema collection PhoneSchema as N’<xs:schema attributeFormDefault=”unqualified” elementFormDefault=”qualified” xmlns:xs=”http://www.w3.org/2001/XMLSchema”> <xs:element name=”phone”> <xs:complexType> <xs:sequence> <xs:element name=”homePhone” type=”xs:string” /> <xs:element name=”cellPhone” type=”xs:string” /> <xs:element name=”officePhone” type=”xs:string” /> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>’ GO After the schema is created, you can associate the schema with the Phone column using the Alter Table statement. Alter table Users Alter Column Phone XML(PhoneSchema) To insert rows into the Users table, the InsertUser stored procedure is utilized. CREATE Procedure InsertUser (@UserID char(20), @Password char(10), @Name varchar(128), @Address varchar(128), @Phone xml, @City varchar(50), @State char(2), @Zip char(5)) As Begin Insert into Users(UserID,Password,Name,Address,Phone, City,State,Zip) Values(@UserID,@Password,@Name,@Address,@Phone,@City,@State,@Zip) End 341 Building an Airline Reservation System 14_596772 ch11.qxd 12/13/05 11:19 PM Page 341 In addition to storing the user details, you also need a way to be able to verify the credentials of a user that is trying to log onto the site. To this end, the CheckUserLogin is used. CREATE Procedure CheckUserLogin ( @UserID varchar(20), @Password varchar(10), @RetValue int OUTPUT ) As Begin SELECT * FROM Users WHERE UserID = @UserID AND Password = @Password IF @@Rowcount < 1 SELECT @RetValue = -1 ELSE SELECT @RetValue = 1 End Now that you have implemented the stored procedures, the next step is to implement the middle tier component that will consume the stored procedures. Implementation of AirlineReservationsLib Component In this section, you learn the implementation of the C# class library AirlineReservationsLib. This compo- nent contains all the necessary classes and methods that provide the core functionalities for the online reservations system. To start, create a new Visual C# Class library project named AirlineReservationsLib using Visual Studio 2005. After the project is created, change the name of the default class from Class1 to UserInfo. The UserInfo class simply acts as a container for holding user-related data, and its imple- mentation is shown in Listing 11-1. Listing 11-1: Declaration of the UserInfo Class using System; namespace AirlineReservationsLib { [Serializable] public class UserInfo { protected string userID; protected string passWord; protected string name; protected string address; protected string phone; protected string city; protected string state; protected string zip; public string UserID { get{return userID;} set{userID = value;} } public string PassWord { 342 Chapter 11 14_596772 ch11.qxd 12/13/05 11:19 PM Page 342 get{return passWord;} set{passWord = value;} } public string Name { get{return name;} set{name = value;} } public string Address { get{return address;} set{address = value;} } public string Phone { get{return phone;} set{phone = value;} } public string City { get{return city;} set{city = value;} } public string State { get{return state;} set{state = value;} } public string Zip { get{return zip;} set{zip = value;} } } } As you can see from this code, the UserInfo class simply exposes a bunch of properties that act as the container for user-related data. Implementation of Data Access Layer Methods So far, you have seen the container class for holding user-related data. That is only part of the story, and you need a data access layer class for persisting that data and retrieving that data from the Users table. This is where the UserDB class comes into play. Implementation of the UserDB class is illustrated in Listing 11-2. Listing 11-2: Implementation of UserDB Class using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Text; 343 Building an Airline Reservation System 14_596772 ch11.qxd 12/13/05 11:19 PM Page 343 [...]... flights = flightObj.SearchFlight(startingFrom, destination, departureDate, arrivalDate, 1); return TransformXmltoHtml(flights.GetXml()); } else { throw new ApplicationException(“Input XML is Invalid”); } } string TransformXmltoHtml(string xml) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml (xml) ; string xslPath = Request.PhysicalApplicationPath + @”\App_Data\SearchOutput.xsl”; XslCompiledTransform... combination of an XmlDataSource control and a GridView control The XmlDataSource control acts as the source of data for the GridView control that actually displays the stock quote 351 Chapter 11 The XmlDataSource control utilizes a local XML file Stocks .xml as the source of XML data The Stocks .xml file is... input XML search criteria ❑ Use of ASP.NET 2.0 Script Callback to asynchronously retrieve XML data from the client side without refreshing the browser ❑ Use of the XML features of DataSet object to convert the DataSet object contents into an XML representation ❑ Transformation of XML to HTML using XSL transformation SearchFlights Page Flow Transforms the DataSet XML to HTML Validates the input XML using... the XML file is not available, it invokes a local method named CreateXml() to create the XML file by calling the GetStockQuote() method of the StockDB class void CreateXmlFile(string path) { StockDB stock = new StockDB(); XmlDocument doc = stock.GetStockQuote(“WOTS”); doc.Save(path); } The XmlDocument returned by the GetStockQuote() method is directly saved to the Stocks .xml file If the Stocks .xml. .. exercise except for the fact that you need to create an XML string for the Phone property of the UserInfo object string xml = CreateXml(); user.Phone = xml; The creation of an XML structure for the phone details is accomplished through a helper method named CreateXml(), which simply creates an XML string on the fly dynamically using the methods of the XmlWriter object Figure 11-4 shows the registration... command.Parameters.Add(paramName); XmlReader reader = command.ExecuteXmlReader(); XmlDocument doc = new XmlDocument(); //Load the XmlReader to an XmlDocument object doc.Load(reader); return doc; } } catch (Exception ex) { throw ex; } } } } The GetStockQuote() method simply retrieves the stock quote by executing a stored procedure named GetStockQuote that accepts the stock ticker company as an argument and returns the XML output... phone column (which is of type XML) is added to the Parameters collection of the SqlCommand object SqlParameter paramPhone = new SqlParameter(“@Phone”, SqlDbType .Xml) ; paramPhone.Value = new SqlXml(new XmlTextReader(userInfo.Phone, XmlNodeType.Document, null)); command.Parameters.Add(paramPhone); You specify the type of the column as XML by passing in the enumeration SqlDbType .Xml to the second parameter... transform.Load(xslPath); StringWriter writer = new StringWriter(); transform.Transform(xmlDoc, null, writer); return writer.ToString(); } bool IsInputXmlValid(string xml) { TextReader textReader = new StringReader (xml) ; string xsdPath = Request.PhysicalApplicationPath + @”\App_Data\SearchInput.xsd”; XmlReader reader = null; XmlReaderSettings settings = new XmlReaderSettings(); settings.ValidationEventHandler += new ValidationEventHandler(this.ValidationEventHandler);... page uses this feature to search for flights from the client side ASP.NET 2.0 script callback is a new feature introduced with ASP.NET 2.0 that enables you to invoke a remote function from the server side of a Web page without refreshing the browser This new feature builds on the foundation of the XmlHttp object library Using the ASP.NET 2.0 script callback feature, you can emulate some of the behaviors... arrivalDate, 1); return TransformXmltoHtml(flights.GetXml()); } If the input XML is valid, you then parse the contents of the XML into local variables and pass them as arguments to the SearchFlight() method of the FlightDB class The SearchFlight() method returns a DataSet object, which is then converted to an XML format and passed to a helper method named TransformXmlToHtml() The TransformXmlToHtml() method is . 13_59 67 72 ch 10. qxd 12/ 13 /05 11:19 PM Page 334 Building an Airline Reservation System Using ASP. NET 2. 0 and SQL Server 20 05 So far in this book, you have learned about XML DOM, XML support. 11 14_59 67 72 ch11.qxd 12/ 13 /05 11:19 PM Page 3 50 < ;asp: Table id=”tblTop” BackColor=”Red” runat=”server” Width=”819px” Height=” 108 px” ForeColor=”blue”> < ;asp: TableRow runat=”server”> < ;asp: TableCell. Site Browser AirlineReservation Web Site Data Access Layer Internet SQL Server 20 05 Database 336 Chapter 11 14_59 67 72 ch11.qxd 12/ 13 /05 11:19 PM Page 336 choosing the best approach. The business

Ngày đăng: 12/08/2014, 23:22

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan