Click here to Skip to main content
12,455,701 members (82,427 online)
Click here to Skip to main content
Add your own
alternative version

Stats

171.6K views
4.3K downloads
65 bookmarked
Posted

Generic Shopping Basket

, 28 Dec 2003 CPOL
Rate this:
Please Sign up or sign in to vote.
A generic shopping basket web control that should serve as a good starting point to roll your own, more advanced version.

Introduction

The web seems to be teeming with different shopping baskets and different ways (PHP, ASP, JScript..) to solve the problem. I thought it would be fun to write a generic shopping basket as a nice, standalone web control. To whole idea was to make a web control that includes as much "shopping basket logic" as possible so that it needed minimal coding to include in an existing or new ASP.NET project. One of my aims was also to keep the code relatively light so that the control could be used as a kind of introduction to developing controls in C# and maybe even as a tutorial on some very common .NET and C# techniques. The result turned out pretty good and I am certainly convinced that even beginning .NET programmers will be able to understand all of the code. Of course, there are many ways to change and improve some of the concepts in the web control. I will mention possible improvements in the relevant sections so you can use this control as a template to add new functionality that better suits your needs. There really is a whole lot of extra you can do with web controls but some of these are beyond the scope of the article. So let's start shopping...

Background

When I designed the control, I had to make certain decisions since "generic" certainly implies some kind of open design while at the same time introducing some kind of limited functionality. First of all, I did not want my control to use Viewstate to pass settings from page to page because I wanted a design that enabled a web designer to drop the basket on any webpage and have it display its content correctly. Now there are a couple of ways to do this but saving the basket in a session state looked like the best generic solution. Note that session state in .NET is not so evil anymore as it was in normal ASP. Session state can now easily be used in clustered web environments.

.NET gives me the option to serialize classes in a binary format or in an XML format. I decided to go the XML way because it would enable developers to read the basket content from session state (of course, you can also use the control to do that when you have it available on your ASP.NET page). I did not use built-in serialization because it has trouble handling private members and I prefer to roll my own serialization from time to time. Note that you can implement binary serialization if you want to make the basket session state smaller.

The second big decision was to use a composite control (a control that contains a host of other child .NET controls) but still handle a big part of the rendering myself. This results (according to MS) in a faster control but I really did it because I could see how the actual HTML was being spit out by the control. Of course, this also makes the look and feel of the control a bit easier to adapt. If you don't like the way it looks, just change the Render code. The host control logic made it a bit easier to catch events (with OnBubbleEvent), and the INamingContainer interface makes sure that children have unique IDs.

Using the code

Using this control should be pretty straightforward. Just add it as a web control to the VS2003 toolbar and drop it on an ASP.NET webpage. You should provide logic on your webpage to add products because there is no way the web control can know where these products come from. The main things you need to remember is that the control itself handles modifying quantities, removing products and emptying the basket. Also, the control provides a handler that you can use when the user pushes the Checkout button of the basket. The basket does not display any button when it is set to "disabled", so this state can be used to just display the content (on a checkout page, for example) of the basket. The basket saves all its information in session state, so you can use the basket on any page in your website and it will be able to read the content of the shopping basket of the logged on user. Here is some sample code that illustrates how you could use the control on an aspx.cs page.

protected GenericBasket.Basket Basket1;

// Events will be added in design mode or you can do it manually
// Example : this.Basket1.Checkout += new System.EventHandler(
// this.Page_Checkout);

private void Page_Checkout(object sender, System.EventArgs e)
{
  // disable the basket so that no buttons can be pressed
  Basket1.Enabled = false;
  // do some other stuff to checkout
  // add an item that includes the Shipping & Handling fee
  // I just add 10% of the total cost for demo purposes
  Basket1.Remove("SHIPPING");
  Basket1.Add("SHIPPING","+ Shipping & Handling",1,Basket1.TotalPrice/10);
}

