ASP.NET 2.0 Everyday Apps For Dumies 2006 phần 5 pot

35 459 0
ASP.NET 2.0 Everyday Apps For Dumies 2006 phần 5 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

data into another table that also has an identity column. In that case, the @@IDENTITY function returns the identity value for the second table. Fortu- nately, the Cart database doesn’t use triggers, so the @@IDENTITY function will correctly return the identity value generated by the Orders table. Connecting to the database The connection string used to access the Cart database is stored in the application’s web.config file, like this: <connectionStrings> <add name=”ConnectionString” connectionString=”Data Source=localhost\SQLExpress; Initial Catalog=Cart;Integrated Security=True”/> </connectionStrings> The only place in the application that references this connection string is here in the web.config file. This makes it easy to relocate the database when you put the application into production. The Application’s Folders The Shopping Cart application includes the following folders: ߜ (Root): The application’s root folder contains the application’s six pages (Default.aspx, Product.aspx, Cart.aspx, CheckOut.aspx, and Completed.aspx) as well as the Master Page (Default.master). ߜ App_Data: This folder is designed to store databases used by the applica- tion. However, this particular application uses a database that’s stored in a location that’s determined by SQL Server. So the database for our Cart isn’t actually stored in this folder. (If you use the script presented in Listing 6-1 to create the database, the database file is stored in C:\Apps.) ߜ App_Code: This folder contains the C# or Visual Basic code files that define the classes used by the application. For more information about these classes, see the section “Designing the Classes” later in this chapter. ߜ Images: Here, you’ll find the banner image displayed by the Master Page and the image files that show pictures of the store’s products. 161 Chapter 6: Building a Shopping Cart Application 12_597760 ch06.qxp 1/11/06 9:55 PM Page 161 Designing the Classes Unlike most of the other applications presented in this book, the Shopping Cart application depends on several classes that both define the business objects used by the program as well as provide the database access. In par- ticular, the application uses the following classes: ߜ Customer: Represents a single customer. ߜ ShoppingCart: Represents the user’s shopping cart. ߜ CartItem: Represents an item in the user’s shopping cart. ߜ Order: Represents an order. ߜ OrderDB: Handles the details of writing an order to the database. The following sections describe each of these classes in detail. The Customer class The Customer class represents a single customer. Its constructors and prop- erties are spelled out in Table 6-4. Table 6-4 The Customer Class Constructor Description Customer() Creates an instance of the Customer class with default property values. Customer(string lastName, Creates an instance of the Customer string firstName, string class with the specified property values. address, string city, string state, string zipCode, string phoneNumber, string email) Property Description string LastName The customer’s last name. string FirstName The customer’s first name. 162 Part III: Building E-Commerce Applications 12_597760 ch06.qxp 1/11/06 9:55 PM Page 162 Property Description string Address The customer’s street address. string City The customer’s city. string State The customer’s state. string zipCode The customer’s Zip code. string phoneNumber The customer’s phone number. string email The customer’s e-mail address. The ShoppingCart class The ShoppingCart class represents a user’s shopping cart. Its constructors, properties, and methods are listed in Table 6-5. Table 6-5 The ShoppingCart class Constructor Description ShoppingCart() Creates a new shopping cart with no items. Property Description int Count The number of items in the shopping cart. Method Description List<CartItem> GetItems() Returns a List object that contains one CartItem object for each item in the shopping cart. void AddItem(string id, Adds a new item with the specified string name, decimal price) product ID, name, and price. void UpdateQuantity Updates the quantity at the specified (int index, int quantity) index. void DeleteItem(int index) Deletes the item at the specified index. string PhoneNumber The customer’s phone number. 163 Chapter 6: Building a Shopping Cart Application 12_597760 ch06.qxp 1/11/06 9:55 PM Page 163 The CartItem class The CartItem class represents an item in the user’s shopping cart. Its con- structors and properties are listed in Table 6-6. Table 6-6 The CartItem class Constructor Description CartItem() Creates a new CartItem object with default property values. CartItem(string ID, Creates a new CartItem object with string name, decimal the specified ID, name, price, and price, int quantity) quantity. Property Description string ID The Product ID for the product repre- sented by the item. string Name The product name. decimal Price The price per unit. int Quantity The quantity. decimal Total The total for the item (read-only). The Order class The Order class represents an order submitted by the user. Its constructors and properties are listed in Table 6-7. Table 6-7 The Order class Constructor Description Order () Creates a new Order object with default property values. Order (date OrderDate, Creates a new CartItem object with Customer cust, the specified order date, customer, and ShoppingCart cart) shopping cart. Property Description DateTime OrderDate The date the order was submitted. Customer Cust The customer who submitted the order. 164 Part III: Building E-Commerce Applications 12_597760 ch06.qxp 1/11/06 9:55 PM Page 164 Property Description ShoppingCart Cart The shopping cart that specifies the items being ordered. decimal SubTotal The subtotal, calculated by adding up the total for each item in the order’s shopping cart. decimal SalesTax The sales tax for the order (read-only). The sales tax is calculated as 7.75% of the subtotal if the Customer resides in California. Otherwise, the sales tax is zero. decimal Shipping The shipping charges for the order (read- only). The shipping charge is calculated as $2.00 per item. decimal Total The total for the order (read-only). The total is calculated by adding up the subtotal, sales tax, and shipping charges. The OrderDB class The OrderDB class handles the task of writing an order to the database. It consists of just a single static method (Shared for all you Visual Basic pro- grammers out there), as described in Table 6-8. Table 6-8 The OrderDB class Method Description static bool Writes the order to the Cart database. WriteOrder(Order o) Returns true if the order is successfully written; otherwise, returns false. The connection string for the database is obtained from the application’s web.config file. Building the Master page The Master Page (MasterPage.master) for the Shopping Cart application is shown in Listing 6-2. It’s similar to the Master Page that was used in the Product Listing application shown in Chapter 5. However, it includes an addi- tional label that displays information about the user’s shopping cart and a link that leads to the Cart page. 165 Chapter 6: Building a Shopping Cart Application 12_597760 ch06.qxp 1/11/06 9:55 PM Page 165 Listing 6-2: The Master Page (MasterPage.master) <%@ Master Language=”C#” ➝ 1 AutoEventWireup=”true” CodeFile=”MasterPage.master.cs” Inherits=”MasterPage” %> <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN” “http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”> <html xmlns=”http://www.w3.org/1999/xhtml” > <head runat=”server”> <title>Acme Pirate Supply</title> </head> <body> <form id=”form1” runat=”server”> <div> <img src=”Images/Banner.jpg” /> ➝ 2 <br /> <asp:Label ID=”lblCart” runat=”server” ➝ 3 Font-Size=”Small”/> &nbsp; <a href=”Cart.aspx” ➝ 4 style=”font-size: small”> Go To Cart</a> <br /><br /> <asp:contentplaceholder ➝ 5 id=”ContentPlaceHolder1” runat=”server”> </asp:contentplaceholder> </div> </form> </body> </html> The following paragraphs describe the key lines of the Master Page: ➝ 1 The Master directive identifies the file as a Master Page. ➝ 2 The Image control displays a banner image at the top of each page. The Banner.jpg file is stored in the Images folder. ➝ 3 The label that displays the number of items currently in the shop- ping cart. The text for this label is set in the Page_Load method. ➝ 4 The link that leads to the Cart page. ➝ 5 The ContentPlaceHolder control provides the area where the content for the application’s content pages will be displayed. The Master Page requires a code-behind file to set the Text property of the label. The C# version of this code-behind file is shown in Listing 6-3, and the Visual Basic version is shown in Listing 6-4. 166 Part III: Building E-Commerce Applications 12_597760 ch06.qxp 1/11/06 9:55 PM Page 166 Listing 6-3: The code-behind file for the Master Page (C#) using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class MasterPage : System.Web.UI.MasterPage { protected void Page_Load(object sender, EventArgs e) { ShoppingCart cart = (ShoppingCart)Session[“cart”]; if (cart == null) lblCart.Text = “Your shopping cart is empty.”; else if (cart.Count == 0) lblCart.Text = “Your shopping cart is empty.”; else if (cart.Count == 1) lblCart.Text = “You have 1 item in your shopping cart.”; else lblCart.Text = “You have “ + cart.Count.ToString() + “ items in your shopping cart.”; } } Listing 6-4: The code-behind file for the Master Page (VB) Partial Class MasterPage Inherits System.Web.UI.MasterPage Protected Sub Page_Load( _ ByVal sender As Object, _ ByVal e As System.EventArgs) _ Handles Me.Load Dim cart As ShoppingCart cart = Session(“cart”) If cart Is Nothing Then lblCart.Text = “Your shopping cart is empty.” ElseIf cart.Count = 0 Then lblCart.Text = “Your shopping cart is empty.” ElseIf cart.Count = 1 Then lblCart.Text = “You have 1 item in your shopping cart.” Else (continued) 167 Chapter 6: Building a Shopping Cart Application 12_597760 ch06.qxp 1/11/06 9:55 PM Page 167 Listing 6-4 (continued) lblCart.Text = “You have “ _ + cart.Count.ToString() _ + “ items in your shopping cart.” End If End Sub End Class As you can see, the code-behind file has just one method, named Page_Load, which is executed when the page is loaded. It retrieves the shopping cart from session state, casts it as a ShoppingCart object, then sets the label accordingly. If the cart doesn’t exist or is empty, the label is set to “Your shopping cart is empty.” If the cart contains exactly one item, the label is set to “You have 1 item in your shopping cart.” And if the cart has more than one item, the label is set to “You have n items in your shopping cart.” Modifying the Product Detail Page The Product Detail page (Product.aspx) is almost identical to the Product Detail page for the Product Catalog application shown in Chapter 5. However, there’s one crucial difference. In the Chapter 5 application, clicking the Add to Cart button simply led the user to a page that indicates that the shopping cart feature hasn’t yet been implemented. But in this application, clicking the Add to Cart button must actually add the product to the shopping cart, then redi- rect the user to the Cart.aspx page to see the contents of the shopping cart. To add this feature to the Product Detail page, you must modify the method that’s called when the user clicks the Add to Cart button, btnAdd_Click. The rest of the page is unchanged from the Chapter 5 application. Listing 6-5 shows the C# version of the btnAdd_Click method, the method that’s called when the user clicks the Add to Cart button. Listing 6-6 shows the Visual Basic version of this method. (To see the .aspx file for the Product Detail page, please refer back to Chapter 5.) Listing 6-5: The btnAdd_Click method (C#) protected void btnAdd_Click(object sender, EventArgs e) { // get values from data source ➝ 1 DataView dv = (DataView)SqlDataSource1.Select( DataSourceSelectArguments.Empty); DataRowView dr = dv[0]; string ID = (String)dr[“ProductID”]; string Name = (string)dr[“Name”]; 168 Part III: Building E-Commerce Applications 12_597760 ch06.qxp 1/11/06 9:55 PM Page 168 decimal Price; if (dr[“SalePrice”] is DBNull) Price = (decimal)dr[“Price”]; else Price = (decimal)dr[“SalePrice”]; // get or create shopping cart ➝ 2 ShoppingCart cart; if (Session[“cart”] == null) { cart = new ShoppingCart(); Session[“cart”] = cart; } else { cart = (ShoppingCart)Session[“cart”]; } // add item to cart ➝ 3 cart.AddItem(ID, Name, Price); // redirect to cart page ➝ 4 string ProductID = Request.QueryString[“prod”]; string CatID = Request.QueryString[“cat”]; Response.Redirect(“Cart.aspx?prod=” + ProductID + “&cat=” + CatID); } The following paragraphs describe the key points of this method: ➝ 1 The btnAdd_Click method begins by retrieving the ID, name, and price information for the current product from the data source. You’d think that it would be pretty easy to retrieve the product data displayed by the form, but it turns out to be a little tricky. The easiest technique is to use the Select method of the data source to retrieve a data view object that contains the data retrieved by the data source’s SELECT statement. Because the SELECT statement for this data source retrieves the data for a single product, the resulting data view will have just one row. The indexer for the DataView object lets you retrieve the individual rows of the data view. Thus, index 0 is used to retrieve a DataRowView object for the data view’s only row. Then the indi- vidual columns are retrieved from the DataRowView object using the column names as indexes. Note that if a SalePrice column is present, it is used instead of the Price column for the product’s price. ➝ 2 Once the product information has been retrieved from the data source, session state is checked to see if a shopping cart already exists. If so, the shopping cart is retrieved from session state. If not, the application creates a new shopping cart by calling the 169 Chapter 6: Building a Shopping Cart Application 12_597760 ch06.qxp 1/11/06 9:55 PM Page 169 ShoppingCart class constructor. Then the new shopping cart is added to session state under the name “cart.” ➝ 3 The AddItem method of the shopping cart is called to add the product to the shopping cart. ➝ 4 The user is redirected to the Cart.aspx page, with the product and category IDs passed on as query string fields. Listing 6-6: The btnAdd_Click method (VB) Protected Sub btnAdd_Click( _ ByVal sender As Object, _ ByVal e As System.EventArgs) _ Handles btnAdd.Click ‘ get values from data source ➝ 1 Dim dv As DataView dv = SqlDataSource1.Select( _ DataSourceSelectArguments.Empty) Dim dr As DataRowView = dv(0) Dim ID As String = dr(“ProductID”) Dim name As String = dr(“Name”) Dim Price As Decimal If TypeOf (dr(“SalePrice”)) Is DBNull Then Price = dr(“Price”) Else Price = dr(“SalePrice”) End If ‘ get or create shopping cart ➝ 2 Dim cart As ShoppingCart If Session(“cart”) Is Nothing Then cart = New ShoppingCart() Session(“cart”) = cart Else cart = Session(“cart”) End If ‘ add item to cart ➝ 3 cart.AddItem(ID, name, Price) ‘ redirect to cart page ➝ 4 Dim ProductID As String ProductID = Request.QueryString(“prod”) Dim CatID As String CatID = Request.QueryString(“cat”) Response.Redirect( _ “Cart.aspx?prod=” + ProductID _ + “&cat=” + CatID) End Sub 170 Part III: Building E-Commerce Applications 12_597760 ch06.qxp 1/11/06 9:55 PM Page 170 [...]... code-behind file for the Check Out page Mercifully, the code-behind file for the Check Out page is not nearly as long as the aspx file (or as long as the code-behind for the Cart page, for that matter) Listing 6-11 shows the C# version, and the Visual Basic version is shown in Listing 6-12 Listing 6-11: using using using using using using using using using using The code-behind file for the Check Out... returning to the product pages ➝10 The Check Out button lets the user proceed to the checkout page For the Visual Basic version of this application, you should remove the OnClick attribute for this control The code-behind file for the Cart page Listing 6-8 shows the C# version of the code-behind file for the Cart page, and Listing 6-9 shows the Visual Basic version 173 174 Part III: Building E-Commerce... the user enter the credit card number For an actual application, you’ll want to do more validation than a simple required-field validator provides In particular, you’ll want to make sure that the number entered conforms to the requirements for each credit card type (The requirements vary depending on card type; I’ll leave it to you to provide this validation.) ➝ 15 A label and drop-down list let the... displays a summary of the order and allows the user to submit the order for final processing The title of this step is “Confirmation.” ➝ 18 This label displays the order subtotal, obtained by adding the total for each item in the shopping cart ➝ 19 This label displays the sales tax for the order ➝ 20 This label displays the shipping charges for the order ➝ 21 This label displays the order total This is the... modifying it 5 The next column is bound to the Price field It uses a format string to display the price in currency format It too is read-only ➝6 Unlike the other columns in the GridView control, the Quantity column isn’t read-only As a result, the user can modify its contents when the row is placed into Edit mode ➝7 The Total column displays the item total (the price times the quantity) in currency format... section For now, just realize that this method forces the page to refresh if the user has come to the page by using the browser’s back button This approach prevents problems that can occur when the user backs up to a version of the page that shows a shopping cart with contents that differ from the shopping cart that’s stored in session state Assuming that the CheckTimeStamps method didn’t force the... credit card payment information And in the third step, the user confirms the order Once the order is confirmed, the Check Out page calls the InsertOrder method of the OrderDB class to actually write the order to the database The following sections present the aspx code for the Check Out page and the C# and VB code-behind files The CheckOut.aspx file Listing 6-10 shows the aspx code for the Check Out page... January... Building a Shopping Cart Application The Wizard Control The Wizard control is a new feature in ASP.NET 2.0 that makes it easy to create wizards that walk the user through a series of steps A wizard consists of one or more steps and navigation buttons that let the user move from step to step Only the content defined for the current step is displayed when the page containing a Wizard control is rendered ߜ... position in the element (For example, the first step declared is the start step.) Here’s a basic skeleton of a simple Wizard control with three steps: Content for step one goes here Content for step two goes here . Request.QueryString(“cat”) Response.Redirect( _ “Cart.aspx?prod=” + ProductID _ + “&cat=” + CatID) End Sub 1 70 Part III: Building E-Commerce Applications 12_ 59 77 60 ch06.qxp 1/11 /06 9 :55 PM Page 1 70 Building the Cart Page The. to the Cart page. 1 65 Chapter 6: Building a Shopping Cart Application 12_ 59 77 60 ch06.qxp 1/11 /06 9 :55 PM Page 1 65 Listing 6 -2: The Master Page (MasterPage.master) <%@ Master Language=”C#” ➝ 1 AutoEventWireup=”true”. name. string FirstName The customer’s first name. 1 62 Part III: Building E-Commerce Applications 12_ 59 77 60 ch06.qxp 1/11 /06 9 :55 PM Page 1 62 Property Description string Address The customer’s

Ngày đăng: 05/08/2014, 10:20

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

Tài liệu liên quan