ASP.NET 2.0 Everyday Apps For Dumies 2006 phần 6 docx

43 270 0
ASP.NET 2.0 Everyday Apps For Dumies 2006 phần 6 docx

Đ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

Listing 6-13 (continued) return _state; } set { _state = value; } } public string ZipCode ➝ 9 { get { return _zipCode; } set { _zipCode = value; } } public string Email ➝ 10 { get { return _email; } set { _email = value; } } public string PhoneNumber ➝ 11 { get { return _phoneNumber; } set { _phoneNumber = value; } } } The following paragraphs define each component of this class: ➝ 1 The class begins by defining private instance variables that are used to hold the values associated with the class properties. By convention, each of these variable names begins with an 196 Part III: Building E-Commerce Applications 12_597760 ch06.qxp 1/11/06 9:56 PM Page 196 underscore to indicate that it corresponds to a property with the same name. ➝ 2 The default constructor creates a Customer object with default values for each of its properties. ➝ 3 This constructor accepts arguments that initialize the customer data. Notice that the assignment statements don’t directly assign values to the instance variables of the class. Instead, they use the properties to assign these values. That way, any validation rou- tines written in the property setters will be used. (In this example, none of the property setters have validation routines. Still, it’s a good practice to follow just in case.) ➝ 4 The LastName property represents the customer’s last name. Its get routine simply returns the value of the _lastName instance variable, and its set routine simply sets the _lastName variable to the value passed via the value argument. ➝ 5 The FirstName property represents the customer’s first name, which is stored in the _firstName instance variable. ➝ 6 The Address property represents the customer’s address, stored in the _address instance variable. ➝ 7 The City property represents the customer’s city, stored in the _city instance variable. ➝ 8 The State property represents the customer’s state, stored in the _state instance variable. ➝ 9 The ZipCode property represents the customer’s Zip code, stored in the _zipCode instance variable. ➝ 10 The Email property represents the customer’s e-mail address, stored in the _email instance variable. ➝ 11 The PhoneNumber property represents the customer’s phone number, stored in the _phoneNumber instance variable. Listing 6-14: The Customer class (VB version) Imports Microsoft.VisualBasic Public Class Customer Private _lastName As String ➝ 1 Private _firstName As String Private _address As String Private _city As String Private _state As String Private _zipCode As String Private _phoneNumber As String (continued) 197 Chapter 6: Building a Shopping Cart Application 12_597760 ch06.qxp 1/11/06 9:56 PM Page 197 Listing 6-14 (continued) Private _email As String Public Sub New() ➝ 2 End Sub Public Sub New(ByVal lastName As String, _ ➝ 3 ByVal firstName As String, _ ByVal address As String, _ ByVal city As String, _ ByVal state As String, _ ByVal zipCode As String, _ ByVal phoneNumber As String, _ ByVal email As String) Me.LastName = lastName Me.FirstName = firstName Me.Address = address Me.City = city Me.State = state Me.ZipCode = zipCode Me.PhoneNumber = phoneNumber Me.Email = email End Sub Public Property LastName() As String ➝ 4 Get Return _lastName End Get Set(ByVal value As String) _lastName = value End Set End Property Public Property FirstName() As String ➝ 5 Get Return _firstName End Get Set(ByVal value As String) _firstName = value End Set End Property Public Property Address() As String ➝ 6 Get Return _address End Get Set(ByVal value As String) _address = value End Set End Property Public Property City() As String ➝ 7 Get 198 Part III: Building E-Commerce Applications 12_597760 ch06.qxp 1/11/06 9:56 PM Page 198 Return _city End Get Set(ByVal value As String) _city = value End Set End Property Public Property State() As String ➝ 8 Get Return _state End Get Set(ByVal value As String) _state = value End Set End Property Public Property ZipCode() As String ➝ 9 Get Return _zipCode End Get Set(ByVal value As String) _zipCode = value End Set End Property Public Property Email() As String ➝ 10 Get Return _email End Get Set(ByVal value As String) _email = value End Set End Property Public Property PhoneNumber() As String ➝ 11 Get Return _phoneNumber End Get Set(ByVal value As String) _phoneNumber = value End Set End Property End Class Creating the ShoppingCart Class The ShoppingCart class represents the user’s virtual shopping cart, as described in detail earlier in this chapter (see Table 6-5). Now, Listing 6-15 presents the C# version of the ShoppingCart class, and the Visual Basic ver- sion is shown in Listing 6-16. 199 Chapter 6: Building a Shopping Cart Application 12_597760 ch06.qxp 1/11/06 9:56 PM Page 199 Listing 6-15: The ShoppingCart class (C# version) using System; using System.Data; using System.Configuration; 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; using System.Collections.Generic; public class ShoppingCart { private List<CartItem> _cart; ➝ 1 public ShoppingCart() ➝ 2 { _cart = new List<CartItem>(); } public List<CartItem> GetItems() ➝ 3 { return _cart; } public void AddItem(string id, string name, ➝ 4 decimal price) { bool itemFound = false; foreach (CartItem item in _cart) { if (item.ID == id) { item.Quantity += 1; itemFound = true; } } if (!itemFound) { CartItem item = new CartItem(id, name, price, 1); _cart.Add(item); } } public void UpdateQuantity(int index, ➝ 5 int quantity) { CartItem item = _cart[index]; item.Quantity = quantity; 200 Part III: Building E-Commerce Applications 12_597760 ch06.qxp 1/11/06 9:56 PM Page 200 } public void DeleteItem(int index) ➝ 6 { _cart.RemoveAt(index); } public int Count ➝ 7 { get { return _cart.Count; } } } The following paragraphs describe the important details of this class: ➝ 1 A private instance variable named _cart holds the contents of the shopping cart. This variable uses the new Generics feature to create a list object that can only hold objects of type CartItem. (For more information about generics, see the sidebar “Using Generics” later in this section.) To use the List class, you must provide an imports (C#) or Using (VB) statement that specifies the namespace System. Collections.Generic. ➝ 2 The constructor for this class creates an instance of the List class and assigns it to the _cart variable. ➝ 3 The GetItems method returns a List that contains CartItem objects. It simply returns the _cart variable. ➝ 4 The AddItem method adds an item to the shopping cart, using the product ID, name, and price values passed as parameters. It uses a for each loop to search the items in the cart. If one of the items already in the cart has a product ID that matches the ID passed as a parameter, that item’s quantity is incremented and a local vari- able named itemFound is set to true. If a matching item is not found by the for each loop, a new CartItem object is created with a quantity of 1. Then the new cart item is added to the list. ➝ 5 The UpdateQuantity method changes the quantity for a speci- fied product. It uses the index value passed as a parameter to access the cart item, then sets the item’s Quantity property to the value passed via the quantity parameter. ➝ 6 The DeleteItem method uses the RemoveAt method of the List class to remove the item at the index passed via the parameter. ➝ 7 The Count property simply returns the Count property of the _cart list. Notice that since this is a read-only property, no set routine is provided. 201 Chapter 6: Building a Shopping Cart Application 12_597760 ch06.qxp 1/11/06 9:56 PM Page 201 Listing 6-16: The ShoppingCart class (VB version) Imports Microsoft.VisualBasic Imports System.Collections.Generic Public Class ShoppingCart Private _cart As List(Of CartItem) ➝ 1 Public Sub New() ➝ 2 _cart = New List(Of CartItem)() End Sub Public Function GetItems() As List(Of CartItem) ➝ 3 Return _cart End Function Public Sub AddItem(ByVal id As String, _ ➝ 4 ByVal name As String, _ ByVal price As Decimal) Dim itemFound As Boolean = False For Each item As CartItem In _cart If item.ID = id Then item.Quantity += 1 itemFound = True End If Next If Not itemFound Then Dim item As CartItem item = New CartItem(id, name, price, 1) cart.Add(item) End If End Sub Public Sub UpdateQuantity( _ ➝ 5 ByVal index As Integer, ByVal quantity As Integer) Dim item As CartItem item = _cart(index) item.Quantity = quantity End Sub Public Sub DeleteItem(ByVal index As Integer) ➝ 6 _cart.RemoveAt(index) End Sub Public ReadOnly Property Count() As Integer ➝ 7 Get Return _cart.Count End Get End Property End Class 202 Part III: Building E-Commerce Applications 12_597760 ch06.qxp 1/11/06 9:56 PM Page 202 Creating the CartItem Class The CartItem class defines an item in the user’s shopping cart. The ShoppingCart class itself (presented in the previous section) is basically a list of CartItem objects. For a list of properties provided by the CartItem class, refer to Table 6-6. Listings 6-17 and 6-18 present the C# and Visual Basic versions of this class. 203 Chapter 6: Building a Shopping Cart Application Using Generics Generics is a new feature of both the C# and the Visual Basic programming languages. The pur- pose of the Generics feature is to prevent a common problem when dealing with .NET col- lection classes. Suppose you want to store a collection of Customer objects. You can do that by declaring an ArrayList object, then adding Customer objects to the array list. However, nothing prevents you from adding other types of objects to the array list. If you were careless, you could also add a ShoppingCart object to the array list. With the new Generics feature, you can create collections that are designed to hold only objects of a specified type. For example, you can create a list that can hold only Customer objects. Then, if you try to add a ShoppingCart object to the list by accident, an exception will be thrown. Along with the Generics feature comes a new namespace (System.Collections. Generic) with a set of collection classes that are designed to work with the Generics feature. Here are the classes you’ll probably use most: ߜ List: A generic array list. ߜ SortedList: A generic list that’s kept in sorted order. ߜ LinkedList: A generic linked list. ߜ Stack: A generic last-in, first-out stack. ߜ Queue: A generic first-in, first-out queue. ߜ Dictionary: A generic collection of key/value pairs. ߜ SortedDictionary: A generic collection of key/value pairs kept in sorted order. The syntax for using the Generics feature takes a little getting used to. Here’s a C# example that defines a variable of type List whose objects are Customer types, then creates an instance of the list and assigns it to the variable: List<Customer> custlist; custlist = new List<Customer>(); Notice how the generic type is enclosed in greater-than and less-than symbols. Here’s the same example in Visual Basic: Dim custlist As List(Of Customer) custlist = New List(Of Customer)() As you can see, Visual Basic uses the Of key- word to indicate the generic type. 12_597760 ch06.qxp 1/11/06 9:56 PM Page 203 Listing 6-17: The CartItem class (C# version) using System; using System.Data; using System.Configuration; 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 class CartItem { private string _id; ➝ 1 private string _name; private decimal _price; private int _quantity; public CartItem() ➝ 2 { this.ID = “”; this.Name = “”; this.Price = 0.0m; this.Quantity = 0; } public CartItem(string id, string name, ➝ 3 decimal price, int quantity) { this.ID = id; this.Name = name; this.Price = price; this.Quantity = quantity; } public string ID ➝ 4 { get { return _id; } set { _id = value; } } public string Name ➝ 5 { get { return _name; 204 Part III: Building E-Commerce Applications 12_597760 ch06.qxp 1/11/06 9:56 PM Page 204 } set { _name = value; } } public decimal Price ➝ 6 { get { return _price; } set { _price = value; } } public int Quantity ➝ 7 { get { return _quantity; } set { _quantity = value; } } public decimal Total ➝ 8 { get { return _price * _quantity; } } } Here are the key points to take note of in these listings: ➝ 1 The private instance variables _id, _name, _price, and _quantity hold the values for the cart item’s properties. ➝ 2 The first constructor, which has no parameters, simply initializes the class properties to default values. ➝ 3 The second constructor lets you create a CartItem object and set the ID, Name, Price, and Quantity properties at the same time. ➝ 4 The ID property provides the ID of the product referred to by the cart item. It uses the private instance variable id to store its value. 205 Chapter 6: Building a Shopping Cart Application 12_597760 ch06.qxp 1/11/06 9:56 PM Page 205 [...]... Select link is shown for each product ߜ To the right of the GridView control is a FormsView control that displays the data for the selected product The FormsView control — a new control introduced with ASP.NET 2.0 — makes it easy to display and update data for a single row of a data source ߜ When the Product Maintenance page is first displayed — and no product has yet been selected — the FormsView control... text boxes in the FormView control is followed by a RequiredFieldValidator That way, the user must enter data for each field ߜ Unlike the GridView control, the FormView control does allow for insertions If the user clicks New, the FormView control enters Insert mode, as shown in Figure 7-7 Then the user can enter the data for a new product and click Insert to insert the row Figure 7 -6: The Product Maintenance... the Select link for one of the products displayed by the GridView control Figure 7-5: The Product Maintenance page 227 228 Part IV: Building Back-End Applications ߜ The user can edit the data for the selected product by clicking the Edit link at the bottom of the FormView control This places the FormView control into Edit mode, as shown in Figure 7 -6 Then the user can change the data for the product... and properties of this class appear back in Table 6- 7; Listings 6- 19 and 6- 20 provide the C# and Visual Basic versions of this class Listing 6- 19: using using using using using The Order class (C# version) System; System.Data; System.Configuration; System.Web; System.Web.Security; (continued) 207 208 Part III: Building E-Commerce Applications Listing 6- 19 (continued) using using using using System.Web.UI;... property that returns the total for the items in the order’s shopping cart It uses a for each loop to calculate this value by adding up the Total property for each item in the shopping cart Notice that the cart’s GetItems method is called to retrieve the items ➝8 The SalesTax property is a read-only property that calculates the sales tax If the customer lives in California, the tax is calculated at... write an order to the database However, several private methods are required to support this method The C# version of this class is shown in Listing 6- 21, and Listing 6- 22 shows the Visual Basic version Chapter 6: Building a Shopping Cart Application Listing 6- 21: using using using using using using using using using using using The OrderDB class (C# version) System; System.Data; System.Configuration;... item.Quantity); cmd.ExecuteNonQuery(); } 6 } The following list spells out the most important details of this class: ➝1 The C# version of the OrderDB class is defined with the static keyword That simply means that the class can’t contain any instance properties or members Instead, all methods and properties must be declared as static That’s a new feature of C# for ASP.NET 2.0 Visual Basic doesn’t have this... avoids the need for query strings, session states, or other similar features There are a few additional considerations to think about whenever you create a maintenance application such as this one For example, try these on for size: ߜ How will the user look up the data to be updated? In this application, a GridView control is used to display the Categories and Products tables That’s feasible for this application... change the primary key fields? If you do, you must ensure that foreign key constraints are properly handled For example, if you allow a user to change the category ID for a category, how will you handle products assigned to that category? You have three possible approaches: • Cascade the update, so the category IDs change automatically for any related products • Don’t allow the category ID to be changed... customer data into the Customers table, calls the InsertOrder method to insert a row into the Orders table, and uses a for each loop to call the InsertItem method once for each item in the order’s shopping cart Notice that the InsertOrder method returns the order number generated for the order This value is then passed to the InsertItem method so the order items will be associated with the correct . shown in Listing 6 -21 , and Listing 6 -22 shows the Visual Basic version. 21 2 Part III: Building E-Commerce Applications 12_ 5977 60 ch 06. qxp 1/11 / 06 9: 56 PM Page 21 2 Listing 6 -21 : The OrderDB class. read-only property, no set routine is provided. 20 1 Chapter 6: Building a Shopping Cart Application 12_ 5977 60 ch 06. qxp 1/11 / 06 9: 56 PM Page 20 1 Listing 6- 16: The ShoppingCart class (VB version) Imports. _cart[index]; item.Quantity = quantity; 20 0 Part III: Building E-Commerce Applications 12_ 5977 60 ch 06. qxp 1/11 / 06 9: 56 PM Page 20 0 } public void DeleteItem(int index) ➝ 6 { _cart.RemoveAt(index); } public

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

Từ khóa liên quan

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

Tài liệu liên quan