private void Page_Load(object sender, System.EventArgs e)
{
  if (!IsPostBack)
  {
    // Add some products
    Basket1.Add("1","XBox",2,199);
    Basket1.Add("2","GameCube",1,99);
    Basket1.Add("3","PS2",1,199);
    Basket1.Add("4","Remove me",1,0);
    // and remove a product again
    Basket1.Remove("4");
    // of course you can also use the product class
    GenericBasket.Product newProduct = new GenericBasket.Product(
        "4","GameBoy Advance",1,140);
    Basket1.Add(newProduct );
    }
  }
}

The GenericBasket.Product class

The methods and properties that are public (i.e. that you can use on ASP.NET pages) have been kept to a minimum. The Product class, however, is made public so you can use it as a wrapper for most of your product manipulations. I have kept the Product class very basic because there are so many different properties that you could attach to a product and most of them are application specific. The design of the control assumes that you will get the product specific information (tax, location, stock....) yourself and do something with that on the checkout cycle.

Of course, you can easily add some more specific stuff to the Product class if you want the shopping basket to contain more business logic. The Product class implements the ICompareable interface. This interface provides sorting so we can easily sort an array of Product elements.

Getting information out of the basket

The basket supports (read-only) indexers and enumerators so it behaves very much like a normal array and/or collection. The following code is quite valid:

Response.Write(Basket1.Count.ToString());
Response.Write(" Items in Basket");
foreach (GenericBasket.Product itemProduct in Basket1)
{
  Reponse.Write("*");
  Response.Write(itemProduct.sName);
  Response.Write(" ");
}
// Get the product with ID "9"
if (Basket1["9"] != null)
  Response.Write("Product ID 9 found");
else
  Response.Write("Product ID 9 not found");

Implementing these was quite straightforward. The enumerator does not need a lot of code, basically you can just return the existing enumerator from the ArrayList member. Don't forget to add the IEnumerable interface to support enumerators. Likewise, supporting indexers was a breeze as well, with just some simple code to support an integer index and a string index like most .NET classes. Here is the code of one indexer, the string version is very similar:

public Product this [int index]   // Indexer declaration
{
  get
  {
    if (index >= 0 && index < m_aProducts.Count)
      return(m_aProducts[index] as Product);
    else
  return(null);
  }
}

Events

With event bubbling, the control can make sure some events "bubble" up to the parent control. In the case of our generic basket, I decided to bubble only two events to the top. To support event bubbling, you need to implement the INamingContainer interface.

public event EventHandler Checkout; // Event that is triggered 
  // when checkout button is pressed
public event EventHandler Changed;  // Event that happens when 
  // control changes *itself*

To correctly process all the commands that are fired by the control, you need to specify the CommandArgument attribute to all child controls that you create. For example, on a Button:

btnGeneric = new Button();
btnGeneric.Text = "Delete";
btnGeneric.CommandName = "Delete";
btnGeneric.CommandArgument = outputProduct.sID;
btnGeneric.CssClass = CssClass;
Controls.Add(btnGeneric);

And this can then result in a bubbled event processing method like this:

protected override bool OnBubbleEvent(object source, EventArgs e) 
{   
  bool handled = false;
  if (e is CommandEventArgs)
  {
    CommandEventArgs ce = (CommandEventArgs)e;
    if (ce.CommandName == "Delete")
    {
      Remove((string)ce.CommandArgument);                
      OnChanged(ce);
      handled = true;   
    }
  }
  return(handled);    
}

protected virtual void OnChanged (EventArgs e)
{
  if (Changed != null)
  {
    Changed(this,e);
  }
}

Composite control?

I chose to go the way of the composite control (as opposed to a control where I render all HTML elements myself and handle the postback results) because I think that .NET handles events fired from children fairly well and this results in easier code. Of course, a composite control is a bit slower and has some small pitfalls. If you really experience performance issues, you might have to completely redesign the control so that it takes care of its own rendering and support postback data processing (implement IPostBackDataHandler).

I did run into one serious problem. Apparently the .NET framework calls CreateChildControls before it processes the events fired by the child controls. This resulted in very weird behavior and wrong controls containing wrong information. The solution was quite simple (but not really satisfactory). I just added the CreateChildControls call in the PreRender event. Why not satisfactory? Well, if you step through the code with the debugger, you will see that CreateChildControls is now called twice. Not very sensitive performance-wise, is it? I have left this for now because I suspect there is a more elegant way of solving this problem.

