Part 6: ASP.NET Membership
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 6 adds ASP.NET Membership.
Working with ASP.NET Membership
Click Security
Make sure that we are using forms authentication.
Use the “Create User” link to create a couple of users.
When done, refer to the Solution Explorer window and refresh the view.
Note that the ASPNETDB.MDF fine has been created. This file contains the tables to support the core ASP.NET services like membership.
Now we can begin implementing the checkout process.
Begin by creating a CheckOut.aspx page.
The CheckOut.aspx page should only be available to users who are logged in so we will restrict access to logged in users and redirect users who are not logged in to the LogIn page.
To do this we’ll add the following to the configuration section of our web.config file.
[!code-xmlMain]
1: <location path="Checkout.aspx">
2: <system.web>
3: <authorization>
4: <deny users="?" />
5: </authorization>
6: </system.web>
7: </location>
The template for ASP.NET Web Forms applications automatically added an authentication section to our web.config file and established the default login page.
[!code-xmlMain]
1: <authentication mode="Forms">
2: <forms loginUrl="~/Account/Login.aspx" timeout="2880" />
3: </authentication>
We must modify the Login.aspx code behind file to migrate an anonymous shopping cart when the user logs in. Change the Page_Load event as follows.
[!code-csharpMain]
1: using System.Web.Security;
2:
3: protected void Page_Load(object sender, EventArgs e)
4: {
5: // If the user is not submitting their credentials
6: // save refferer
7: if (!Page.IsPostBack)
8: {
9: if (Page.Request.UrlReferrer != null)
10: {
11: Session["LoginReferrer"] = Page.Request.UrlReferrer.ToString();
12: }
13: }
14:
15: // User is logged in so log them out.
16: if (User.Identity.IsAuthenticated)
17: {
18: FormsAuthentication.SignOut();
19: Response.Redirect("~/");
20: }
21: }
Then add a “LoggedIn” event handler like this to set the session name to the newly logged in user and change the temporary session id in the shopping cart to that of the user by calling the MigrateCart method in our MyShoppingCart class. (Implemented in the .cs file)
[!code-csharpMain]
1: protected void LoginUser_LoggedIn(object sender, EventArgs e)
2: {
3: MyShoppingCart usersShoppingCart = new MyShoppingCart();
4: String cartId = usersShoppingCart.GetShoppingCartId();
5: usersShoppingCart.MigrateCart(cartId, LoginUser.UserName);
6:
7: if(Session["LoginReferrer"] != null)
8: {
9: Response.Redirect(Session["LoginReferrer"].ToString());
10: }
11:
12: Session["UserName"] = LoginUser.UserName;
13: }
Implement the MigrateCart() method like this.
[!code-csharpMain]
1: //--------------------------------------------------------------------------------------+
2: public void MigrateCart(String oldCartId, String UserName)
3: {
4: using (CommerceEntities db = new CommerceEntities())
5: {
6: try
7: {
8: var myShoppingCart = from cart in db.ShoppingCarts
9: where cart.CartID == oldCartId
10: select cart;
11:
12: foreach (ShoppingCart item in myShoppingCart)
13: {
14: item.CartID = UserName;
15: }
16: db.SaveChanges();
17: Session[CartId] = UserName;
18: }
19: catch (Exception exp)
20: {
21: throw new Exception("ERROR: Unable to Migrate Shopping Cart - " +
22: exp.Message.ToString(), exp);
23: }
24: }
25: }
In checkout.aspx we’ll use an EntityDataSource and a GridView in our check out page much as we did in our shopping cart page.
[!code-aspxMain]
1: <div id="CheckOutHeader" runat="server" class="ContentHead">
2: Review and Submit Your Order
3: </div>
4: <span id="Message" runat="server"><br />
5: <asp:Label ID="LabelCartHeader" runat="server"
6: Text="Please check all the information below to be sure it's correct.">
7: </asp:Label>
8: </span><br />
9: <asp:GridView ID="MyList" runat="server" AutoGenerateColumns="False"
10: DataKeyNames="ProductID,UnitCost,Quantity"
11: DataSourceID="EDS_Cart"
12: CellPadding="4" GridLines="Vertical" CssClass="CartListItem"
13: onrowdatabound="MyList_RowDataBound" ShowFooter="True">
14: <AlternatingRowStyle CssClass="CartListItemAlt" />
15: <Columns>
16: <asp:BoundField DataField="ProductID" HeaderText="Product ID" ReadOnly="True"
17: SortExpression="ProductID" />
18: <asp:BoundField DataField="ModelNumber" HeaderText="Model Number"
19: SortExpression="ModelNumber" />
20: <asp:BoundField DataField="ModelName" HeaderText="Model Name"
21: SortExpression="ModelName" />
22: <asp:BoundField DataField="UnitCost" HeaderText="Unit Cost" ReadOnly="True"
23: SortExpression="UnitCost" DataFormatString="{0:c}" />
24: <asp:BoundField DataField="Quantity" HeaderText="Quantity" ReadOnly="True"
25: SortExpression="Quantity" />
26: <asp:TemplateField>
27: <HeaderTemplate>Item Total</HeaderTemplate>
28: <ItemTemplate>
29: <%# (Convert.ToDouble(Eval("Quantity")) * Convert.ToDouble(Eval("UnitCost")))%>
30: </ItemTemplate>
31: </asp:TemplateField>
32: </Columns>
33: <FooterStyle CssClass="CartListFooter"/>
34: <HeaderStyle CssClass="CartListHead" />
35: </asp:GridView>
36:
37: <br />
38: <asp:imagebutton id="CheckoutBtn" runat="server" ImageURL="Styles/Images/submit.gif"
39: onclick="CheckoutBtn_Click">
40: </asp:imagebutton>
41: <asp:EntityDataSource ID="EDS_Cart" runat="server"
42: ConnectionString="name=CommerceEntities"
43: DefaultContainerName="CommerceEntities"
44: EnableFlattening="False"
45: EnableUpdate="True"
46: EntitySetName="ViewCarts"
47: AutoGenerateWhereClause="True"
48: EntityTypeFilter=""
49: Select="" Where="">
50: <WhereParameters>
51: <asp:SessionParameter Name="CartID" DefaultValue="0"
52: SessionField="TailSpinSpyWorks_CartID" />
53: </WhereParameters>
54: </asp:EntityDataSource>
Note that our GridView control specifies an “ondatabound” event handler named MyList_RowDataBound so let’s implement that event handler like this.
[!code-csharpMain]
1: decimal _CartTotal = 0;
2:
3: //--------------------------------------------------------------------------------------+
4: protected void MyList_RowDataBound(object sender, GridViewRowEventArgs e)
5: {
6: if (e.Row.RowType == DataControlRowType.DataRow)
7: {
8: TailspinSpyworks.Data_Access.ViewCart myCart = new Data_Access.ViewCart();
9: myCart = (TailspinSpyworks.Data_Access.ViewCart)e.Row.DataItem;
10: _CartTotal += myCart.UnitCost * myCart.Quantity;
11: }
12: else if (e.Row.RowType == DataControlRowType.Footer)
13: {
14: if (_CartTotal > 0)
15: {
16: CheckOutHeader.InnerText = "Review and Submit Your Order";
17: LabelCartHeader.Text = "Please check all the information below to be sure
18: it's correct.";
19: CheckoutBtn.Visible = true;
20: e.Row.Cells[5].Text = "Total: " + _CartTotal.ToString("C");
21: }
22: }
23: }
This method keeps a running total of the shopping cart as each row is bound and updates the bottom row of the GridView.
At this stage we have implemented a “review” presentation of the order to be placed.
Let’s handle an empty cart scenario by adding a few lines of code to our Page_Load event:
[!code-csharpMain]
1: protected void Page_Load(object sender, EventArgs e)
2: {
3: CheckOutHeader.InnerText = "Your Shopping Cart is Empty";
4: LabelCartHeader.Text = "";
5: CheckoutBtn.Visible = false;
6: }
When the user clicks on the “Submit” button we will execute the following code in the Submit Button Click Event handler.
[!code-csharpMain]
1: protected void CheckoutBtn_Click(object sender, ImageClickEventArgs e)
2: {
3: MyShoppingCart usersShoppingCart = new MyShoppingCart();
4: if (usersShoppingCart.SubmitOrder(User.Identity.Name) == true)
5: {
6: CheckOutHeader.InnerText = "Thank You - Your Order is Complete.";
7: Message.Visible = false;
8: CheckoutBtn.Visible = false;
9: }
10: else
11: {
12: CheckOutHeader.InnerText = "Order Submission Failed - Please try again. ";
13: }
14: }
The “meat” of the order submission process is to be implemented in the SubmitOrder() method of our MyShoppingCart class.
SubmitOrder will:
- Take all the line items in the shopping cart and use them to create a new Order Record and the associated OrderDetails records.
- Calculate Shipping Date.
- Clear the shopping cart.
[!code-csharpMain]
1: //--------------------------------------------------------------------------------------+
2: public bool SubmitOrder(string UserName)
3: {
4: using (CommerceEntities db = new CommerceEntities())
5: {
6: try
7: {
8: //------------------------------------------------------------------------+
9: // Add New Order Record |
10: //------------------------------------------------------------------------+
11: Order newOrder = new Order();
12: newOrder.CustomerName = UserName;
13: newOrder.OrderDate = DateTime.Now;
14: newOrder.ShipDate = CalculateShipDate();
15: db.Orders.AddObject(newOrder);
16: db.SaveChanges();
17:
18: //------------------------------------------------------------------------+
19: // Create a new OderDetail Record for each item in the Shopping Cart |
20: //------------------------------------------------------------------------+
21: String cartId = GetShoppingCartId();
22: var myCart = (from c in db.ViewCarts where c.CartID == cartId select c);
23: foreach (ViewCart item in myCart)
24: {
25: int i = 0;
26: if (i < 1)
27: {
28: OrderDetail od = new OrderDetail();
29: od.OrderID = newOrder.OrderID;
30: od.ProductID = item.ProductID;
31: od.Quantity = item.Quantity;
32: od.UnitCost = item.UnitCost;
33: db.OrderDetails.AddObject(od);
34: i++;
35: }
36:
37: var myItem = (from c in db.ShoppingCarts where c.CartID == item.CartID &&
38: c.ProductID == item.ProductID select c).FirstOrDefault();
39: if (myItem != null)
40: {
41: db.DeleteObject(myItem);
42: }
43: }
44: db.SaveChanges();
45: }
46: catch (Exception exp)
47: {
48: throw new Exception("ERROR: Unable to Submit Order - " + exp.Message.ToString(),
49: exp);
50: }
51: }
52: return(true);
53: }
For the purposes of this sample application we’ll calculate a ship date by simply adding two days to the current date.
[!code-csharpMain]
1: //--------------------------------------------------------------------------------------+
2: DateTime CalculateShipDate()
3: {
4: DateTime shipDate = DateTime.Now.AddDays(2);
5: return (shipDate);
6: }
Running the application now will permit us to test the shopping process from start to finish.
|