0

EDIT: I'm sorry for multiple posts, I couldn't delete or modify the previous one.

Hey guys, ASP.net noob here (several years since I've worked with anything not opensource-related). I'm attempting to pretty much copy and modify an ecommerce site tutorial which is driven by my already created MS SQL database (running on sql server 2008r2).

I've based my project on the official ASP.net tutorial for Wingtip Toys, located here: http://www.asp.net/web-forms/tutorials/aspnet-45/getting-started-with-aspnet-45-web-forms/shopping-cart (this particular link is the shopping cart section I'm working on).

I've modified a few parts of this tutorial to work with my data, namely, I've change the portion of ShoppingCartActions.cs 'AddToCart' to use a decimal instead of an integer for the 'id' parameter (too large of a number to reasonably use an int type), that way I can change my id (acquired from URL parameter) to a string and compare it with my database entry (a string) to then find the correct row item.

Here is the main portion of the code in question...
ShoppingCartActions.cs (certain portions)

public void AddToCart(decimal id)
        {
            // Retrieve the product from the database.           
            ShoppingCartId = GetCartId();

            var cartItem = _db.ShoppingCartItems.SingleOrDefault(
                c => c.CartId == ShoppingCartId
                && c.ProductId == id);
            if (cartItem == null)
            {
                var idHold = id.ToString();
                // Create a new cart item if no cart item exists.                 
                cartItem = new cartItem
                {
                    ItemId = Guid.NewGuid().ToString(),
                    ProductId = id,
                    CartId = ShoppingCartId,
                    Product = _db.Products.SingleOrDefault(
                     p => p.generatedID == idHold),
                    Quantity = 1,
                    DateCreated = DateTime.Now
                };

                _db.ShoppingCartItems.Add(cartItem);
            }
            else
            {
                // If the item does exist in the cart,                  
                // then add one to the quantity.                 
                cartItem.Quantity++;
            }
            _db.SaveChanges();
        }

    ...

    public string GetCartId()
    {
        if (HttpContext.Current.Session[CartSessionKey] == null)
        {
            if (!string.IsNullOrWhiteSpace(HttpContext.Current.User.Identity.Name))
            {
                HttpContext.Current.Session[CartSessionKey] = HttpContext.Current.User.Identity.Name;
            }
            else
            {
                // Generate a new random GUID using System.Guid class.     
                Guid tempCartId = Guid.NewGuid();
                HttpContext.Current.Session[CartSessionKey] = tempCartId.ToString();
            }
        }
        return HttpContext.Current.Session[CartSessionKey].ToString();
    }

...related files...

cartItem.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace projectName.Models
{
    public class cartItem
    {
        [Key]
        public string ItemId { get; set; }
        public string CartId { get; set; }
        public int Quantity { get; set; }
        public System.DateTime DateCreated { get; set; }
        public decimal ProductId { get; set; }
        public virtual Tran Product { get; set; }
    }
}

productContext.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace projectName.Models
{
    public class productContext : DbContext
    {
        public productContext()
            : base("projectName")
        {
        }
        /* Products is a Tran string element, check ProductID sub-element in shoppingcartactions.cs  */
        public DbSet<Tran> Products { get; set; }
        public DbSet<cartItem> ShoppingCartItems { get; set; }
    }
}

AddToCart.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Diagnostics;
using projectName.Logic;
namespace projectName
{
    public partial class AddToCart : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string rawId = Request.QueryString["ProductID"];
            decimal productId;
            if (!String.IsNullOrEmpty(rawId) && decimal.TryParse(rawId, out productId))
            {
                using (ShoppingCartActions usersShoppingCart = new ShoppingCartActions())
                {
                    usersShoppingCart.AddToCart(Decimal.Parse(rawId));
                }
            }
            else
            {
                Debug.Fail("ERROR : We should never get to AddToCart.aspx without a ProductId.");
                throw new Exception("ERROR : It is illegal to load AddToCart.aspx without setting a ProductId.");
            }
            Response.Redirect("ShoppingCart.aspx");
        }
    }
}

Everything seems to work fine until I attempt to save the newly created cartItem via the line in ShoppingCartActions.cs

_db.SaveChanges();

When I get to the point on the website that I add a new cartitem and display it (click add to cart), I get an error saying "An error occurred while updating the entries. See the inner exception for details"... the inner exception says "Arithmetic overflow error converting expression to data type int" pointing to this line of code

Let me know if there is anything else I can provide either file or concept related.. any ideas are much appreciated (been searching and playing for days)!

Edited by PsychicTide

1
Contributor
2
Replies
35
Views
3 Years
Discussion Span
Last Post by PsychicTide
0

So I've attempted to recreate the tutorials files from the bottom and recreate the same idea with my own personal build up. and I'm getting an entirely new error now... maybe you guys can help point me in the right direction.

I'll just post the files that are being used and where the current error is occurring.

basketItem.cs (model class)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace projectName.Models
{
    public class basketItem
    {
        [Key]
        public string cartId { get; set; }
        public string itemId { get; set; }
        public int itemQuantity { get; set; }
        public double itemPrice { get; set; }
        public virtual Tran product { get; set; }
    }
}

basketItemContext.cs (model class)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;

namespace projectName.Models
{
    public class basketItemContext : DbContext
    {
        public basketItemContext()
            : base("projectName")
        {
        }

        public DbSet<Tran> Products { get; set; }
        public DbSet<basketItem> ShoppingCartItems { get; set; }
    }
}