Public methods

Here is a list of the methods you can use on the basket and a short description:

public System.Int32 Add ( GenericBasket.Product newProduct ); 
  // Add a new Product to the basket. Returns index at which 
  // the value has been added.
public System.Int32 Add ( System.String sProductID , 
    System.String sName , System.Int32 iQuantity, System.Single fPrice); 
     // Add a new product to the basket alternative version. 
     // Returns index at which the value has been added.
public Basket ( ); // Constructor, nothing interesting to 
    //say about this one ;)
public void Clear ( ); // Clears the content of the basket
public int Count [  get]; // The number of items in the basket
public string EmptyTitle [  get,  set ]; // The title of control 
   // when it is empty
public System.Collections.IEnumerator GetEnumerator ( ); 
    // returns an enumerator, used for implementing enumeration
public void Remove ( System.String sProductID ); // Removes a product 
   // from the basket based on product ID
public string SessionKey [  get]; // The "session key" that you 
  // can use to read the basket session information XML
public const GenericBasket.Product this [  get]; // Indexers, 
  // one takes int index and the other one takes a product ID string
public string Title [  get,  set ]; // The title of your basket 
   // (when there are items inside)
// New in version 1.1
public float TotalPrice [  get]; // Gets the total price of all items in basket
public System.Globalization.CultureInfo Culture [  get,  set ]; 
  // the Culture of the basket, this makes sure the 
  // basket can display price in correct format

Points of Interest

I must add that this is my first .NET contribution to CodeProject. I made the switch to .NET from C++ about a year ago (of course, I still use C++ a lot but mainly at home) and discovered quickly that the .NET framework is a vast new maze with different paths to solve different problems. During the writing of this control, I constantly found different approaches and before you start modifying this control, you should think about some new and better ways to improve on the design (it is a generic control after all).

  • You can use more advanced child controls (DataGrid, for example) to display the contents of the basket.
  • You could even bind the XML session data to the DataGrid. This would give you a very good looking basket with some nice DataGrid functionality.
  • Adding database saving/loading would also be good since visitors of your website might like it if their basket stays filled between visits. This can be implemented in the control or it can be exposed as an event to the parent (just like checkout).
  • The Product class is pretty basic and could be extended. What about an URL to the product page or maybe a link to a picture?
  • Some business logic could be incorporated. For example, automatically adding tax and/or shipping costs.
  • There is a lot that can be done with the layout that is pretty basic right now. Modifying styles with a CSS stylesheet is of course very doable, maybe you could add extra HTML class tags to some of the HTML elements in the Render method, or maybe you can give the control templated properties which allow a page developer to customize the UI for the control. Remember that the control, at the moment, propagates the CssClass attribute to all of the HTML elements. This gives you some layout control, but more might be needed.

If you decide to use a shopping basket on your website, I hope this article gave you some ideas and useful code. If anybody decides to improve the design, let me know so I can incorporate them in newer versions of the article. Have fun shopping!

History

  • Version 1.1:
    • Fixed a minor bug in the indexer.
    • Added price information.
    • Added culture information, so that the basket will know how to display price information.
    • Changed some variable names to make them more ".NET compliant".
  • Version 1.2
    • Fixed a small bug in the HTML output when basket was empty (the last TD tag was not closed).
    • Added some "&nbsp;" between table elements to make table look consistent.
    • Added [Browsable(false)] to some properties that shouldn't really appear in the Properties window.
    • Session key getter is now static so you can query basket session key info without creating basket instance.
    • Changed some TD tags into TH tags to allow better stylesheet layout control of basket.
    • Changed the basket table color in HTML output if no color was defined, to white/black.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Dirk Vandenheuvel
Architect
Belgium Belgium
No Biography provided

You may also be interested in...

Pro
Pro

