asp tutorials, asp.net tutorials, sample code, and Microsoft news from 15Seconds
Data Access  |   Troubleshooting  |   Security  |   Performance  |   ADSI  |   Upload  |   Email  |   Control Building  |   Component Building  |   Forms  |   XML  |   Web Services  |   ASP.NET  |   .NET Features  |   .NET 2.0  |   App Development  |   App Architecture  |   IIS  |   Wireless
 
Pioneering Active Server
 Power Search





Active News
15 Seconds Weekly Newsletter
• Complete Coverage
• Site Updates
• Upcoming Features

More Free Newsletters
Reference
News
Articles
Archive
Writers
Code Samples
Components
Tools
FAQ
Feedback
Books
Links
DL Archives
Community
Messageboard
List Servers
Mailing List
WebHosts
Consultants
Tech Jobs
15 Seconds
Home
Site Map
Press
Legal
Privacy Policy
internet.commerce














internet.com
IT
Developer
Internet News
Small Business
Personal Technology

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers

HardwareCentral
Compare products, prices, and stores at Hardware Central!

Create a Fully Functional, Multifeatured ASP Shopping Basket
By Manny Agrinya
Rating: 3.9 out of 5
Rate this article


  • email this article to a colleague
  • suggest an article

    Introduction


    For an e-commerce Web site, a shopping basket is a crucial part of the equation. Having a fully functional and easy-to-use shopping basket can be the difference between a shopper completing his or her visit with a purchase from your site, or simply adding to the list of abandoned baskets on the Internet. The days of the HTML form as shopping basket are long gone; your shoppers expect more. ISPs and business owners know this, and that is why, today, most ISPs will charge an extra fee to add a shopping cart to your hosted Web site. This article shows how to create your own shopping cart relatively easily.

    This article uses the terms "shopping cart" and "shopping basket" interchangeably. Also, to define "shopping cart," I am referring to the aspect of the Web site that allows shoppers to enter products and modify them in their cart. This does not include the checkout process, which in many cases includes on-line credit-card verification and billing procedures.

    The Problem

    If an ISP hosts your e-commerce site, your shopping cart options have traditionally been limited to:

    1. Paying extra each month for an ISP-provided shopping cart program such as Express Technologies' CartExpress.
    2. Purchasing a commercially available third-party shopping cart program (usually a DLL) and paying your ISP to install it on a dedicated server, or
    3. Using a HTML form to collect shoppers' desired products and orders.
    In each of these cases, you either have an added expense to your hosting fees, or you have a less than optimal order-collection system.

    The Solution

    Creating a shopping cart application with all the functionality of the commercial options, plus more, is relatively painless. Give your shoppers the ability to create and save different baskets for future reuse, for example. You will get a solution that can scale to meet the demands of all but the most traffic-heavy sites on the Web. All of these use features that come standard with most hosting plans today: ASP, SQL Server, and Open Database Connectivity (ODBC).

    Required software

    To create this basket application, the following software needs to be in place: MS SQL Server 7.0 or higher, IIS 4.0 or higher, and ADO 2.0 or higher. (Download complete source code for this article)

    Overview of the Shopping Basket

    The shopping basket is composed of two SQL tables that store the basket data, stored procedures that interact with the tables to insert, retrieve, or modify data in them (the back end), and three ASP pages on the Web server (the front end) that simply contain logic to make the database calls. In-depth analyses of these layers follow below.

    Back-end (Database) Design

    Tables
    At its core, every shopping cart program is made up of a series of calls to the database to save, retrieve, or modify data. Our shopping cart is no different. The database diagram for the tables is shown below.


    Figure 1: Database diagram for the shopping cart.

    The guiding principle for the above design was to make the shopping cart as extensible as possible, as well as to have the database do as much of the housekeeping as possible. It is amazing how many database designers neglect to fully take advantage of the built-in capabilities of their Relational Database Management Systems (RDBMSes) to minimize data manipulation errors. This design takes advantage of SQL Server's ability to enforce referential integrity, constraints, identity columns, etc, freeing the developer to worry only about shopper-specific issues.

    It is advisable to have at least two tables that comprise your shopping cart - as opposed to having one, wide, un-normalized table. This allows you to better enforce normalization in your design by not repeating data. It also allows you more room for extensibility of the shopping cart.

    Some things that should stand out from the design above:

    • The shopper_id column is not set as a primary key, or a unique identifier. This allows a shopper to have more than one basket at any time. Which basket is displayed is determined by the default_basket column, which has a bit data type (meaning it only allows 1 or 0). I chose to use a bit data type to conserve server resources, but a tiny int data type would suffice.
    • The primary key is set on the basket_id column and is foreign-keyed in the basket_detail table to ensure referential integrity. The basket_id column is also an identity column in the basket table with a default value of 1000 that is incremented by 1 for each new basket created.
    • The basket_detail table has a composite primary key using the basket_id and sku columns. (A composite key is a key created by using more than one column in a table). The reason we want a composite key is to enforce the requirement that no one basket can contain more than one row of the same product (sku).
    • The date_created and date_modified columns in the basket table are a good design practice because they not only tell you when the basket was created, but when a shopper last modified his basket content. This can be an excellent audit trail that opens opportunities to add new date-sensitive features to the shopping cart (like sending e-mail reminders to shoppers whose baskets have not been touched for one week, etc...).
    The SQL script for creating the described tables is shown below.


    Figure 2: SQL script for creating shopping basket tables.

    Stored Procedures

    The shopping basket is composed of nine stored procedures. Five of these are considered crucial to the core basket functionality, while the remaining four allow the added multiple-basket functionality.

    I cannot explicitly type out the code for each of them here, so I will follow this paragraph with their names, a brief discussion of what they accomplish, and what they return to the caller. Each of these has been scripted out and is part of the download file for this article.

    Sproc_addToBasket:
    This stored procedure (SP) adds a new product to the shopper's default basket. A return code of 0 means success, while 1 signifies an error in the operation.

    Sproc_createBasket:
    This SP checks to see if a shopper has an existing default basket. If none exists, it creates one and returns the basket id (which must be greater than 1,000) to the calling procedure. This SP is called only by the SP sproc_addToBasket before the product add operation happens. A return code of 1 implies an error.

    Sproc_getBasket:
    This SP returns a recordset of the shopper's default basket for display on the browser.

    Sproc_deleteBasket:
    This SP is responsible for deleting the shopper's entire specified basket. It returns 0 for success and 1 for failure. Note that this SP uses a transaction. The reason for this is simple - you want to minimize data corruption by ensuring that either all the basket information is deleted from both the basket and basket_detail tables, or nothing happens.

    Sproc_updateBasket:
    This SP updates the shopper's default basket to register any quantity changes, etc. It returns 0 for success or 1 for error.

    The SPs that follow are part of the added basket functionality and are considered noncritical. That is, the core basket functionality would be intact if they were not available.

    Sproc_getSavedBaskets:
    This SP returns a recordset of all of the shopper's saved baskets to display on the browser.

    Sproc_makeDefaultBasket:
    This SP is responsible for changing which basket is displayed as a shopper's default basket if that shopper has saved baskets. It returns 0 for success or 1 for error. This SP also uses a transaction to ensure that there is no chance of ever having more than 1 default basket for a shopper at any time.

    Sproc_saveBasket:
    This SP is responsible for saving a shopper's default basket if the shopper decides to do so. It simply sets the default_basket flag to 0 and writes the shopper-specified basket name to the basket table. It returns 0 for success and 1 for error.

    Sproc_createGUID:
    For virtually every Web site that users interact with, there needs to be a mechanism for uniquely identifying each visitor. This SP provides that mechanism by using the SQL Server NEWID() function to return a 32-character Globally Unique Identifier (GUID). This is then written to the shopper's cookie on the Web site if the shopper does not already have one.

    Front-end Design

    ASP Pages

    The shopping basket is comprised of three ASP pages: two browser-viewable and one include file. These pages and their functions are described below.

    Basket.asp:
    This is the page that the shopper interacts with when using a basket. An image of what the shopper sees is shown below.


    Figure 3: A multifeatured ASP shopping cart.

    The basket.asp page also has three main functions:

    1. It receives and adds products from the product page to the shopper's basket.
    2. It processes various actions requested by the shopper from the basket form, such as updates, deletes, etc.
    3. It displays saved baskets, if any, and provides functionality to let the shopper manage them.
    A shopper can also flip between which basket is shown (default basket) from among the shopper'ss saved baskets.

    Note that the basket.asp page also has disabled session state and is enforcing explicit variable declarations by having the line "Option Explicit." Forcing yourself to explicitly declare variables is a good programming practice because it can prevent against inadvertently reusing or reassigning a variable with the wrong data. Disabling session state by having the statement "enablesessionstate = false " at the top of the page can buy added speed for your page since the server does not waste time trying to account for session management.

    Save_basket.asp:
    This page does exactly what its name implies: It allows the shopper to save a default basket to the database. This comes in handy if the user wants to start a new basket, but would like to preserve what is in a current basket for future purchase.

    Basket_util.asp:
    This page is simply a collection of functions and subroutines that make database calls or display HTML messages. These functions and subroutines are all called from the basket.asp page. It is generally good design to break out sections of code into subroutines that you can then call. It makes for cleaner code, much easier maintenance, and facilitates code reuse.

    Putting It All Together

    Sewing all parts of the application together to produce a single, coherent piece is fairly straightforward. You will notice that most of the business logic behind the basket is placed in the stored procedures. The advantage of this is twofold:

    1. Your application is much easier to migrate to a new platform (or ISP), if you so desire.
    2. You reduce network traffic by passing raw parameters to the database, having it do the processing, and simply returning the appropriate message back to your calling function.

    Error Handling

    By having "On Error Resume Next" near the top of the basket.asp page, you ensure that the server will continue to process the script even if it encounters an error. This provides a way to manually trap for errors that might occur and presents a more user-friendly error message if an error does occur. This is a much better practice than having your shoppers see a cryptic ODBC error message on their browser.

    Conclusion

    You have seen it is relatively painless to create and add a fully functional, multifeatured ASP-based shopping cart to your Web site. You do not have to spend the money to buy any commercial basket software. The solution shown here is also highly modular. This means, provided your Web site currently runs on IIS (supports ASP) and you have a database on the back end, you can simply plop the shopping basket into your existing Web site with very little modifications to the site's existing source code.

    I realize there are different ways this solution could be designed and implemented to achieve a similar result. As such, I welcome any and all feedback or suggestions on how you would have designed/implemented the solution differently from what was shown.

    About the Author

    Manny Agrinya is a Microsoft Certified Solutions Developer from New Jersey. He enjoys riding or tinkering with his motorcycle, and when not doing that, he is spending time in front of a computer - coding, or learning more about Linux and open-source software. He can be reached by email at emm_ag@yahoo.com or www.agrinya.com.

  • Rate This Article
    Not HelpfulMost Helpful
    1 2 3 4 5
    Supporting Products/Tools
    Proposion N2N
    Proposion N2N connects Microsoft .NET applications to Lotus Notes and Lotus Domino databases. This ADO.NET managed data provider allows you to perform blindingly fast queries and updates of Notes data from ASP.NET pages, .NET web services, Windows, or Mobile applications. An innovative SQL-like query language leverages the unique features of Notes and makes collaborative software accessible to relational database programmers.
    [Top]
    Other Articles
    Sep 15, 2005 - Building an Image Keyword System
    Unlike text-based file formats image files aren't made up of words, which makes searching for an image file by keyword difficult. Instead of being able to simply open the file to see what it contains, we're stuck looking at the text around it and other metadata to determine the image's meaning. In this article, Ziran Sun shows you how to build a simple database-based image keyword system that allows you to associate keywords with images and use these keywords to make finding images easier.
    [Read This Article]  [Top]
    Apr 7, 2005 - A Step-by-Step Guide To Using MySQL with ASP.NET - Part 2
    In the second part of of his article on using MySQL with ASP.NET, Ziran Sun covers how to add a new MySQL user to the database server, assign the user the appropriate permissions, connect to the database, and build a simple ASP.NET page to perform a query.
    [Read This Article]  [Top]
    Feb 10, 2005 - A Step-by-Step Guide To Using MySQL with ASP.NET - Part 1
    Back in the days of classic ASP, if you were building a database-driven web site, your choice was either to invest a lot of money to get a copy of Microsoft SQL Server (or some other enterprise-ready database) or invest a lot of time finding a way to deal with the performance and scalability limitations of Microsoft Access. Luckily these days there's another viable alternative: MySQL.
    [Read This Article]  [Top]
    Jan 27, 2005 - Moving a Database from SQL Server 7.0 to SQL Server 2000
    Moving or copying a SQL Server database from one machine to another requires a lot of preparation in order to ensure a smooth transfer. In this article, Dina Fleet Berry examines the different methods and highlights the different issues associated with each of them.
    [Read This Article]  [Top]
    Jan 6, 2005 - Debugging a SQL Stored Procedure from inside SQL Server 2000 Query Analyzer
    There are many times when using SQL Server 2000 Query Analyzer to debug SQL statements is a better choice than debugging in Visual Studio .NET. In this article, Dina Fleet Berry explains why and walks you through the debugging process step-by step.
    [Read This Article]  [Top]
    Nov 24, 2004 - Persisting .NET Objects to SQL Server Using SQLXML and Serialization
    As a follow up to his article on retrieving objects from SQL Server using SQLXML and serialization, Gianluca Nuzzo discusses saving objects back to SQL Server using a schema definition file and updategrams.
    [Read This Article]  [Top]
    Sep 14, 2004 - Transaction Processing in ADO.NET 2.0
    One area that stands out when comparing ADO.NET 1.x to ADO.NET 2.0 is transaction processing. Bill Ryan shows just how easy transaction processing has become with the TransactionScope object in ADO.NET 2.0.
    [Read This Article]  [Top]
    Sep 8, 2004 - Custom Object Data Binding with .NET
    Developers often use brute force coding to marshal data between the GUI and application objects. In this article, Luther Stanton explains how to use .NET's out-of-the box data-binding functionality to make this job much easier.
    [Read This Article]  [Top]
    Sep 2, 2004 - Queue MSMQ Messages from SQL Server
    Learn how to create a console application to queue a message in Microsoft Message Queuing (MSMQ) and then use an extended stored procedure to call the console application from a SQL Server trigger.
    [Read This Article]  [Top]
    Aug 30, 2004 - Tuning Up ADO.NET Connection Pooling in ASP.NET Applications
    Connection pooling increases the performance of Web applications by reusing active database connections instead of creating a new connection with every request. This article shows how to monitor the connection pool, diagnose a potential problem, and apply the appropriate fix.
    [Read This Article]  [Top]
    Mailing List
    Want to receive email when the next article is published? Just Click Here to sign up.

    Support the Active Server Industry