addToBasket.aspx.cs (code behind for blank addToBasket.aspx web form)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Diagnostics;
using projectName.Models;

namespace projectName
{
    public partial class addToBasket : System.Web.UI.Page
    {
        private basketItemContext _db = new basketItemContext();
        public const string CartSessionKey = "CartId";
        public string shoppingCartId { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            shoppingCartId = GetCartId();
            string itemID = Request.QueryString["itemID"];
            double itemPrice = 0.00; /* random zero double for testing purposes */

            var cartItem = _db.ShoppingCartItems.SingleOrDefault(
                c => c.cartId == shoppingCartId
                && c.itemId == itemID);
            if (cartItem == null)
            {
                cartItem = new basketItem
                {
                    cartId = shoppingCartId,
                    itemId = itemID,
                    itemQuantity = 1,
                    itemPrice = itemPrice
                };
                _db.ShoppingCartItems.Add(cartItem);
            }
            else
            {
                // If the item does exist in the cart,
                // then add one to the quantity.                 
                cartItem.itemQuantity++;
            }
            Response.Redirect("Cart.aspx");
        }

        public string GetCartId()
        {
            if (HttpContext.Current.Session[CartSessionKey] == null)
            {
                if (!string.IsNullOrWhiteSpace(HttpContext.Current.User.Identity.Name))
                {
                    HttpContext.Current.Session[CartSessionKey] = HttpContext.Current.User.Identity.Name;
                }
                else
                {
                    // Generate a new random GUID using System.Guid class.     
                    Guid tempCartId = Guid.NewGuid();
                    HttpContext.Current.Session[CartSessionKey] = tempCartId.ToString();
                }
            }
            return HttpContext.Current.Session[CartSessionKey].ToString();
        }

        public List<basketItem> GetCartItems()
        {
            shoppingCartId = GetCartId();
            return _db.ShoppingCartItems.Where(
                c => c.cartId == shoppingCartId).ToList();
        }
    }
}

cart.aspx (web form using master.site)
(will be modified once I get to this point)

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Cart.aspx.cs" Inherits="projectName.Cart" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
    <div id="ShoppingCartTitle" runat="server" class="ContentHead"><h1>Shopping Cart</h1></div>
    <asp:GridView ID="CartList" runat="server" AutoGenerateColumns="False" ShowFooter="True" GridLines="Vertical" CellPadding="4"
        ItemType="projectName.Models.basketItem" SelectMethod="GetShoppingCartItems" 
        CssClass="table table-striped table-bordered" >   
        <Columns>
        <asp:BoundField DataField="ProductID" HeaderText="ID" SortExpression="ProductID" />        
        <asp:BoundField DataField="Product.ProductName" HeaderText="Name" />        
        <asp:BoundField DataField="Product.UnitPrice" HeaderText="Price (each)" DataFormatString="{0:c}"/>     
        <asp:TemplateField   HeaderText="Quantity">            
                <ItemTemplate>
                    <asp:TextBox ID="PurchaseQuantity" Width="40" runat="server" Text="<%#: Item.itemQuantity %>"></asp:TextBox> 
                </ItemTemplate>        
        </asp:TemplateField>    
        <asp:TemplateField HeaderText="Item Total">            
                <ItemTemplate>
                    <%#: String.Format("{0:c}", ((Convert.ToDouble(Item.itemQuantity)) *  Convert.ToDouble(Item.product.Trs_Price)))%>
                </ItemTemplate>        
        </asp:TemplateField> 
        <asp:TemplateField HeaderText="Remove Item">            
                <ItemTemplate>
                    <asp:CheckBox id="Remove" runat="server"></asp:CheckBox>
                </ItemTemplate>        
        </asp:TemplateField>    
        </Columns>    
    </asp:GridView>
    <div>
        <p></p>
        <strong>
            <asp:Label ID="LabelTotalText" runat="server" Text="Order Total: "></asp:Label>
            <asp:Label ID="lblTotal" runat="server" EnableViewState="false"></asp:Label>
        </strong> 
    </div>
    <br />
</asp:Content>

cart.aspx.cs (code behind for cart.aspx)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using projectName.Models;

namespace projectName
{
    public partial class Cart : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        public List<basketItem> GetShoppingCartItems()
        {
            addToBasket actions = new addToBasket();
            return actions.GetCartItems();
        }
    }
}

I use a link on my products page like so access the addToBasket.aspx which will eventually end up at cart.aspx after redirects

<a href="/addToBasket.aspx?itemID=<%# Eval("GeneratedID") %>">

The error I'm getting occurs in addToBasket.aspx.cs on the lines (these lines get the current cartItem [if there is one already in the basket of the same ID, else null] via comparing the itemIDs)

var cartItem = _db.ShoppingCartItems.SingleOrDefault(
                c => c.cartId == shoppingCartId
                && c.itemId == itemID);

The error is an innerexception which says "{"Invalid object name 'dbo.basketItems'."}"

Any ideas or suggestions are very much appreciated!

Edited by PsychicTide

0

Don't mean to be a bother, but just trying to bump this thread a bit. If anyone has any idea on how I can create a simple shopping basket through asp.net/c# I'm open for any idea. The next thought I had was to just use arrays/lists in cookies, but there is always potential for abuse of such things. Guess if I just passed along item numbers and quantities I would then do the backend by itself on submit reducing injection/modification possibilities.

Again, any ideas are much appreciated, would be nice to use what I already have written ,but if not that's ok as well, the end result is all that matters.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.