Example #1
0
        public void Can_Remove_Line()
        {
            // Arrange - create some test products
            PRODUCT p1 = new PRODUCT {
                ProductId = 1, Name = "P1"
            };
            PRODUCT p2 = new PRODUCT {
                ProductId = 2, Name = "P2"
            };
            PRODUCT p3 = new PRODUCT {
                ProductId = 3, Name = "P3"
            };
            // Arrange - create a new cart
            CART target = new CART();

            // Arrange - add some products to the cart
            target.AddItem(p1, 1);
            target.AddItem(p2, 3);
            target.AddItem(p3, 5);
            target.AddItem(p2, 1);
            // Act
            target.RemoveLine(p2);
            // Assert
            Assert.AreEqual(target.Lines.Where(c => c.Product == p1).Count(), 1);
            Assert.AreEqual(target.Lines.Where(c => c.Product == p2).Count(), 0);
            Assert.AreEqual(target.Lines.Where(c => c.Product == p3).Count(), 1);
            Assert.AreEqual(target.Lines.Count(), 2);
        }
Example #2
0
        public int AddToCart(int pid, int uid)
        {
            if (uid == -1)
            {
                return(-1);
            }
            PRODUCTS product = db.PRODUCTS.Find(pid);


            if (product == null)
            {
                return(4004);
            }

            CART chk     = db.CARTs.Where(c => c.UserId == uid && c.ProductId == pid).FirstOrDefault();
            CART cartobj = new CART();

            if (chk == null)
            {
                cartobj.UserId       = uid;
                cartobj.ProductId    = product.ProductId;
                cartobj.ItemQuantity = 1;
                db.CARTs.Add(cartobj);
                db.SaveChanges();
                return(2000);
            }
            else
            {
                chk.ItemQuantity += 1;

                db.Entry(chk).State = EntityState.Modified;
                db.SaveChanges();
                return(2001);
            }
        }
 public void LoadCart(CART cart)
 {
     this.grd_CART.DataSource = cart;
     this.grd_CART.DataBind();
     this.grd_CART.FooterRow.Cells[3].Text = "Tổng tiền";
     this.grd_CART.FooterRow.Cells[4].Text = cart.Total().ToString();
 }
Example #4
0
    protected void btn_CART_Click(object sender, EventArgs e)
    {
        HttpCookie CookieUser = Request.Cookies["USERNAMR"];
        HttpCookie CookiePass = Request.Cookies["PASSWORD"];

        if (CookiePass != null && CookieUser != null)
        {
            CART cart;
            Session.Timeout = 1;
            if (Session["CART"] != null)
            {
                cart = (CART)Session["CART"];
            }
            else
            {
                cart = new CART();
            }
            cart.AddCart(Convert.ToInt16(tbSANPHAM.Rows[0]["MASP"].ToString()),
                         tbSANPHAM.Rows[0]["TENSP"].ToString(),
                         Convert.ToInt16(drl_SOLUONG.SelectedValue),
                         Convert.ToDouble(tbSANPHAM.Rows[0]["DONGIA"].ToString()),
                         tbSANPHAM.Rows[0]["HINHANH"].ToString());
            Session["CART"] = cart;
            Response.Redirect("pageCART.aspx");
        }
    }
Example #5
0
        public HttpResponseMessage editEmployeeById(int id, [FromBody] CART cart)
        {
            try
            {
                var cartToEdit = db.CART.Where(x => x.Id == id).FirstOrDefault();
                var product    = db.PRODUCT.Where(u => u.productId == cartToEdit.productId).FirstOrDefault();

                if (cartToEdit == null)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Cart Product with id " + id.ToString() + " not found"));
                }
                else
                {
                    cartToEdit.quantity = cart.quantity;
                    cartToEdit.subTotal = cart.quantity * product.productPrice;

                    db.SaveChanges();

                    return(Request.CreateResponse(HttpStatusCode.OK, cartToEdit));
                }
            }
            catch (Exception ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex));
            }
        }