Comments and Discussions

 
GeneralI dot err Pin
amirghaf23-Sep-08 22:49
memberamirghaf23-Sep-08 22:49 
GeneralFYI Maybe a help Pin
stixoffire21-May-08 23:21
memberstixoffire21-May-08 23:21 
Generalvb.net Pin
Nick-Belgium10-Oct-07 3:37
memberNick-Belgium10-Oct-07 3:37 
GeneralRe: vb.net Pin
Dirk Vandenheuvel10-Oct-07 5:06
memberDirk Vandenheuvel10-Oct-07 5:06 
Question[Message Deleted] Pin
Bigfellahull14-Sep-07 4:53
memberBigfellahull14-Sep-07 4:53 
AnswerRe: Removing Quantity Pin
Dirk Vandenheuvel14-Sep-07 5:23
memberDirk Vandenheuvel14-Sep-07 5:23 
GeneralReferencing the Basket Pin
JackSz13-Sep-07 9:15
memberJackSz13-Sep-07 9:15 
GeneralRe: Referencing the Basket Pin
Dirk Vandenheuvel14-Sep-07 5:06
memberDirk Vandenheuvel14-Sep-07 5:06 
QuestionVisual Studio 2005 Pin
Nick-Belgium31-Jul-07 2:56
memberNick-Belgium31-Jul-07 2:56 
AnswerRe: Visual Studio 2005 Pin
Dirk Vandenheuvel31-Jul-07 2:58
memberDirk Vandenheuvel31-Jul-07 2:58 
GeneralRe: Visual Studio 2005 Pin
Nick-Belgium31-Jul-07 3:10
memberNick-Belgium31-Jul-07 3:10 
GeneralRe: Visual Studio 2005 Pin
Dirk Vandenheuvel1-Aug-07 3:27
memberDirk Vandenheuvel1-Aug-07 3:27 
GeneralIntegrate w/ Payment Processing Pin
everman18-Apr-07 4:59
membereverman18-Apr-07 4:59 
Generalunable to run the pgm Pin
reddyamar_uk19-Jan-07 6:17
memberreddyamar_uk19-Jan-07 6:17 
GeneralRe: unable to run the pgm Pin
Dirk Vandenheuvel22-Jan-07 2:44
memberDirk Vandenheuvel22-Jan-07 2:44 
GeneralRe: unable to run the pgm Pin
reddyamar_uk24-Jan-07 5:26
memberreddyamar_uk24-Jan-07 5:26 
GeneralRe: unable to run the pgm Pin
Shyam Bharath18-May-07 20:21
memberShyam Bharath18-May-07 20:21 
QuestionColor and Size & Gift Wrap Option Pin
uswebpro25-Jan-07 7:58
memberuswebpro25-Jan-07 7:58 
GeneralAwsome control Pin
Koen_V7-Nov-06 4:56
memberKoen_V7-Nov-06 4:56 
QuestionCan I Add to Basket even when Control is not on the page? Pin
nattyBoy21-Aug-06 4:34
membernattyBoy21-Aug-06 4:34 
AnswerRe: Can I Add to Basket even when Control is not on the page? Pin
Dirk Vandenheuvel21-Aug-06 4:44
memberDirk Vandenheuvel21-Aug-06 4:44 
GeneralRe: Can I Add to Basket even when Control is not on the page? Pin
nattyBoy21-Aug-06 5:00
membernattyBoy21-Aug-06 5:00 
GeneralRe: Can I Add to Basket even when Control is not on the page? [modified] Pin
Dirk Vandenheuvel21-Aug-06 5:08
memberDirk Vandenheuvel21-Aug-06 5:08 
GeneralRe: Can I Add to Basket even when Control is not on the page? Pin
nattyBoy22-Aug-06 0:04
membernattyBoy22-Aug-06 0:04 
GeneralRe: Can I Add to Basket even when Control is not on the page? [modified] Pin
Dirk Vandenheuvel22-Aug-06 0:17
memberDirk Vandenheuvel22-Aug-06 0:17 
GeneralRe: Can I Add to Basket even when Control is not on the page? Pin
nattyBoy4-Sep-06 4:50
membernattyBoy4-Sep-06 4:50 
AnswerRe: Can I Add to Basket even when Control is not on the page? Pin
Dirk Vandenheuvel7-Nov-06 5:00
memberDirk Vandenheuvel7-Nov-06 5:00 
QuestionAdding Customization Pin
cbertolasio3-Dec-05 5:06
membercbertolasio3-Dec-05 5:06 
AnswerRe: Adding Customization Pin
Dirk Vandenheuvel5-Dec-05 22:29
memberDirk Vandenheuvel5-Dec-05 22:29 
GeneralRe: Adding Customization Pin
cbertolasio6-Dec-05 2:49
membercbertolasio6-Dec-05 2:49 
GeneralRe: Adding Customization Pin
Dirk Vandenheuvel6-Dec-05 3:56
memberDirk Vandenheuvel6-Dec-05 3:56 
GeneralRe: Adding Customization Pin
cbertolasio6-Dec-05 4:07
membercbertolasio6-Dec-05 4:07 
GeneralRe: Adding Customization Pin
Dirk Vandenheuvel12-Dec-05 2:32
memberDirk Vandenheuvel12-Dec-05 2:32 
Generaltrying to use it on my website as session object Pin
hm_kamae8-Jun-05 6:42
memberhm_kamae8-Jun-05 6:42 
GeneralRe: trying to use it on my website as session object Pin
Dirk Vandenheuvel12-Jun-05 23:38
memberDirk Vandenheuvel12-Jun-05 23:38 
GeneralRe: trying to use it on my website as session object [modified] Pin
Anthony_Yio19-Jun-06 17:06
memberAnthony_Yio19-Jun-06 17:06 
GeneralRe: Basket Sorting Pin
Dirk Vandenheuvel23-Apr-04 3:18
memberDirk Vandenheuvel23-Apr-04 3:18 
GeneralRe: Basket Sorting Pin
Bryan Paijit26-Apr-04 11:50
memberBryan Paijit26-Apr-04 11:50 
GeneralRe: Basket Sorting Pin
Dirk Vandenheuvel26-Apr-04 11:57
memberDirk Vandenheuvel26-Apr-04 11:57 
GeneralCut n Paste Merchant......... Pin
bertsamo30-Jan-04 7:05
memberbertsamo30-Jan-04 7:05 
GeneralRe: Cut n Paste Merchant......... Pin
Dirk Vandenheuvel2-Feb-04 23:14
memberDirk Vandenheuvel2-Feb-04 23:14 
GeneralRe: Cut n Paste Merchant......... Pin
Anonymous4-Feb-04 2:27
sussAnonymous4-Feb-04 2:27 
GeneralRe: Cut n Paste Merchant......... Pin
Happylady22-Jul-05 17:37
memberHappylady22-Jul-05 17:37 
GeneralRe: Cut n Paste Merchant......... Pin
Dirk Vandenheuvel22-Jul-05 22:27
memberDirk Vandenheuvel22-Jul-05 22:27 
GeneralVAT/Sales Tax Pin
Bill Seddon28-Dec-03 22:53
memberBill Seddon28-Dec-03 22:53 
GeneralRe: VAT/Sales Tax Pin
Dirk Vandenheuvel30-Dec-03 1:19
memberDirk Vandenheuvel30-Dec-03 1:19 
GeneralRe: VAT/Sales Tax Pin
Bill Seddon30-Dec-03 1:53
memberBill Seddon30-Dec-03 1:53 
GeneralRe: VAT/Sales Tax Pin
Dirk Vandenheuvel30-Dec-03 2:06
memberDirk Vandenheuvel30-Dec-03 2:06 
GeneralRe: VAT/Sales Tax Pin
Bill Seddon30-Dec-03 2:36
memberBill Seddon30-Dec-03 2:36 
GeneralRe: VAT/Sales Tax Pin
Rocky Moore30-Dec-03 7:23
memberRocky Moore30-Dec-03 7:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.160826.1 | Last Updated 29 Dec 2003
Article Copyright 2003 by Dirk Vandenheuvel
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid