Link to home
Start Free TrialLog in
Avatar of ukerandi
ukerandiFlag for United Kingdom of Great Britain and Northern Ireland

asked on

C# ASP.net Shopping cart

Using examples I crated shopping cart,
But  issue is if i add any products , its will appear all the other client web browser.
for that i need to add unique Cart identifier.
Could you please show me where i have to use that code i already attached my code
using System.Collections.Generic;
using System.Web;

/**
 * The ShoppingCart class
 * 
 * Holds the items that are in the cart and provides methods for their manipulation
 */
public class ShoppingCart
{
    #region Properties

    public List<CartItem> Items { get; private set; }

    #endregion

    #region Singleton Implementation

    // Readonly properties can only be set in initialization or in a constructor
    public static readonly ShoppingCart Instance;
    public const string CartSessionKey = "CartId";
    // The static constructor is called as soon as the class is loaded into memory
    static ShoppingCart()
    {
        // If the cart is not in the session, create one and put it there
        // Otherwise, get it from the session
        if (HttpContext.Current.Session[CartSessionKey] == null)
        {
            Instance = new ShoppingCart();
            Instance.Items = new List<CartItem>();
            HttpContext.Current.Session[CartSessionKey] = Instance;
        }
        else
        {
            Instance = (ShoppingCart)HttpContext.Current.Session["ASPNETShoppingCart"];
        }
    }

    // A protected constructor ensures that an object can't be created from outside
    protected ShoppingCart() { }

    #endregion

    #region Item Modification Methods
    /**
	 * AddItem() - Adds an item to the shopping 
	 */
    public void AddItem(int productId)
    {
        // Create a new item to add to the cart
        CartItem newItem = new CartItem(productId);

        // If this item already exists in our list of items, increase the quantity
        // Otherwise, add the new item to the list
        if (Items.Contains(newItem))
        {
            foreach (CartItem item in Items)
            {
                if (item.Equals(newItem))
                {
                    item.Quantity++;
                    return;
                }
            }
        }
        else
        {
            newItem.Quantity = 1;
            Items.Add(newItem);
        }
    }

    /**
     * SetItemQuantity() - Changes the quantity of an item in the cart
     */
    public void SetItemQuantity(int productId, int quantity)
    {
        // If we are setting the quantity to 0, remove the item entirely
        if (quantity == 0)
        {
            RemoveItem(productId);
            return;
        }

        // Find the item and update the quantity
        CartItem updatedItem = new CartItem(productId);

        foreach (CartItem item in Items)
        {
            if (item.Equals(updatedItem))
            {
                item.Quantity = quantity;
                return;
            }
        }
    }

    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();
    }
    
    /**
     * RemoveItem() - Removes an item from the shopping cart
     */
    public void RemoveItem(int productId)
    {
        CartItem removedItem = new CartItem(productId);
        Items.Remove(removedItem);
    }
    #endregion

    #region Reporting Methods
    /**
	 * GetSubTotal() - returns the total price of all of the items
	 *                 before tax, shipping, etc.
	 */
    public decimal GetSubTotal()
    {
        decimal subTotal = 0;
        foreach (CartItem item in Items)
            subTotal += item.TotalPrice;

        return subTotal;
    }
    #endregion
}

Open in new window

Avatar of kaufmed
kaufmed
Flag of United States of America image

Why are you using a singleton pattern for something that should be configured per user?
Avatar of ukerandi

ASKER

I used becuase example used "singleton pattern", Shopping cart is working well, only issue
is how to give user to unique number,
I need to add some customer unique key for following method
public void AddItem(int productId)
    {
        // Create a new item to add to the cart
        CartItem newItem = new CartItem(productId);

        // If this item already exists in our list of items, increase the quantity
        // Otherwise, add the new item to the list
        if (Items.Contains(newItem))
        {
            foreach (CartItem item in Items)
            {
                if (item.Equals(newItem))
                {
                    item.Quantity++;
                    return;
                }
            }
        }
        else
        {
            newItem.Quantity = 1;
            Items.Add(newItem);
        }
    }

Open in new window

or someone let me know better way with example
ASKER CERTIFIED SOLUTION
Avatar of lenordiste
lenordiste
Flag of France image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I just googled your code and found many related posts. There are two ways to solve the issue (the first one is similar to mine so even though i did not test it, it will probably work):
http://stackoverflow.com/questions/7779906/static-asp-net-session-for-all-users
http://stackoverflow.com/questions/10250288/c-sharp-shopping-cart
lenordiste : are Excellent programmer
if you could explain little bit more how you did i'll appreciated
Excellent, Great i have no words to thank you