Example #6
0
        public ActionResult Create([Bind(Include = "ProdID,CatID,ProdName,Price")] PRODUCT pRODUCT)
        {
            if (ModelState.IsValid)
            {
                var user  = @Session["userName"];
                var id    = pRODUCT.ProdID;
                var price = pRODUCT.Price;
                var cat   = pRODUCT.CatID;


                CART c = new CART();
                c.USERNAME = user.ToString();
                c.ProdID   = id;
                c.Price    = price;
                c.Cat      = cat;

                db.CARTs.Add(c);


                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.CatID = new SelectList(db.CATEGORies, "CatID", "CatName", pRODUCT.CatID);
            return(View("Index", "CARTs"));
        }
Example #7
0
        public JsonResult AddToCart(ItemEntry VE, int itemcd)
        {
            try
            {
                Random rnd = new Random();
                int    id  = rnd.Next(0, 9999);

                int uid    = Convert.ToInt32(Session["USER_ID"].ToString());
                var cartid = DB.CART.Where(a => a.USER_ID == uid && a.STATUS == "A").Select(b => b.CART_ID).ToList();
                if (cartid != null && cartid.Count() > 0)
                {
                    int cart_id = cartid[0];
                    var Q       = DB.CART_ITEM.Where(M => M.CART_ID == cart_id && M.ITEM_CD == itemcd).FirstOrDefault();
                    if (Q != null)
                    {
                        var max_qnty = Q.QNTY;
                        Q.ITEM_CD = itemcd;
                        Q.QNTY    = max_qnty + 1;
                        DB.SaveChanges();
                    }
                    else
                    {
                        CART_ITEM CARTITEM = new CART_ITEM();
                        CARTITEM.CI_ID   = id;
                        CARTITEM.CART_ID = cart_id;
                        CARTITEM.ITEM_CD = itemcd;
                        CARTITEM.QNTY    = 1;
                        DB.CART_ITEM.Add(CARTITEM);
                        DB.SaveChanges();
                    }
                }
                else
                {
                    CART CART = new CART();
                    CART.CART_ID   = id;
                    CART.USER_ID   = Convert.ToInt32(Session["USER_ID"].ToString());
                    CART.STATUS    = "A";
                    CART.CART_TIME = System.DateTime.Now;
                    DB.CART.Add(CART);
                    DB.SaveChanges();

                    CART_ITEM CARTITEM = new CART_ITEM();
                    CARTITEM.CI_ID   = id;
                    CARTITEM.CART_ID = CART.CART_ID;
                    CARTITEM.ITEM_CD = itemcd;
                    CARTITEM.QNTY    = 1;
                    DB.CART_ITEM.Add(CARTITEM);
                    DB.SaveChanges();
                }



                return(Json("Success", JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                return(Json(ex.Message + ex.InnerException, JsonRequestBehavior.AllowGet));
            }
        }
 protected void Page_Load(object sender, EventArgs e)
 {
     if (Session["CART"] != null && !IsPostBack)
     {
         cart = (CART)Session["CART"];
         LoadCart(cart);
     }
 }
        public ActionResult DeleteConfirmed(string id)
        {
            CART cART = db.CARTs.Find(id);

            db.CARTs.Remove(cART);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Example #10
0
 // GET: Cart
 public ViewResult Index(CART cart, string returnUrl)
 {
     ViewBag.NameApp = this.repository.NameApp();
     return(View(new CartIndexViewModel {
         Cart = cart,                      //Теперь через специальный связыватель модели, а так: "Cart = GetCart(),"
         ReturnUrl = returnUrl
     }));
 }
Example #11
0
 public RedirectToRouteResult ClearCart(CART cart, string returnUrl)
 {
     if (cart.Lines.Count() > 0)
     {
         cart.Clear();
     }
     return(RedirectToAction("List", "Product"));
 }
Example #12
0
        /// <summary>
        /// Add new product to Cart
        /// </summary>
        /// <param name="product"></param>
        /// <returns></returns>
        public Guid AddProductInCart(CART product)
        {
            try
            {
                CART productcart = null;
                product.ISACTIVE = true;
                if (product == null)
                {
                    throw new ArgumentNullException("Product", "Product can not be null");
                }

                // check if all required fields are present
                if ((product.PRODUCTID == null || product.PRODUCTID == Guid.Empty) || product.QUANTITY == null ||
                    (product.BUYERID == null || product.BUYERID == Guid.Empty))
                {
                    throw new ArgumentException("Some mandatory parameters required to add a new product are missing", "Product");
                }
                try
                {
                    using (APIShopKaro.Models.apsteamCFHEntities db = new APIShopKaro.Models.apsteamCFHEntities())
                    {
                        productcart = (from p in db.CARTs
                                       where p.BUYERID == product.BUYERID && p.PRODUCTID == product.PRODUCTID
                                       select p).Single();
                    }
                    return(productcart.ID);
                }
                catch (Exception e)
                {
                }

                if (product.ID == null || product.ID == Guid.Empty)
                {
                    product.ID = Guid.NewGuid();
                }

                using (APIShopKaro.Models.apsteamCFHEntities db = new APIShopKaro.Models.apsteamCFHEntities())
                {
                    try
                    {
                        db.CARTs.Add(product);
                        db.SaveChanges();
                    }
                    catch (System.Data.DataException e)
                    {
                        throw new Exception(e.InnerException.InnerException.Message);
                    }
                }

                return(product.ID);
            }
            catch (Exception e)
            {
                throw;
            }
        }
Example #13
0
        public RedirectToRouteResult AddToCart(CART cart, int productId, string returnUrl)
        {
            PRODUCT product = repository.Products.FirstOrDefault(p => p.ProductId == productId);

            if (product != null)
            {
                cart.AddItem(product, 1);         //GetCart().AddItem(product, 1);
            }
            return(RedirectToAction("Index", new { returnUrl }));
        }
Example #14
0
        public RedirectToRouteResult RemLineFromCart(CART cart, int productId, string returnUrl)
        {
            PRODUCT product = repository.Products.FirstOrDefault(p => p.ProductId == productId);

            if (product != null)
            {
                cart.RemoveLine(product);         //GetCart().RemoveLine(product);
            }
            return(RedirectToAction("Index", new { returnUrl }));
        }
Example #15
0
        private CART GetCart()
        {
            CART cart = (CART)Session["Cart"];

            if (cart == null)
            {
                cart            = new CART();
                Session["Cart"] = cart;
            }
            return(cart);
        }
 public ActionResult Edit([Bind(Include = "USERNAME,ProdID,Price,Cat")] CART cART)
 {
     if (ModelState.IsValid)
     {
         db.Entry(cART).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     ViewBag.ProdID   = new SelectList(db.PRODUCTS, "ProdID", "CatID", cART.ProdID);
     ViewBag.USERNAME = new SelectList(db.CUSTOMERS, "USERNAME", "PASSWORD", cART.USERNAME);
     return(View(cART));
 }
 protected void btn_Xoa_Click(object sender, EventArgs e)
 {
     cart = (CART)Session["CART"];
     foreach (GridViewRow row in this.grd_CART.Rows)
     {
         CheckBox ckb = (CheckBox)row.FindControl("ckb_Delete");
         if (ckb.Checked == true)
         {
             cart.DeleteCart(row.Cells[0].Text);
         }
     }
     LoadCart(cart);
 }
Example #18
0
        public void Can_View_Cart_Contents()
        {
            // Arrange - create a Cart
            CART cart = new CART();
            // Arrange - create the controller
            CartController target = new CartController(null, null);
            // Act - call the Index action method
            CartIndexViewModel result = (CartIndexViewModel)target.Index(cart, "myUrl").ViewData.Model;

            // Assert
            Assert.AreSame(result.Cart, cart);
            Assert.AreEqual(result.ReturnUrl, "myUrl");
        }
        // GET: CARTs/Details/5
        public ActionResult Details(string id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            CART cART = db.CARTs.Find(id);

            if (cART == null)
            {
                return(HttpNotFound());
            }
            return(View(cART));
        }
Example #20
0
        //提交订单
        public void check(int addrId)
        {
            int             book_numbers = Convert.ToInt32(Session["select_book_number"]);//Get the size of selected book list
            int             user_id      = Convert.ToInt32(Session["user_id"]);
            List <CARTLIST> order_list   = new List <CARTLIST>();

            for (int i = 0; i < book_numbers; i++)
            {
                order_list.Add(db.Database.SqlQuery <CARTLIST>("select * from CARTLIST where USER_ID=" + user_id.ToString() + " and BOOK_ID =" + Session["select_book" + i.ToString()]).FirstOrDefault());
            }
            CART cart = db.CART.Find(user_id);//购物车项
            //var cartlist = db.CARTLIST.SqlQuery("select * from CARTLIST where USER_ID=" + user_id.ToString()).ToList();//购物车清单
            //int count = db.Database.SqlQuery<int>("select QUANTITY from CARTLIST where USER_ID=" + user_id.ToString()).FirstOrDefault();//项数
            int amout       = 0;
            int total_price = 0;

            for (int i = 0; i < book_numbers; i++)
            {
                total_price += Convert.ToInt32(order_list[i].TOTAL_PRICE);
                amout       += Convert.ToInt32(order_list[i].QUANTITY);
            }
            ORDERS new2 = new ORDERS();
            int    max  = db.Database.SqlQuery <int>("select max(ID) from ORDERS").FirstOrDefault(); //找到ID的最大值

            max++;                                                                                   //作为新ID
            int post_cost = 15 - 3 * amout;

            if (post_cost < 0)
            {
                post_cost = 0;
            }
            new2.ID         = max; new2.USER_ID = user_id; new2.ADDRESS_ID = addrId; new2.QUANTITY = book_numbers; new2.PRICE = total_price;
            new2.TIME_START = DateTime.Now.ToString(); new2.STATUS = "NO"; new2.POST_COST = post_cost;
            db.ORDERS.Add(new2);
            for (int i = 0; i < book_numbers; i++)
            {
                ORDER_INCLUDE temp = new ORDER_INCLUDE();
                temp.ORDER_ID    = max;
                temp.BOOK_ID     = order_list[i].BOOK_ID;
                temp.QUANTITY    = order_list[i].QUANTITY;
                temp.TOTAL_PRICE = order_list[i].TOTAL_PRICE;
                db.ORDER_INCLUDE.Add(temp);
            }
            for (int i = 0; i < book_numbers; i++)
            {
                removeCart(Convert.ToInt32(Session["select_book" + i.ToString()]), user_id);
            }
            db.SaveChanges();
        }
Example #21
0
 public HttpResponseMessage AddProductToCart(CART product)
 {
     try
     {
         var cartService = new CartService();
         var id          = cartService.AddProductInCart(product);
         var response    = Request.CreateResponse(HttpStatusCode.OK, id);
         return(response);
     }
     catch (Exception e)
     {
         var error = Request.CreateResponse(HttpStatusCode.InternalServerError, e.Message);
         return(error);
     }
 }
Example #22
0
        public object BindModel(ControllerContext controllerContext, ModelBindingContext
                                bindingContext)
        {
            // Получить объект CART из сессии
            CART cart = (CART)controllerContext.HttpContext.Session[sessionKey];

            // Создать экземпляр CART, если его не обнаружено в данных сеанса
            if (cart == null)
            {
                cart = new CART();
                controllerContext.HttpContext.Session[sessionKey] = cart;
            }
            // Вернуть объект CART
            return(cart);
        }
Example #23
0
        //Edit the amount of book
        public void EditAmount(int bookId, int bookAmount)
        {
            int          user_id   = Convert.ToInt32(Session["user_id"]);
            CART         cart_temp = db.CART.Where(u => u.USER_ID == user_id).FirstOrDefault();
            CART_INCLUDE book_temp = db.CART_INCLUDE.Where(u => u.USER_ID == user_id).Where(u => u.BOOK_ID == bookId).FirstOrDefault();
            BOOK         book      = db.BOOK.Find(bookId);
            decimal      delta     = (decimal)bookAmount - (decimal)book_temp.QUANTITY;

            cart_temp.QUANTITY    += delta;
            cart_temp.TOTAL_PRICE += delta * book.PRICE;
            book_temp.QUANTITY     = bookAmount;
            book_temp.TOTAL_PRICE  = book.PRICE * bookAmount;

            db.SaveChanges();
        }
        // GET: CARTs/Edit/5
        public ActionResult Edit(string id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            CART cART = db.CARTs.Find(id);

            if (cART == null)
            {
                return(HttpNotFound());
            }
            ViewBag.ProdID   = new SelectList(db.PRODUCTS, "ProdID", "CatID", cART.ProdID);
            ViewBag.USERNAME = new SelectList(db.CUSTOMERS, "USERNAME", "PASSWORD", cART.USERNAME);
            return(View(cART));
        }
Example #25
0
        public HttpResponseMessage addToCart(int cartId, int productId)
        {
            try
            {
                PRODUCT product = db.PRODUCT.Where(u => u.productId == productId).FirstOrDefault();
                //USER queryUser = db.USER.Where(u => u.cartId == cart.cartId).FirstOrDefault();
                CART cartFound = db.CART.Where(u => u.productId == productId && u.cartId == cartId).FirstOrDefault();


                if (product == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, "There is no Product with Id " + productId));
                }
                else
                {
                    if (cartFound != null)
                    {
                        cartFound.quantity += 1;
                        cartFound.subTotal  = cartFound.quantity * product.productPrice;

                        db.SaveChanges();
                        return(Request.CreateResponse(HttpStatusCode.Created, cartFound));
                    }
                    else
                    {
                        var newCart = new CART()
                        {
                            cartId    = cartId,
                            productId = productId,
                            //quantity = cart.quantity == 0? 1:cart.quantity,
                            quantity = 1,
                            isClosed = false,
                            subTotal = product.productPrice
                        };

                        db.CART.Add(newCart);
                        db.SaveChanges();

                        return(Request.CreateResponse(HttpStatusCode.Created, newCart));
                    }
                }
            }
            catch (Exception ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex));
            }
        }
Example #26
0
        //Remove book
        public void RemoveBook(int bookId)
        {
            int          user_id   = Convert.ToInt32(Session["user_id"]);
            CART_INCLUDE book_temp = db.CART_INCLUDE.Where(u => u.USER_ID == user_id).Where(u => u.BOOK_ID == bookId).FirstOrDefault();
            CART         cart_temp = db.CART.Where(u => u.USER_ID == user_id).FirstOrDefault();

            //Judge whether the cart is empty
            if (cart_temp.QUANTITY != book_temp.QUANTITY)
            {
                cart_temp.QUANTITY -= book_temp.QUANTITY;
            }
            else
            {
                db.CART.Remove(cart_temp);
            }
            db.CART_INCLUDE.Remove(book_temp);
            db.SaveChanges();
        }
Example #27
0
 public ViewResult Checkout(CART cart, SHIPPING_DETAILS shippingDetails)
 {
     if (cart.Lines.Count() == 0)
     {
         ModelState.AddModelError("", "Извините, ваша корзина пуста!");
     }
     if (ModelState.IsValid)
     {
         orderProcessor.ProcessOrder(cart, shippingDetails);
         orderProcessor.SaveOrder(cart, shippingDetails);
         ViewBag.NameApp = this.repository.NameApp();
         cart.Clear();
         return(View("Completed"));
     }
     else
     {
         return(View(shippingDetails));
     }
 }
Example #28
0
        public int getCartId()
        {
            MembershipUser membershipUser = Membership.GetUser("Username");
            Guid           userId         = new Guid();

            if (membershipUser != null)
            {
                userId = (Guid)membershipUser.ProviderUserKey;
            }

            if (HttpContext.Current.Session[CartSessionKey] == null)
            {
                //create the new cart id
                CART cart = new CART
                {
                    Date     = DateTime.Today,
                    Discount = 0,
                    UserId   = userId
                };

                HttpContext.Current.Session[CartSessionKey] = cart.CartId;
                return(cart.CartId);
            }

            //if (HttpContext.Current.Session[CartSessionKey] == null)
            //{
            //    if (!string.IsNullOrWhiteSpace(HttpContext.Current.User.Identity.Name))
            //    {
            //        HttpContext.Current.Session[CartSessionKey] = HttpContext.Current.User.Identity.Name;
            //    }
            //    else
            //    {
            //        //NEED TO REPLACE THIS TO RETRIEVE CART ID FROM DATABASE
            //        // Generate a new random GUID using System.Guid class.
            //        Guid tempCartId = Guid.NewGuid();
            //        HttpContext.Current.Session[CartSessionKey] = tempCartId.ToString();
            //    }
            //}
            string cartSessionKey = HttpContext.Current.Session[CartSessionKey].ToString();

            return(int.Parse(cartSessionKey));
        }
Example #29
0
        public void Can_Checkout_And_Submit_Order()
        {
            // Arrange - create a mock order processor
            Mock <IOrderProcessor> mock = new Mock <IOrderProcessor>();
            // Arrange - create a cart with an item
            CART cart = new CART();

            cart.AddItem(new PRODUCT(), 1);
            // Arrange - create an instance of the controller
            CartController target = new CartController(null, mock.Object);
            // Act - try to checkout
            ViewResult result = target.Checkout(cart, new SHIPPING_DETAILS());

            // Assert - check that the order has been passed on to the processor
            mock.Verify(m => m.ProcessOrder(It.IsAny <CART>(), It.IsAny <SHIPPING_DETAILS>()), Times.Once());
            // Assert - check that the method is returning the Completed view
            Assert.AreEqual("Completed", result.ViewName);
            // Assert - check that we are passing a valid model to the view
            Assert.AreEqual(true, result.ViewData.ModelState.IsValid);
        }
Example #30
0
        public void Cannot_Checkout_Empty_Cart()
        {
            // Arrange - create a mock order processor
            Mock <IOrderProcessor> mock = new Mock <IOrderProcessor>();
            // Arrange - create an empty cart
            CART cart = new CART();
            // Arrange - create shipping details
            SHIPPING_DETAILS shippingDetails = new SHIPPING_DETAILS();
            // Arrange - create an instance of the controller
            CartController target = new CartController(null, mock.Object);
            // Act
            ViewResult result = target.Checkout(cart, shippingDetails);

            // Assert - check that the order hasn't been passed on to the processor
            mock.Verify(m => m.ProcessOrder(It.IsAny <CART>(), It.IsAny <SHIPPING_DETAILS>()), Times.Never());
            // Assert - check that the method is returning the default view
            Assert.AreEqual("", result.ViewName);
            // Assert - check that we are passing an invalid model to the view
            Assert.AreEqual(false, result.ViewData.ModelState.IsValid);
        }