Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

C# ASP.net Shopping cart

Posted on 2013-05-20
6
Medium Priority
?
1,716 Views
Last Modified: 2013-05-21
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

0
Comment
Question by:ukerandi
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
6 Comments
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 39183291
Why are you using a singleton pattern for something that should be configured per user?
0
 
LVL 10

Author Comment

by:ukerandi
ID: 39183677
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
0
 
LVL 11

Accepted Solution

by:
lenordiste earned 2000 total points
ID: 39183999
kaufmed is right, the singleton pattern does not make any sense in this context. Either make it non static or find a better working shopping cart example.

Anyhow, you can try replacing this:
    // 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"];
        }
    }

Open in new window


with the following code to have one shopping cart per session (and hence per user):
    // Readonly properties can only be set in initialization or in a constructor
    public const string CartSessionKey = "CartId";
    public static ShoppingCart Instance
    {
      get{
        // 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)
        {
            var instance = new ShoppingCart();
            instance.Items = new List<CartItem>();
            HttpContext.Current.Session[CartSessionKey] = instance;
            return instance;
        }
        else
        {
            return (ShoppingCart)HttpContext.Current.Session[CartSessionKey];
        }
      }
    }

Open in new window


This should be working, even though I find the example code a bit "weird" :-) Cheers.
0
NEW Veeam Agent for Microsoft Windows

Backup and recover physical and cloud-based servers and workstations, as well as endpoint devices that belong to remote users. Avoid downtime and data loss quickly and easily for Windows-based physical or public cloud-based workloads!

 
LVL 11

Expert Comment

by:lenordiste
ID: 39184024
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
0
 
LVL 10

Author Comment

by:ukerandi
ID: 39184374
lenordiste : are Excellent programmer
if you could explain little bit more how you did i'll appreciated
0
 
LVL 10

Author Closing Comment

by:ukerandi
ID: 39184381
Excellent, Great i have no words to thank you
0

Featured Post

Get free NFR key for Veeam Availability Suite 9.5

Veeam is happy to provide a free NFR license (1 year, 2 sockets) to all certified IT Pros. The license allows for the non-production use of Veeam Availability Suite v9.5 in your home lab, without any feature limitations. It works for both VMware and Hyper-V environments

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
Video by: ITPro.TV
In this episode Don builds upon the troubleshooting techniques by demonstrating how to properly monitor a vSphere deployment to detect problems before they occur. He begins the show using tools found within the vSphere suite as ends the show demonst…
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…

636 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question