Building An Online Shopping Cart Using C And Asp Net

  

C#Today - Your J ust- In- Time Resource for C# Code and Techniques 페이지 1 / 16

Program m e

  Se a r ch C# Toda y Liv in g Book I ndex Full Tex t n l m j k i n j m l k

  Advanced H OM E SI TE M AP SEARCH REFEREN CE FORU M FEED BACK AD V ERTI SE SU

  Th e C# Toda y Ar t icle Previous art icle - Next art Au gu st 2 1 , 2 0 0 1 August 20, 2001 August 2

Bu ildin g a n On lin e Sh oppin g Ca r t u sin g C# a n d ASP.N ET Pa r t 1

  by Juan Mart ínez CATEGORY: Applicat ion Developm ent ARTI CLE TYPE: Tut orial

  Reader Com m ent s

ABSTRACT

  Art icle Usefu I n t his art icle Juan Mart ínez discusses and im plem ent s t he building blocks of an online shopping cart - covering in t his part it em cat alogs, it em det ails, a cart and a checkout syst em . This act s as t he

  I nnov foundat ion for fur t her ar t icles, w here Juan covers ot her funct ionalit y like adm inist rat ion pages and set t ing up credit card paym ent s.

  I nform 15 resp

Art icle Discussion Rat e t his ar t icle Relat ed Links I ndex Ent ries

ARTI CLE Edit or 's N ot e : Th is a r t icle ' s code h a s be e n u pda t e d t o w or k w it h t h e fin a l r e le a se of t h e .N e t fr a m e w or k

  

As w eb developers w e are required t o face a w ide variet y of applicat ion needs. Each w eb sit e developed is unique

and furnished according t o each client 's specific needs. The fact is t hat w ebsit es are indeed fabricat ed for each

client w it h different specificat ions but every sit e shares som e com m on charact erist ics. Those part s of t he sit e t hat

share funct ionalit y feat ures can be t reat ed as separat e applicat ions t o be reused.

  I n t his case w e w ill address t he developm ent cycle for one of t he com m on blocks in t oday's w ebsit es - an Online Shopping Cart . We w ill analyze t he developm ent of a shopping cart as a group of com ponent s described clearly before w e

im plem ent t hem , t hus allow ing us t o use t his know ledge in areas ot her t han ASP.NET. Aft er a descript ion of each

com ponent t he im plem ent at ion w ill be explained using C# . The applicat ion w ill be designed t o w ork w it h a SQLServer dat abase for st orage. Applicat ion logic w ill be done w it hin t he Web Form and present ed t o t he user t hrough t he w eb brow ser. Core logic w ill reside in a separat e C# com ponent using t he code behind t echnique. I t will also be .NET fr am ew or k Bet a 2 com pliant . I t is assum ed t hat you have regular know ledge of t he C# language, w eb developm ent know ledge and dat abase design basics.

  Se t t in g u p t h e ba sis Fir st w e w ill t ake som e t im e t o underst and how a sim ple shopping cart w orks. From t his know ledge w e w ill draw som e conclusions and st at e our requirem ent s. From t hese requirem ent s t he dat abase design w ill em erge.

  

Aft er t hese st eps w e w ill have a clear pat h of developm ent and be ready t o im plem ent our online shopping cart in

t he C# language.

  D iggin g in t h e On lin e Sh oppin g Ca r t M ode l

We w ill first t ake a look at a sim plified diagram of an Online Shopping Cart . These are t he funct ionalit y blocks t o

be discussed.

  We t hen have four basic m odules: z I t e m Ca t a log - Here w e display t he opt ions t o our client s in an or ganized w ay. z I t e m D e t a ils - Here w e show t he client as m uch info as w e can t o show off our product . z Sh oppin g Ca r t - Here we m anage t he user's select ed it em s.

z Ch e ck ou t Sy st e m - Her e w e save t he it em s select ed and t he client 's infor m at ion t o close t he t ransact ion.

  

These are t he basic blocks t o be im plem ent ed in our online st ore. I t includes t he indispensable funct ionalit y t hat

w ill be described in det ail lat er. These blocks could be enriched furt her w it h m ore feat ures, w hich w ill be covered

in lat er art icles.

  D e fin in g r e qu ir e m e n t s As in every soft w are developm ent cycle, w e need t o define our requirem ent s first so w e can design soft w are capable of giving sat isfact ion t o our cust om ers.

  Our online shopping cart applicat ion should do t he follow ing: z Have a list of cat egories and subcat egories. z I t em s should be ar r anged in it s corresponding subcat egory. z I t em s could be select ed for cat egory and hom e prom ot ion.

z Each product should have an id, nam e, shor t and long descript ions, sm all and lar ge im ages, st ock and price.

z Users should be able t o add product s t o t he basket and rem ove t hem . z The user should be given an order num ber and w ill be able t o t rack it t hrough an order t racking syst em .

  Ge n e r a t in g ou r da t a ba se m ode l 페이지 2 / 16 C#Today - Your J ust- In- Time Resource for C# Code and Techniques

  

C#Today - Your J ust- In- Time Resource for C# Code and Techniques 페이지 3 / 16

From our requir em ent s w e define t he dat abase schem a. The t ables ar e show n as a concept ual m odel, w it h all t ables used in t his version of t he shopping cart .

  The t ables ar e gr ouped as follow s: z Green - The cat alog part of our applicat ion. z Sky blue - I t em det ails. z Orange - Shopping cart basket . z Yellow - The checkout syst em .

  Ca t a log Se ct ion The green part corresponds t o t he ca t a log sect ion. I t is com posed of t wo t ables. This is a very sim ple arrangem ent in which t he su bse ct ion t able inherit s t he se ct ion I d. This w ay w e can display t he it em s in a

  

C#Today - Your J ust- In- Time Resource for C# Code and Techniques 페이지 4 / 16

sect ion/ subsect ion approach. As t his approach will work in m ost cases, you could im prove t his t o a com plet ely flexible design using r ecur sive sect ions, which will inherit a parent I d.

  I t e m D e t a ils

The it em det ails part of our m odel is a t rim m ed down version of an it em det ails design. We have only one t able in

which we save t he vit al inform at ion of t he it e m such as descript ion, price and im ages. We have a couple of Boolean values t hat are used t o specify if t he it em should be displayed as a hom e or sect ion it em .

  Sh oppin g ca r t ba sk e t The shopping basket is a sim ple t able t hat is used t em por ar ily t o st or e t he it em s select ed by t he user . We j ust save t he se ssion I d, t he it e m id and t he qu a n t it y. We will im plem ent t his as an in - m e m or y da t a t a ble and

hold our select ed it em s in a session var iable. This t able is show n t o show you're t he inform at ion t hat needs t o be

ret ained during our session.

  Ch e ck ou t syst e m

This is t he m ost com plicat ed par t or our syst em . Upon checkout w e creat e an order I d in t he order t able. Then t he

it em s st ored in t he shopping basket are t ransferred and saved in our order I t em s t able. The user inform at ion is

st or ed in t he order det ails t able. These t w o t ables inher it t he order I d. We have a fourt h t able which also inherit s

t he order I d. This is t he order Progress t able and it is used for order t racking. As progress is done, t he online shop

adm inist rat or should add a record t o t his t able indicat ing t he progress done t o dat e. This is t hen checked by t he buyer.

Le t t h e codin g be gin

  

As our design basis is done, w e are all set t o st art our coding. The archit ect ure will be based on sim ple Web Form s

calling cust om User Cont rols. Core logic w ill be done in separat e com ponent s using t he code behind t echnique.

  Applica t ion fr a m e w or k We st art by set t ing our basic fram ew ork. We m ake use of our web.config file t o save im port ant applicat ion inform at ion such as our connect ion st ring. This is how our configurat ion file will look:

  <configuration> <appSettings> <add key="connString" value="server=(local)\NetSDK;database=ShoppingCart;Trusted_Con </appSettings> </configuration> To r et rieve t his inform at ion w e use t he follow ing code snippet .

  String connString = ConfigurationSettings.AppSettings["connString"]; As you can see, t his is a very easy and convenient w ay t o st ore applicat ion w ise dat a.

  Ca t e gor y List Block All being set , w e have our first t ask w hich is t o display a list of pr oduct s w hich w ill be filt ered by sect ion and subsect ion if select ed.

  The first t ask is t o set up t he w orkspace of our Web Form s. We set up our language and add t he appropriat e nam espaces for our code t o w ork.. We set C# as our language and im port t he System nam espace for general purposes. We t hen add t he System.Data and System.Data.OleDb since w e w ill be using SQLSer ver as our dat abase engine. We should set t he debug flag t o false once w e deliver t his applicat ion t o t he real w orld.

  <%@ Page Language="C#" Debug="true" %> <%@ Import Namespace="System" %> <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SqlClient " %> We now set our references t o our cust om Use r Con t r ols.

C#Today - Your J ust- In- Time Resource for C# Code and Techniques 페이지 5 / 16

  <%@ Register TagPrefix="SC" TagName="Site" Src="uc_header.ascx" %> <%@ Register TagPrefix="SC" TagName="Section" Src="uc_catalog_section.ascx" %> <%@ Register TagPrefix="SC" TagName="SubSection" Src="uc_catalog_subsection.ascx" %> <%@ Register TagPrefix="SC" TagName="ProductList" Src="uc_catalog_product_list.ascx" %> We reference our cont rols by em bedding t hem int o t he aspx file.

  <SC:Site runat="server" /> This w ill be our com plet e cat alog WebForm , t he file. catalog.aspx

  <%@ Page Language="C#" Debug="true" %> <%@ Register TagPrefix="SC" TagName="Site" Src="uc_header.ascx" %> <%@ Register TagPrefix="SC" TagName="Section" Src="uc_catalog_section.ascx" %> <%@ Register TagPrefix="SC" TagName="SubSection" Src="uc_catalog_subsection.ascx" %> <%@ Register TagPrefix="SC" TagName="ProductList" Src="uc_catalog_product_list.ascx" %> <html> <head> <title>Shopping Cart in C# - Catalog</title> <link rel="stylesheet" href="style.css"> </head> <body> <form runat=server> <SC:Site runat="server" /> <table width="800" cellspacing="0" cellpadding="3" border="0" style="border-color:Black;b <tr> <td width="800" align="right" bgcolor="#CCCCCC"><span class="itemTitle">Item Catalog</sp </tr> </table> <table width="800" cellspacing="0" cellpadding="0" border="0"> <tr> <td width="200" height="100%" rowspan="2" valign="top"><SC:Section runat="server" /></td <td width="600" height="10" valign="top"><SC:SubSection runat="server" /></td> </tr> <tr> <td width="600" height="100%"><SC:ProductList runat="server" /></td> </tr> </table> </form> </body> </html>

  We have used four cust om user cont r ols in our fir st Web For m . We shall now go t owards im plem ent ing t hese cust om cont rols, m ost of which, will be reused t hrough out t he sit e. Let s st art by im plem ent ing t he sim plest of our user cont r ols, uc_header.ascx . This file cont ains t he " logo" of t he sit e and a couple of links. We encapsulat e t his int o a cont rol since it w ill be repeat ed t hr ough t he w hole sit e. This is t he code:

  <table width="800" cellspacing="0" cellpadding="3" border="0" style="border-color:Black;b <tr> <td width="400"><a href="catalog.aspx"><span class="mainTitle">Shopping Cart Site</span> <td width="400" align="right"><a href="cart.aspx">View Cart</a><span class="mainText"> | </span><a href="tracking.aspx">Track your order</a></td> </tr> </table>

  

