Part 5: Business Logic
by Joe Stagner
Tailspin Spyworks demonstrates how extraordinarily simple it is to create powerful, scalable applications for the .NET platform. It shows off how to use the great new features in ASP.NET 4 to build an online store, including shopping, checkout, and administration.
This tutorial series details all of the steps taken to build the Tailspin Spyworks sample application. Part 5 adds some business logic.
Adding Some Business Logic
We want our shopping experience to be available whenever someone visits our web site. Visitors will be able to browse and add items to the shopping cart even if they are not registered or logged in. When they are ready to check out they will be given the option to authenticate and if they are not yet members they will be able to create an account.
This means that we will need to implement the logic to convert the shopping cart from an anonymous state to a “Registered User” state.
Let’s create a directory named “Classes” then Right-Click on the folder and create a new “Class” file named MyShoppingCart.cs
As previously mentioned we will be extending the class that implements the MyShoppingCart.aspx page and we will do this using .NET’s powerful “Partial Class” construct.
The generated call for our MyShoppingCart.aspx.cf file looks like this.
[!code-csharpMain]
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Web;
5: using System.Web.UI;
6: using System.Web.UI.WebControls;
7:
8: namespace TailspinSpyworks
9: {
10: public partial class MyShoppingCart : System.Web.UI.Page
11: {
12: protected void Page_Load(object sender, EventArgs e)
13: {
14:
15: }
16: }
17: }
Note the use of the “partial” keyword.
The class file that we just generated looks like this.
[!code-csharpMain]
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Web;
5:
6: namespace TailspinSpyworks.Classes
7: {
8: public class MyShoppingCart
9: {
10: }
11: }
We will merge our implementations by adding the partial keyword to this file as well.
Our new class file now looks like this.
[!code-csharpMain]
1: namespace TailspinSpyworks.Classes
2: {
3: public partial class MyShoppingCart
4: {
5: }
6: }
The first method that we will add to our class is the “AddItem” method. This is the method that will ultimately be called when the user clicks on the “Add to Art” links on the Product List and Product Details pages.
Append the following to the using statements at the top of the page.
[!code-csharpMain]
1: using TailspinSpyworks.Data_Access;
And add this method to the MyShoppingCart class.
[!code-csharpMain]
1: //------------------------------------------------------------------------------------+
2: public void AddItem(string cartID, int productID, int quantity)
3: {
4: using (CommerceEntities db = new CommerceEntities())
5: {
6: try
7: {
8: var myItem = (from c in db.ShoppingCarts where c.CartID == cartID &&
9: c.ProductID == productID select c).FirstOrDefault();
10: if(myItem == null)
11: {
12: ShoppingCart cartadd = new ShoppingCart();
13: cartadd.CartID = cartID;
14: cartadd.Quantity = quantity;
15: cartadd.ProductID = productID;
16: cartadd.DateCreated = DateTime.Now;
17: db.ShoppingCarts.AddObject(cartadd);
18: }
19: else
20: {
21: myItem.Quantity += quantity;
22: }
23: db.SaveChanges();
24: }
25: catch (Exception exp)
26: {
27: throw new Exception("ERROR: Unable to Add Item to Cart - " +
28: exp.Message.ToString(), exp);
29: }
30: }
31: }
We are using LINQ to Entities to see if the item is already in the cart. If so, we update the order quantity of the item, otherwise we create a new entry for the selected item
In order to call this method we will implement an AddToCart.aspx page that not only class this method but then displayed the current shopping a=cart after the item has been added.
Right-Click on the solution name in the solution explorer and add and new page named AddToCart.aspx as we have done previously.
While we could use this page to display interim results like low stock issues, etc, in our implementation, the page will not actually render, but rather call the “Add” logic and redirect.
To accomplish this we’ll add the following code to the Page_Load event.
[!code-csharpMain]
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Web;
5: using System.Web.UI;
6: using System.Web.UI.WebControls;
7: using System.Diagnostics;
8:
9: namespace TailspinSpyworks
10: {
11: public partial class AddToCart : System.Web.UI.Page
12: {
13: protected void Page_Load(object sender, EventArgs e)
14: {
15: string rawId = Request.QueryString["ProductID"];
16: int productId;
17: if (!String.IsNullOrEmpty(rawId) && Int32.TryParse(rawId, out productId))
18: {
19: MyShoppingCart usersShoppingCart = new MyShoppingCart();
20: String cartId = usersShoppingCart.GetShoppingCartId();
21: usersShoppingCart.AddItem(cartId, productId, 1);
22: }
23: else
24: {
25: Debug.Fail("ERROR : We should never get to AddToCart.aspx
26: without a ProductId.");
27: throw new Exception("ERROR : It is illegal to load AddToCart.aspx
28: without setting a ProductId.");
29: }
30: Response.Redirect("MyShoppingCart.aspx");
31: }
32: }
33: }
Note that we are retrieving the product to add to the shopping cart from a QueryString parameter and calling the AddItem method of our class.
Assuming no errors are encountered control is passed to the SHoppingCart.aspx page which we will fully implement next. If there should be an error we throw an exception.
Currently we have not yet implemented a global error handler so this exception would go unhandled by our application but we will remedy this shortly.
Note also the use of the statement Debug.Fail() (available via using System.Diagnostics;)
Is the application is running inside the debugger, this method will display a detailed dialog with information about the applications state along with the error message that we specify.
When running in production the Debug.Fail() statement is ignored.
You will note in the code above a call to a method in our shopping cart class names “GetShoppingCartId”.
Add the code to implement the method as follows.
Note that we’ve also added update and checkout buttons and a label where we can display the cart “total”.
[!code-csharpMain]
1: public const string CartId = "TailSpinSpyWorks_CartID";
2:
3: //--------------------------------------------------------------------------------------+
4: public String GetShoppingCartId()
5: {
6: if (Session[CartId] == null)
7: {
8: Session[CartId] = System.Web.HttpContext.Current.Request.IsAuthenticated ?
9: User.Identity.Name : Guid.NewGuid().ToString();
10: }
11: return Session[CartId].ToString();
12: }
We can now add items to our shopping cart but we have not implemented the logic to display the cart after a product has been added.
So, in the MyShoppingCart.aspx page we’ll add an EntityDataSource control and a GridVire control as follows.
[!code-aspxMain]
1: <div id="ShoppingCartTitle" runat="server" class="ContentHead">Shopping Cart</div>
2: <asp:GridView ID="MyList" runat="server" AutoGenerateColumns="False" ShowFooter="True"
3: GridLines="Vertical" CellPadding="4"
4: DataSourceID="EDS_Cart"
5: DataKeyNames="ProductID,UnitCost,Quantity"
6: CssClass="CartListItem">
7: <AlternatingRowStyle CssClass="CartListItemAlt" />
8: <Columns>
9: <asp:BoundField DataField="ProductID" HeaderText="Product ID" ReadOnly="True"
10: SortExpression="ProductID" />
11: <asp:BoundField DataField="ModelNumber" HeaderText="Model Number"
12: SortExpression="ModelNumber" />
13: <asp:BoundField DataField="ModelName" HeaderText="Model Name"
14: SortExpression="ModelName" />
15: <asp:BoundField DataField="UnitCost" HeaderText="Unit Cost" ReadOnly="True"
16: SortExpression="UnitCost"
17: DataFormatString="{0:c}" />
18: <asp:TemplateField>
19: <HeaderTemplate>Quantity</HeaderTemplate>
20: <ItemTemplate>
21: <asp:TextBox ID="PurchaseQuantity" Width="40" runat="server"
22: Text='<%# Bind("Quantity") %>'></asp:TextBox>
23: </ItemTemplate>
24: </asp:TemplateField>
25: <asp:TemplateField>
26: <HeaderTemplate>Item Total</HeaderTemplate>
27: <ItemTemplate>
28: <%# (Convert.ToDouble(Eval("Quantity")) *
29: Convert.ToDouble(Eval("UnitCost")))%>
30: </ItemTemplate>
31: </asp:TemplateField>
32: <asp:TemplateField>
33: <HeaderTemplate>Remove Item</HeaderTemplate>
34: <ItemTemplate>
35: <center>
36: <asp:CheckBox id="Remove" runat="server" />
37: </center>
38: </ItemTemplate>
39: </asp:TemplateField>
40: </Columns>
41: <FooterStyle CssClass="CartListFooter"/>
42: <HeaderStyle CssClass="CartListHead" />
43: </asp:GridView>
44:
45: <div>
46: <strong>
47: <asp:Label ID="LabelTotalText" runat="server" Text="Order Total : ">
48: </asp:Label>
49: <asp:Label CssClass="NormalBold" id="lblTotal" runat="server"
50: EnableViewState="false">
51: </asp:Label>
52: </strong>
53: </div>
54: <br />
55: <asp:imagebutton id="UpdateBtn" runat="server" ImageURL="Styles/Images/update_cart.gif"
56: onclick="UpdateBtn_Click"></asp:imagebutton>
57: <asp:imagebutton id="CheckoutBtn" runat="server"
58: ImageURL="Styles/Images/final_checkout.gif"
59: PostBackUrl="~/CheckOut.aspx">
60: </asp:imagebutton>
61: <asp:EntityDataSource ID="EDS_Cart" runat="server"
62: ConnectionString="name=CommerceEntities"
63: DefaultContainerName="CommerceEntities" EnableFlattening="False"
64: EnableUpdate="True" EntitySetName="ViewCarts"
65: AutoGenerateWhereClause="True" EntityTypeFilter="" Select=""
66: Where="">
67: <WhereParameters>
68: <asp:SessionParameter Name="CartID" DefaultValue="0"
69: SessionField="TailSpinSpyWorks_CartID" />
70: </WhereParameters>
71: </asp:EntityDataSource>
Call up the form in the designer so that you can double click on the Update Cart button and generate the click event handler that is specified in the declaration in the markup.
We’ll implement the details later but doing this will let us build and run our application without errors.
When you run the application and add an item to the shopping cart you will see this.
Note that we have deviated from the “default” grid display by implementing three custom columns.
The first is an Editable, “Bound” field for the Quantity:
[!code-aspxMain]
1: <asp:TemplateField>
2: <HeaderTemplate>Quantity</HeaderTemplate>
3: <ItemTemplate>
4: <asp:TextBox ID="PurchaseQuantity" Width="40" runat="server"
5: Text='<%# Bind("Quantity") %>'></asp:TextBox>
6: </ItemTemplate>
7: </asp:TemplateField>
The next is a “calculated” column that displays the line item total (the item cost times the quantity to be ordered):
[!code-aspxMain]
1: <asp:TemplateField>
2: <HeaderTemplate>Item Total</HeaderTemplate>
3: <ItemTemplate>
4: <%# (Convert.ToDouble(Eval("Quantity")) *
5: Convert.ToDouble(Eval("UnitCost")))%>
6: </ItemTemplate>
7: </asp:TemplateField>
Lastly we have a custom column that contains a CheckBox control that the user will use to indicate that the item should be removed from the shopping chart.
[!code-aspxMain]
1: <asp:TemplateField>
2: <HeaderTemplate>Remove Item</HeaderTemplate>
3: <ItemTemplate>
4: <center>
5: <asp:CheckBox id="Remove" runat="server" />
6: </center>
7: </ItemTemplate>
8: </asp:TemplateField>
As you can see, the Order Total line is empty so let’s add some logic to calculate the Order Total.
We’ll first implement a “GetTotal” method to our MyShoppingCart Class.
In the MyShoppingCart.cs file add the following code.
[!code-csharpMain]
1: //--------------------------------------------------------------------------------------+
2: public decimal GetTotal(string cartID)
3: {
4: using (CommerceEntities db = new CommerceEntities())
5: {
6: decimal cartTotal = 0;
7: try
8: {
9: var myCart = (from c in db.ViewCarts where c.CartID == cartID select c);
10: if (myCart.Count() > 0)
11: {
12: cartTotal = myCart.Sum(od => (decimal)od.Quantity * (decimal)od.UnitCost);
13: }
14: }
15: catch (Exception exp)
16: {
17: throw new Exception("ERROR: Unable to Calculate Order Total - " +
18: exp.Message.ToString(), exp);
19: }
20: return (cartTotal);
21: }
22: }
Then in the Page_Load event handler we’ll can call our GetTotal method. At the same time we’ll add a test to see if the shopping cart is empty and adjust the display accordingly if it is.
Now if the shopping cart is empty we get this:
And if not, we see our total.
However, this page is not yet complete.
We will need additional logic to recalculate the shopping cart by removing items marked for removal and by determining new quantity values as some may have been changed in the grid by the user.
Lets add a “RemoveItem” method to our shopping cart class in MyShoppingCart.cs to handle the case when a user marks an item for removal.
[!code-csharpMain]
1: //------------------------------------------------------------------------------------+
2: public void RemoveItem(string cartID, int productID)
3: {
4: using (CommerceEntities db = new CommerceEntities())
5: {
6: try
7: {
8: var myItem = (from c in db.ShoppingCarts where c.CartID == cartID &&
9: c.ProductID == productID select c).FirstOrDefault();
10: if (myItem != null)
11: {
12: db.DeleteObject(myItem);
13: db.SaveChanges();
14: }
15: }
16: catch (Exception exp)
17: {
18: throw new Exception("ERROR: Unable to Remove Cart Item - " +
19: exp.Message.ToString(), exp);
20: }
21: }
22: }
Now let’s ad a method to handle the circumstance when a user simply changes the quality to be ordered in the GridView.
[!code-csharpMain]
1: //--------------------------------------------------------------------------------------+
2: public void UpdateItem(string cartID, int productID, int quantity)
3: {
4: using (CommerceEntities db = new CommerceEntities())
5: {
6: try
7: {
8: var myItem = (from c in db.ShoppingCarts where c.CartID == cartID &&
9: c.ProductID == productID select c).FirstOrDefault();
10: if (myItem != null)
11: {
12: myItem.Quantity = quantity;
13: db.SaveChanges();
14: }
15: }
16: catch (Exception exp)
17: {
18: throw new Exception("ERROR: Unable to Update Cart Item - " +
19: exp.Message.ToString(), exp);
20: }
21: }
22: }
With the basic Remove and Update features in place we can implement the logic that actually updates the shopping cart in the database. (In MyShoppingCart.cs)
[!code-csharpMain]
1: //-------------------------------------------------------------------------------------+
2: public void UpdateShoppingCartDatabase(String cartId,
3: ShoppingCartUpdates[] CartItemUpdates)
4: {
5: using (CommerceEntities db = new CommerceEntities())
6: {
7: try
8: {
9: int CartItemCOunt = CartItemUpdates.Count();
10: var myCart = (from c in db.ViewCarts where c.CartID == cartId select c);
11: foreach (var cartItem in myCart)
12: {
13: // Iterate through all rows within shopping cart list
14: for (int i = 0; i < CartItemCOunt; i++)
15: {
16: if (cartItem.ProductID == CartItemUpdates[i].ProductId)
17: {
18: if (CartItemUpdates[i].PurchaseQantity < 1 ||
19: CartItemUpdates[i].RemoveItem == true)
20: {
21: RemoveItem(cartId, cartItem.ProductID);
22: }
23: else
24: {
25: UpdateItem(cartId, cartItem.ProductID,
26: CartItemUpdates[i].PurchaseQantity);
27: }
28: }
29: }
30: }
31: }
32: catch (Exception exp)
33: {
34: throw new Exception("ERROR: Unable to Update Cart Database - " +
35: exp.Message.ToString(), exp);
36: }
37: }
38: }
You’ll note that this method expects two parameters. One is the shopping cart Id and the other is an array of objects of user defined type.
So as to minimize the dependency of our logic on user interface specifics, we’ve defined a data structure that we can use to pass the shopping cart items to our code without our method needing to directly access the GridView control.
[!code-csharpMain]
1: public struct ShoppingCartUpdates
2: {
3: public int ProductId;
4: public int PurchaseQantity;
5: public bool RemoveItem;
6: }
In our MyShoppingCart.aspx.cs file we can use this structure in our Update Button Click Event handler as follows. Note that in addition to updating the cart we will update the cart total as well.
[!code-csharpMain]
1: //--------------------------------------------------------------------------------------+
2: protected void UpdateBtn_Click(object sender, ImageClickEventArgs e)
3: {
4: MyShoppingCart usersShoppingCart = new MyShoppingCart();
5: String cartId = usersShoppingCart.GetShoppingCartId();
6:
7: ShoppingCartUpdates[] cartUpdates = new ShoppingCartUpdates[MyList.Rows.Count];
8: for (int i = 0; i < MyList.Rows.Count; i++)
9: {
10: IOrderedDictionary rowValues = new OrderedDictionary();
11: rowValues = GetValues(MyList.Rows[i]);
12: cartUpdates[i].ProductId = Convert.ToInt32(rowValues["ProductID"]);
13: cartUpdates[i].PurchaseQantity = Convert.ToInt32(rowValues["Quantity"]);
14:
15: CheckBox cbRemove = new CheckBox();
16: cbRemove = (CheckBox)MyList.Rows[i].FindControl("Remove");
17: cartUpdates[i].RemoveItem = cbRemove.Checked;
18: }
19:
20: usersShoppingCart.UpdateShoppingCartDatabase(cartId, cartUpdates);
21: MyList.DataBind();
22: lblTotal.Text = String.Format("{0:c}", usersShoppingCart.GetTotal(cartId));
23: }
Note with particular interest this line of code:
[!code-javascriptMain]
1: rowValues = GetValues(MyList.Rows[i]);
GetValues() is a special helper function that we will implement in MyShoppingCart.aspx.cs as follows.
[!code-csharpMain]
1: //--------------------------------------------------------------------------------------+
2: public static IOrderedDictionary GetValues(GridViewRow row)
3: {
4: IOrderedDictionary values = new OrderedDictionary();
5: foreach (DataControlFieldCell cell in row.Cells)
6: {
7: if (cell.Visible)
8: {
9: // Extract values from the cell
10: cell.ContainingField.ExtractValuesFromCell(values, cell, row.RowState, true);
11: }
12: }
13: return values;
14: }
This provides a clean way to access the values of the bound elements in our GridView control. Since our “Remove Item” CheckBox Control is not bound we’ll access it via the FindControl() method.
At this stage in your project’s development we are getting ready to implement the checkout process.
Before doing so let’s use Visual Studio to generate the membership database and add a user to the membership repository.
|