ASP.NET 2.0 Everyday Apps For Dummies (2006)
.pdfChapter 6: Building a Shopping Cart Application 197
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 routines 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)
198 Part III: Building E-Commerce Applications
Listing 6-14 (continued)
Private _email As String
Public Sub New()
End Sub
Public Sub New(ByVal lastName As String, _
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 Get
Return _lastName End Get
Set(ByVal value As String) _lastName = value
End Set End Property
Public Property FirstName() As String Get
Return _firstName End Get
Set(ByVal value As String) _firstName = value
End Set End Property
Public Property Address() As String Get
Return _address End Get
Set(ByVal value As String) _address = value
End Set End Property
Public Property City() As String
Get
2
3
4
5
6
7
Chapter 6: Building a Shopping Cart Application 199
Return _city End Get
Set(ByVal value As String) _city = value
End Set End Property
Public Property State() As String Get
Return _state End Get
Set(ByVal value As String) _state = value
End Set End Property
Public Property ZipCode() As String Get
Return _zipCode End Get
Set(ByVal value As String) _zipCode = value
End Set End Property
Public Property Email() As String Get
Return _email End Get
Set(ByVal value As String) _email = value
End Set End Property
Public Property PhoneNumber() As String Get
Return _phoneNumber End Get
Set(ByVal value As String) _phoneNumber = value
End Set End Property
8
9
10
11
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 version is shown in Listing 6-16.
200 Part III: Building E-Commerce Applications
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;
public ShoppingCart()
{
_cart = new List<CartItem>();
}
public List<CartItem> GetItems()
{
return _cart;
}
public void AddItem(string id, string name, 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, int quantity)
{
CartItem item = _cart[index]; item.Quantity = quantity;
1
2
3
4
5
Chapter 6: Building a Shopping Cart Application 201
} |
|
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 variable 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 specified 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.
202 Part III: Building E-Commerce Applications
Listing 6-16: The ShoppingCart class (VB version)
Imports Microsoft.VisualBasic
Imports System.Collections.Generic
Public Class ShoppingCart
Private _cart As List(Of CartItem)
Public Sub New()
_cart = New List(Of CartItem)()
End Sub
Public Function GetItems() As List(Of CartItem)
Return _cart
End Function
Public Sub AddItem(ByVal id As String, _ 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( _ 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) _cart.RemoveAt(index)
End Sub
Public ReadOnly Property Count() As Integer
Get
Return _cart.Count
End Get
End Property
1
2
3
4
5
6
7
End Class
Chapter 6: Building a Shopping Cart Application 203
Using Generics
Generics is a new feature of both the C# and the Visual Basic programming languages. The purpose of the Generics feature is to prevent a common problem when dealing with .NET collection 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 keyword to indicate the generic type.
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.
204 Part III: Building E-Commerce Applications
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; private string _name; private decimal _price; private int _quantity;
public CartItem()
{
this.ID = “”; this.Name = “”; this.Price = 0.0m; this.Quantity = 0;
}
public CartItem(string id, string name, decimal price, int quantity)
{
this.ID = id; this.Name = name; this.Price = price;
this.Quantity = quantity;
}
public string ID
{
get
{
return _id;
}
set
{
_id = value;
}
}
public string Name
{
get
{
return _name;
1
2
3
4
5
Chapter 6: Building a Shopping Cart Application 205
}
set
{
_name = value;
}
}
public decimal Price
{
get
{
return _price;
}
set
{
_price = value;
}
}
public int Quantity
{
get
{
return _quantity;
}
set
{
_quantity = value;
}
}
public decimal Total
{
get
{
return _price * _quantity;
}
}
}
6
7
8
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.
206 Part III: Building E-Commerce Applications
5 The Name property represents the name of the product referred to by the cart item. It uses the private instance variable name.
6 The Price property represents the price of the product. It uses the _price variable to store its value.
7 The Quantity property records the quantity for the cart item. It stores its value in the _quantity variable.
8 The Total property returns the value Price property multiplied by the Quantity property. Notice that this property’s value isn’t stored in an instance variable. Instead, the value is recalculated each time it is accessed.
Listing 6-18: The CartItem class (VB version)
Imports Microsoft.VisualBasic
Public Class CartItem
Private _id As String
Private _name As String
Private _price As Decimal
Private _quantity As Integer
Public Sub New()
Me.ID = “”
Me.Name = “”
Me.Price = 0.0
Me.Quantity = 0
End Sub
Public Sub New(ByVal id As String, _ ByVal name As String, _ ByVal price As Decimal, _ ByVal quantity As Integer)
Me.ID = id Me.Name = name Me.Price = price
Me.Quantity = quantity End Sub
Public Property ID() As String Get
Return _id End Get
Set(ByVal value As String) _id = value
End Set End Property
Public Property Name() As String
Get
Return _name
1
2
3
4
5