As you can see t his is j ust a st at ic t able, rem iniscent of old st yle include files. Next w e code a m ore com plex user

cont rol, uc_catalog_section.ascx w hich displays t he list of sect ions available on t he sit e. This is done by binding a dat a ret rieval codebehind class t o t he user cont rol.

  This is our User Cont rol Code:

  <%@ Control Language="C#" Debug="true" Inherits="CodeBehind.UcSection" %> <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SqlClient" %>

C#Today - Your J ust- In- Time Resource for C# Code and Techniques 페이지 6 / 16

  <html> <head> <title></title> <script language="C#" runat="server"></script> </head> <body> <font face="Verdana" size="-1"> <asp:DataList id="MySectionList" runat="server" BorderColor="black" BorderWidth="1" GridLines="Both" CellPadding="3" Font-Name="Verdana" Font-Size="8pt" Width="200px" HeaderStyle-BackColor="#aaaadd" SelectedItemStyle-BackColor="Gainsboro" > <HeaderTemplate> Sections </HeaderTemplate> <ItemTemplate> <a href="catalog.aspx?sectionId=<%# DataBinder.Eval(Container.DataItem,"ca &sectionIndex=<%#Cont <%# DataBinder.Eval(Container.DataItem, "catalogS </ItemTemplate> <SelectedItemTemplate> <%# DataBinder.Eval(Container.DataItem, "catalogSectionName") %> </SelectedItemTemplate> </asp:DataList> </font> </body> </html>

  We place som e m ore ht m l int o t he cont rol and w e drop a Dat aList obj ect t o handle t he r ender ing of t he inform at ion. The <%# DataBinder.Eval(Container.DataItem, "catalogSectionName") %> code is used t o select specific inform at ion from t he bound dat a and put it in place.

  

I n our codebehind class w e first have t o declare our Dat aList as prot ect ed. We t hen do som e dat abase w ork. Once

w e have t he inform at ion w e need ready from our dat abase, w e bind t his dat a t o our Web Cont rol, t he Dat aList . Our User Cont rol inherit s t he code behind class and t hat w ay t hey can w ork t oget her. I t is im por t ant t o declar e your shared variables ( such as Web Form Cont rols) as prot ect ed so t hat t he can be reached w it hin t he code behind class.

  public class UcSection : UserControl { protected DataList MySectionList; protected Label MyLabel; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { Bind_MySectionList(); } if (Request.QueryString["sectionIndex"] != null) { MySectionList.SelectedIndex = Int32.Parse(Request.QueryString["sectionIndex"]); } } protected void Bind_MySectionList() { String connString = ConfigurationSettings.AppSettings["connString"]; SqlConnection myConnection = new SqlConnection(connString); SqlDataAdapter myCommand = new SqlDataAdapter("SELECT catalogSectionId, catalogSecti FROM catalogSection ORDER BY catalogSectionName", myConnec DataSet ds = new DataSet(); myCommand.Fill(ds, "catalogSection");

  

C#Today - Your J ust- In- Time Resource for C# Code and Techniques 페이지 7 / 16

  MySectionList.DataSource = new DataView(ds.Tables[0]); MySectionList.DataBind(); } }

  We t hen have t o im plem ent our su bse ct ion u se r con t r ol. This cont rol w ill do a sim ilar t ask t o t he sect ion

cont rol. We w ill j ust add a filt er t o t he Query applied t o t he dat abase. We will select subsect ions corresponding t o

