Exemplo n.º 1
0
    public static Cart GetCartFromSession(HttpSessionState Session)
    {
        Cart cart = null;
        int site_id;
        bool logged_in = CartUsers.IsUserLoggedIn(Session);
        string user_id = logged_in ? CartUsers.GetUserName(Session) : "";
        if (Session[Constants.SessionKeys.SITE_ID] != null)
        {
            if (Int32.TryParse((string)Session[Constants.SessionKeys.SITE_ID], out site_id) == false)
            {
                throw new CartException("Could not find SiteID in current session");
            }
        }
        else
        {
            throw new CartException("Could not find SiteID in current session");
        }

        // This is a three step process
        // We do this because the current context of the shopping cart, should always override the saved context of the shopping cart.
        // This makes most sense in this scenario:
        /* So say you were browsing the site without logging in, and you've added a bunch of items to your cart.
           Now, you don't hit checkout or anything, but instead decide to log in to your account you remember you had.
           Should the cart you just created override any existing (saved) cart in the user account? */

        // 0. If a user is logged in, and the current session doesn't have any items in it, and a saved session exists, use it.
        if (logged_in)
        {
            cart = Cart.GetCartByUserID(site_id, Session.SessionID);
            if (cart != null && cart.IsLoaded && cart.HasItems == false)
            {
                cart = Cart.GetCartByUserID(site_id, user_id);
                if (cart != null && cart.IsLoaded)
                {
                    return cart;
                }
            }
        }

        // 1. If one exists in the current session, and it actually has items in it, use it. In this case, if the username has not been updated, update it.
        cart = Cart.GetCartByUserID(site_id, Session.SessionID);
        if (cart != null && cart.IsLoaded)
        {
            if (logged_in && cart.UserId == Session.SessionID)
            {
                CartDB db = new CartDB();
                db.CartUpdateUserId(cart.CartId, user_id);
            }
            cart.Refresh();
            return cart;
        }

        // 2. If this is not the case, try loading from the user id.
        if (logged_in)
        {
            cart = Cart.GetCartByUserID(site_id, user_id);
            if (cart != null && cart.IsLoaded)
            {
                return cart;
            }
        }

        // 3. If we still do not have one, just create a new one. If logged in, use the current username, if not, use the session id
        cart = Cart.CreateNew(site_id, logged_in ? user_id : Session.SessionID);
        if (cart != null && cart.IsLoaded)
        {
            return cart;
        }

        throw new CartException("Could not retrieve a cart from the current session");
    }