t he select ed sect ion. The rest is pret t y m uch t he sam e.

  "SELECT catalogSubSectionId, catalogSubSectionName FROM catalogSubSection WHERE catalogS sectionId + " ORDER BY catalogSub

  We t hen need t o display our product list . We have t hr ee t ypes of pr oduct s: z Sit e Product s: These are shown if no sect ion is select ed z

  Sect ion Product s: These are shown if a sect ion is select ed but no subsect ion is select ed. z Nor m al Product s: These ar e product s t hat belong t o t he select ed subsect ion.

  We need t o filt er t he t hree possibilit ies and creat e t he proper query. This is done in t he UcProductList class w it h t his code. Aft er w e have our query w e bind it t o a Dat aGr id Web Cont rol t o display t he it em s in a t able arrangem ent .

  string SQLQuery = "SELECT itemId, itemName, itemShortDescription, itemSmallImage, itemPr FROM item WHERE itemPromoteSite=1 ORDER int mysectionId = 0; if (Request.QueryString["sectionId"] != null) { mysectionId = Int32.Parse(Request.QueryString["sectionId"]); } if (mysectionId != 0) { //If we have a section selected we filter products for this section SQLQuery = "SELECT item.itemId, item.itemName, item.itemShortDescription, item.itemSma FROM (catalogSection INNER JOIN catalogSubSection ON catalogSection.catalogSectionI

  INNER JOIN item ON catalogSubSection.catalog WHERE (((catalogSection.catalogSectionId)=" + mysectionId + " } int mysubsectionId = 0; if (Request.QueryString["subsectionId"] != null) { mysubsectionId = Int32.Parse(Request.QueryString["subsectionId"]); } if (mysubsectionId != 0) { //If we have a subsection selected we filter products for this subsection SQLQuery = "SELECT itemId, itemName, itemShortDescription, itemSmallImage, itemPrice, WHERE catalogSubSectionId=" + mysubsectionId + " ORDER BY itemName"; } This concludes our cat alog present at ion layer which consist s of four m ain user cont rols.

  z The first cont rol is responsible for displaying a list of sect ions. z The second cont rol is responsible for t he subsect ion list .

z The t hird cont rol is responsible for displaying a grid of it em s. This list of it em s is ret rieved from one of t hree sql

queries depending on t he sit uat ion. z A final cont rol renders t he t op of t he page.

  All t he cont r ols w or k t oget her t o for m catalog.aspx . The user cont r ols m ake use of codebehind classes for dat abase access and bind t he Dat aList s in our page. Our catalog.aspx file should yield som et hing like t his:

  

C#Today - Your J ust- In- Time Resource for C# Code and Techniques 페이지 8 / 16

I t e m D e t a ils

  

Our next st ep in building our shopping cart is t o show off t he it em det ails. We first w ill use som e of t he code done

for t he cat alog present at ion before. We w ill t ake t he basic ht m l fram ew ork and t hree user cont rols. We will reuse

t he header, sect ion and subsect ion cont r ol.

  

The difference here w ill be t o replace t he it e m list cont rol w it h a ne w it e m de t a ils cont r ol. We w ill use a dat a list

Web Cont rol t o display t he it em s charact erist ics as well as it s cor r esponding class in our code behind reposit ory.

The code t o do t his sim ple t ask is as follow s for t he user cont r ol:

  <%@ Control Language="C#" Debug="true" Inherits="CodeBehind.UcItemDetails" %> <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SqlClient" %> <script language="C#" runat="server"></script> <font face="Verdana" size="-1"> <asp:DataList id="MyItemDetails" runat="server" BorderColor="black" BorderWidth="1" GridLines="Both" CellPadding="3" Font-Name="Verdana" Font-Size="8pt" Width="600px" HeaderStyle-BackColor="#aaaadd" SelectedItemStyle-BackColor="Gainsboro" RepeatDirection = "Horizontal" RepeatColumns = "1"

C#Today - Your J ust- In- Time Resource for C# Code and Techniques 페이지 9 / 16

  > <ItemTemplate> <table> <tr> <td valign="top"> <img src="images/<%# DataBinder.Eval(Container.DataItem, "itemLargeImage") %>" wid </td> <td valign="top"> <span class="itemTitle"><%# DataBinder.Eval(Container.DataItem, "itemName") %></sp <br> <span class="itemText"><%# DataBinder.Eval(Container.DataItem, "itemLongDescriptio <br><br> <span class="itemText">Price: <%# (DataBinder.Eval(Container.DataItem, "itemPrice" <br> <span class="itemText">Stock: <%# DataBinder.Eval(Container.DataItem, "itemStock") <br><br> <a href="catalog.aspx?sectionId=<%=sectionId%>&sectionIndex=<%=sectionIndex%>&subs &subsectionIndex=<%=subsectionIndex <span class="itemText"> | </span> <a href="cart.aspx?cartAction=1&itemId=<%# DataBinder.Eval(Container.DataItem, "it </td> </tr> </table> </ItemTemplate> </asp:DataList> </font>

  And our code behind class:

  protected void Bind_ItemDetails() { int myItemId = 0; if (Request.QueryString["itemId"] != null) { myItemId = Int32.Parse(Request.QueryString["itemId"]); } string SQLQuery = "SELECT itemId, itemName, itemLongDescription, itemLargeImage, itemP FROM item WHERE itemId String connString = ConfigurationSettings.AppSettings["connString"]; SqlConnection myConnection = new SqlConnection(connString); SqlDataAdapter myCommand = new SqlDataAdapter(SQLQuery, myConnection); DataSet ds = new DataSet(); myCommand.Fill(ds, "item"); MyItemDetails.DataSource = new DataView(ds.Tables[0]); MyItemDetails.DataBind(); }

  

Furt her enhancem ent s can be done t o t his sim ple m odule. This form show s t he st ored det ails of t he it em and can

be enriched w it h user review s and r elat ed it em list s. Our r esult ing screen should look as follow s:

  

C#Today - Your J ust- In- Time Resource for C# Code and Techniques 페이지 10 / 16

Sh oppin g ca r t ba sk e t

  The shopping cart basket im plem ent s t he m aj orit y of t he funct ionalit y. I t should provide w ays t o add, edit and

delet e it em s from it . The basket is m erely a t em poral st orage area for t he user t o group t he it em s of int er est . We

t hen need som e session m anagem ent t o be able t o r ecognize w hich it em s belong t o each client in it s ow n session.

  ASP.NET, as in previous asp applicat ions, provides t he necessary obj ect s t o work wit h sessions. I n t his case we w ill t ake advant age of t he Se ssion obj ect . We will st ore a D a t a Ta ble obj ect as a Session var iable t herefor e all shopping cart basket operat ions ar e done in m em or y. This is a very fast approach but w ill need t o be provided w it h enough m em ory t o handle concurrent client s.

  The shopping basket m odule com prises t w o fundam ent al part s. The fir st involves m anaging t he it em s t hat t he

user w ant s t o have in t he basket . The second is in charge of displaying t he it em s current ly in t he basket . We w ill

see t he det ails now .

  We inst ruct our Web Form t o add an it em t o t he cart w it h queryst ring variables. We j ust add an it em t o t he

Dat aTable. To im plem ent t he updat e and delet e m et hods w e bind t he Dat aTable t o t he Dat aList Web Cont rol and

perform t he operat ions.

  void Page_Load(Object Sender, EventArgs E) { if (Request.QueryString["cartAction"] != null) { this.cartAction = Int32.Parse(Request.QueryString["cartAction"]); } if (Session["ShoppingCart"] == null) { Cart = new DataTable(); Cart.Columns.Add(new DataColumn("ItemId", typeof(string))); Cart.Columns.Add(new DataColumn("Item", typeof(string))); Cart.Columns.Add(new DataColumn("Qty", typeof(string))); Cart.Columns.Add(new DataColumn("Price", typeof(string))); Session["ShoppingCart"] = Cart; } else {

C#Today - Your J ust- In- Time Resource for C# Code and Techniques 페이지 11 / 16

  Cart = (DataTable)Session["ShoppingCart"]; } CartView = new DataView(Cart); CartView.Sort = "Item"; if (!IsPostBack) { //Add new entry to the shopping cart int myCartAction = 0; if (Request.QueryString["cartAction"] != null) { myCartAction = Int32.Parse(Request.QueryString["cartAction"]); } if (myCartAction==1) { //Take the items details from the database string myItemId = "0"; if (Request.QueryString["itemId"] != null) { myItemId = Request.QueryString["itemId"]; } string SQLQuery = "SELECT itemName, itemPrice FROM item WHERE itemId = " + myIt String connString = ConfigurationSettings.AppSettings["connString"]; SqlConnection myConnection = new SqlConnection(connString); SqlCommand myCommand = new SqlCommand(SQLQuery, myConnection); myConnection.Open(); SqlDataReader dr2 = myCommand.ExecuteReader(); if (dr2.Read()) { DataRow dr = Cart.NewRow(); dr[0] = myItemId; dr[1] = dr2.GetString(0); dr[2] = "1"; dr[3] = dr2.GetSqlMoney(1).ToString(); Cart.Rows.Add(dr); } } BindCartList(); BindTotalList(); } }

  The funct ions t o updat e and delet e dat a ar e as follow s:

  protected void DataCartList_DeleteCommand1(Object Sender, DataListCommandEventArgs e string item = ((Label)e.Item.FindControl("Label4")).Text; CartView.RowFilter = "Item='"+item+"'"; if (CartView.Count > 0) //item exists in cart CartView.Delete(0); CartView.RowFilter = ""; CartList.EditItemIndex = -1; BindCartList(); BindTotalList(); } protected void DataCartList_EditCommand1(Object Sender, DataListCommandEventArgs e) CartList.EditItemIndex = (int)e.Item.ItemIndex; BindCartList(); BindTotalList(); } protected void DataCartList_CancelCommand1(Object Sender, DataListCommandEventArgs e CartList.EditItemIndex = -1; BindCartList(); BindTotalList(); } protected void DataCartList_UpdateCommand1(Object Sender, DataListCommandEventArgs e string itemId = ((Label)e.Item.FindControl("Label1")).Text; string item = ((Label)e.Item.FindControl("Label2")).Text;

C#Today - Your J ust- In- Time Resource for C# Code and Techniques 페이지 12 / 16

  string qty = ((TextBox)e.Item.FindControl("Text1")).Text; string price = ((Label)e.Item.FindControl("Label3")).Text; // with a database, we'd use an update command. Since we're using an in-memory // DataTable, we'll delete the old row and replace it with a new one //remove old entry CartView.RowFilter = "Item='"+item+"'"; if (CartView.Count > 0) //item exists in cart CartView.Delete(0); CartView.RowFilter = ""; //add new entry DataRow dr = Cart.NewRow(); dr[0] = itemId; dr[1] = item; dr[2] = qty; dr[3] = price; Cart.Rows.Add(dr); CartList.EditItemIndex = -1; BindCartList(); BindTotalList(); }

  

Finally we need t o calculat e t he subt ot al, t ax and t ot al cost of t he order. We use t he BindTotalList() funct ion

t o generat e cont ent and bind it t o anot her Web Cont rol in our page.

  protected void BindTotalList() { double mySubTotal = 0; double myTaxRate = 0.15; double myTax = 0; double myTotal = 0; DataTable CartTable = (DataTable)Session["ShoppingCart"]; foreach(DataRow myRow in CartTable.Rows) { Double tempPrice = Double.Parse(myRow[3].ToString()); Int32 tempQty = Int32.Parse(myRow[2].ToString()); mySubTotal += tempPrice * tempQty; } myTax = mySubTotal * myTaxRate; myTotal = mySubTotal + myTax; CartTotal = new DataTable(); CartTotal.Columns.Add(new DataColumn("SubTotal", typeof(string))); CartTotal.Columns.Add(new DataColumn("Tax", typeof(string))); CartTotal.Columns.Add(new DataColumn("Total", typeof(string))); DataRow drTotal = CartTotal.NewRow(); drTotal[0] = mySubTotal.ToString(); drTotal[1] = myTax.ToString(); drTotal[2] = myTotal.ToString(); CartTotal.Rows.Add(drTotal); CartTotalView = new DataView(CartTotal); CartTotalList.DataSource = CartTotalView; CartTotalList.DataBind(); }

  The shopping cart screen looks like t his:

  

C#Today - Your J ust- In- Time Resource for C# Code and Techniques 페이지 13 / 16

Ch e ck ou t Sy st e m

  The checkout syst em has t he responsibilit y of saving t he client info and select ed it em s for processing. We use t hree t ables t o save t he client info. These are t he follow ing: z order Dat a - St or es t he dat e of t he order and generat es t he order I d. z orderI t em - List of it em s bought , it also saves t he pr ice at t he t im e of pur chase. z orderDet ail - Saves shipping and billing inform at ion for t he order.

  We divide our process int o t hr ee st eps:

z Shipping and Billing I nform at ion - Here w e get t he shipping inform at ion. Wit h t his info w e can calculat e t he

shipping cost s. This should be done accor dingly t o each st or e's necessit ies. We validat e credit car d infor m at ion also. This should be done using a specific provider like paypal. z

  Confirm at ion - Her e w e present a sum m ary of t he inform at ion received and show t he list of it em s t o be bought , as w ell as t he grand t ot al of t he order. The user is asked t o subm it t he inform at ion if it is correct . z Sum m ary - We finish t he t ransact ion and show t he user t he order num ber.

  

We post t he info from t he first t o t he second st ep. We t hen use Web Form Cont rols t o ask for confirm at ion. I f t he

info is correct , t hen w e regist er t he order for our client . We do need t o im plem ent som e form validat ion before post ing t he infor m at ion and im plem ent som e credit card validat ion t hrough an ext ernal pr ovider or your ow n soft w are.

  Tr a ck in g y ou r or de r The final part of our online shopping car t applicat ion is t he t r acking syst em . We w ill im plem ent a basic t racking syst em w hich w ill ask t he user for t heir em ail and order num ber. The syst em w ill t hen show a list of m ilest ones regist ered in t he t racking dat abase.

We use a single t able t o save t he t r acking inform at ion. I t consist s of t he order id and t he inform at ion of t he goals

achieved. Upon valid em ail and order num ber we display t he list of event s below.

  

C#Today - Your J ust- In- Time Resource for C# Code and Techniques 페이지 14 / 16

This is t he code required:

  protected void ButtonView_Click(object Source, EventArgs e) { //Look for order id with provided email and order number String connString = ConfigurationSettings.AppSettings["connString"]; string strSelect = "SELECT orderId FROM orderDetail WHERE orderId=" + orderIdBox.Text AND orderDetailShippingEmail='" + emailBox.Text + "'"; SqlConnection myConnection = new SqlConnection(connString); SqlCommand myCommand = new SqlCommand(strSelect, myConnection); myConnection.Open(); SqlDataReader dr = myCommand.ExecuteReader(); int newOrderId = 0; if (dr.Read()) { //emailBox.Text = "Encontramos!!!"; Bind_TrackingList(); } myConnection.Close(); } protected void Bind_TrackingList() { string SQLQuery = "SELECT orderProgressText, orderProgressDescription, orderProgressD WHERE orderId = " + orderIdBox.Text; String connString = ConfigurationSettings.AppSettings["connString"]; SqlConnection myConnection = new SqlConnection(connString); SqlDataAdapter myCommand = new SqlDataAdapter(SQLQuery, myConnection); DataSet ds = new DataSet(); myCommand.Fill(ds, "orderProgress"); MyTrackingList.DataSource = new DataView(ds.Tables[0]); MyTrackingList.DataBind(); }

  D e ploy m e n t of t h e sit e Deploym ent of t his part icular applicat ion is ver y sim ple. z Creat e a ne w da t a ba se in SQLServer z Once w e have cr eat ed t he dat abase w e need t o r un t he da t a ba se cr e a t ion scr ipt provided. z

  Creat e a ne w sit e in your I I S adm inist rat ion program z Copy t he w e b.con fig file t o t he w w w root folder. z Copy t he W e b For m s and Use r con t r ols t o t he w w w root folder. z Copy t he code be h in d.dll int o your w w w root / bin direct ory ( no regist rat ion required! ) .

I m pr ove m e n t s t o ou r on lin e sh oppin g ca r t a pplica t ion

  The shopping cart w e j ust m ade t akes a basic appr oach t o t he applicat ion providing t he cent r al fr am ew ork of an online shopping cart . Furt her enhancem ent s can be m ade and w ill be t he responsibilit y of t he reader. These enhancem ent s should be m ade t o enrich t he shopping cart applicat ion give a bet t er ser vice t o t he online com m unit y. Som e ideas are present ed here.

  Fe a t u r e im pr ove m e n t s z

  Recursive sect ions for n levels of pr ofundit y z I t em review s z I t em relat ed it em s z

  User account s and m anagem ent z

  Mailing list t o cust om ers z Specific shipping cost s calculat ions

  Te ch n ica l im pr ove m e n t s z

  Build based on com ponent s for perform ance and possible code reuse z Migrat e t o SQL Server dat abase using st ored procedures for perform ance z I m plem ent SSL in your server ( a m ust but out of scope! ) z I m plem ent real t im e credit card processing and charging.

Con clu sion s

  RATE TH I S ARTI CLE Ple a se r a t e t h is a r t icle ( 1 - 5 ) . W a s t h is a r t icle ... Use fu l? N o n m l k j n m l k j n m l k j n m l k j n m l k j

  Ye s, V e r y I n n ova t ive ? N o n m l k j n m l k j n m l k j n m l k j n m l k j

  Ye s, V e r y I n for m a t ive ? N o n m l k j n m l k j n m l k j n m l k j n m l k j

  Ye s, V e r y Br ie f Re a de r Com m e n t s? You r N a m e : USEFU L LI N KS Re la t e d Ta sk s: z D ow n loa d t h e su ppor t m a t e r ia l for t his z

  En t e r Te ch n ica l D iscu ssion on t his Ar t ic z Technical Support on t his art icle - support @ z

  See ot her art icles in t he Applicat ion Develo z

  See ot her Tut orial art icles z Reader Com m ent s on t his ar t icle z Go t o Previous Art icle z

  Go t o Next Art icle 페이지 15 / 16 C#Today - Your J ust- In- Time Resource for C# Code and Techniques

  

The syst em present ed shows t he basis of a working online shopping cart . I t involves t he m ain aspect s of an online

st ore which are t he cat alog of it em s, t he it em det ail m odule, t he shopping cart basket and t he checkout m odule. Every shopping car t online t oday m ust im plem ent t hese basic part s t o be funct ional. Hopefully t his ar t icle has

given you t he know ledge t o build your own w it h ease and t o add new funct ionalit y t o m eet your needs as ideas for

im provem ent have been given.

  

I n fut ure art icles, w e w ill cover som e of t he im port ant requirem ent s of a real - w orld shopping cart t hat have been

left out of t his art icle for t he sake of brevit y - a m anagem ent console t o add, m odify and delet e cat egories, it em s

and orders; it em review s; SSL for credit car d paym ent s; and a discussion of w or king w it h a credit card processing

provider .

  ( Opt ion a l) Re la t e d Sou r ce s z asp101: ht t p: / / w ww.asp101.com / sam ples/ shopping.asp z Paym ent Online: ht t p: / / w ww.paym ent online.com / z Pow er Designer: ht t p: / / w ww.sybase.com / product s/ ent erprisem odeling/ pow erdesigner z

  페이지 16 / 16 C#Today - Your J ust- In- Time Resource for C# Code and Techniques

I n de x En t r ie s in t h is Ar t icle

  Full Tex t n m l k j

  Advanced

  z C# z checkout syst em z code behind t echnique z cont ent s, displaying z cont ent s, updat ing z creat ing z dat abase design z Dat aGrid z Dat aList cont rol z Dat aTable obj ect z designing z it em cat alog z it em det ai z online st or z persist enc z session va z sessions z shopping c z

  SQL Serve z t racking sy z user cont r z w eb cont ro z w eb form s z w eb.config

  H OM E |

  SI TE M AP |

  Pay Pal: w w w .paypal.com Se a r ch t h e C# Toda y Liv in g Book

  SEARCH |

  |

  | AD V ERTI S

  Ecom m erce Perform ance Securit y Sit e Design

  XML SO Dat a Access/ ADO.NET Applicat ion Developm ent

  Web Services Graphics/ Gam es Mobile Ot her Technologies

  C# Today is brought t o you by Wrox Press ( w w w .w rox.com ) . Please see our t erm s and condit ions and privacy C# Today is opt im ised for Microsoft I nt ernet Explorer 5 brow sers. Please report any w ebsit e problem s t o w ebm ast er@csharpt oday.com . Copyright © 2002 Wrox Press. All Right s

  I ndex n m l k j i

  I N D EX |

  

C#Today - Your J ust- In- Time Resource for C# Code and Techniques 페이지 1 / 17

Program m e

  Se a r ch C# Toda y Liv in g Book I ndex Full Tex t j m n k l i n j k m l

  Advanced H OM E SI TE M AP SEARCH REFEREN CE FORU M FEED BACK AD V ERTI SE SU

  Th e C# Toda y Ar t icle Previous art icle - Next ar D e ce m be r 1 7 , 2 0 0 1 Decem ber 14, 2001 Decem b

Bu ildin g a n On lin e Sh oppin g Ca r t Usin g C# Pa r t 2

  by Juan Mart ínez CATEGORY: Applicat ion Developm ent ARTI CLE TYPE: Tut orial

  Reader Com m ent s

ABSTRACT

  Art icle I n t his art icle, Juan Mart inez cont inues his work in building an online shopping cart applicat ion. I n part Usefu one, he discussed t he basic fram ew ork of t he applicat ion, now t he t im e has com e t o increase t he feat ures of t he shopping cart and have a com plet e syst em for online use. These enhancem ent s w ill I nnov dem onst rat e how easy it is t o add new funct ionalit y t o t he fram ew ork, by adding a cust om er rat ing cont rol for t he available it em s. He w ill also build an adm inist rat ion console, which will enable us t o

  I nform m anage t he online st ore t hrough t he web, and will discuss t he secur it y issues on t he w eb, and how t o im plem ent SSL in you ser ver for encr ypt ion. Finally he w ill briefly discuss t he various paym ent services 9 r espo available on t he w eb.

  

Art icle Discussion Rat e t his ar t icle Relat ed Links I ndex Ent ries

ARTI CLE Edit or 's N ot e : Th is a r t icle ' s code h a s be e n u pda t e d t o w or k w it h t h e fin a l r e le a se of t h e .N e t fr a m e w or k

  I n t his art icle, we shall cont inue our w ork in building t he online shopping cart applicat ion t hat w e began in part one ( ht t p: / / w w w .cshar pt oday.com / cont ent / ar t icles/ 20011821.asp ) . We have alr eady discussed t he basis fram ew ork of t he applicat ion; w e built a cat egory list , it em showcase, shopping cart , and checkout syst em .

  Now t he t im e has com e t o incr ease t he feat ures of t he shopping cart and have a com plet e syst em for online use. We w ill build upon our developm ent from part one and enrich t he websit e wit h new feat ures in t he sam e way w e did before, first defining our basic requirem ent s, set t ing up t he necessary m odificat ions, and finally convert ing it t o code.

  These enhancem ent s w ill dem onst r at e how easy it is t o add new funct ionalit y t o t he fram ew or k described in t he previous art icle, by adding a cust om er rat ing cont rol for t he available it em s. We w ill also build an adm inist rat ion

console, w hich w ill enable us t o m anage t he online st ore t hrough t he w eb. We w ill also discuss t he secur it y issues

on t he w eb, and how t o im plem ent SSL in your server for encrypt ion. Finally w e w ill briefly discuss t he various paym ent services available on t he w eb.

  The applicat ion w ill be designed t o w ork w it h an SQL Server dat abase for st or age. Applicat ion logic w ill be done w it hin t he Web Form and present ed t o t he user t hrough t he w eb brow ser. Core logic w ill reside in a separat e C# com ponent using t he code behind t echnique. I t will also be .NET fr am ew or k Bet a 2 com pliant .

  I t is assum ed t hat you have basic know ledge of t he C# language, w eb developm ent know ledge, and dat abase design basics.

  Re m e m be r in g t h e sh oppin g ca r t a r ch it e ct u r e

  

C#Today - Your J ust- In- Time Resource for C# Code and Techniques 페이지 2 / 17

Before w e st art t o put t oget her our new com ponent s, w e need t o rem em ber t he archit ect ure of our exist ing

shopping cart . We w ill review t he shopping cart m odel and st at e w here our m odificat ions w ill be. We w ill also look

back at our exist ing dat abase, w hich w e w ill t hen m odify t o support t he new feat ures.

  Th e sh oppin g ca r t m ode l The shopping cart m odel is a sim plified flow of inform at ion t hat happens in all online shopping car t im plem ent at ions, and is t he basis for our online car t .

  We t hen have four basic m odules in our applicat ion: z I t em Cat alog - Here w e display t he opt ions t o our client s in an or ganized w ay. z I t em Det ails - Here w e show t he client as m uch info as w e can t o show off our product . z Shopping Cart - Here w e m anage t he user's select ed it em s.

z Checkout Syst em - Her e w e save t he it em s select ed and t he client 's infor m at ion t o close t he t ransact ion.

  

We w ill build addit ional feat ures inside t he " it em det ails" m odule by coding new user cont rols and sim ply include

t hem in t he Web Form . The adm inist rat ion console w ill cont rol t he inform at ion in t he dat abase. I t w ill not have any influence on t he shopping cart m odel, as it w ill act as a back end.

  Th e da t a ba se m ode l Now w e w ill t ake a look at our dat abase schem a.

  

C#Today - Your J ust- In- Time Resource for C# Code and Techniques 페이지 3 / 17

The t ables ar e gr ouped as follow s: z Green - The cat alog part of our applicat ion. z Blue - I t em det ails. z Orange - Shopping cart basket . z Yellow - The checkout syst em .

  The new feat ures of our applicat ion w ill have t o int eract w it h t his exist ing dat abase schem a. The det ails w ill be discussed aft erw ards.

  Th e j ob a h e a d

Now t hat w e have review ed t he w ork done previously, w e need t o define our new requirem ent s, and t hen do t he

appropriat e changes t o be able t o support t hem .

  

C#Today - Your J ust- In- Time Resource for C# Code and Techniques 페이지 4 / 17

D e fin in g ou r n e w r e qu ir e m e n t s

  

As in every soft w are developm ent cycle, w e need t o define our requirem ent s first , so t hat w e can design soft w ar e

capable of giving sat isfact ion t o our cust om ers. Our online shopping cart applicat ion should add t he follow ing feat ures: z I nclude a cust om er rat ing com ponent . z