Exemple #1
0
 /// <summary>
 /// Dodanie elementu do koszyka i zwiększenie ilości przedmiotów oraz ceny
 /// </summary>
 /// <param name="item"></param>
 public void AddItemToCart(ElectronicDeviceViewModel item)
 {
     CartItems.Add(item);
     NumberOfElements++;
     TotalPrice += item.Price;
 }
 //get the database and cartitems of guests
 public CartController(Team5_Db db, CartItems cartitems)
 {
     this.db        = db;
     this.cartitems = cartitems;
 }
Exemple #3
0
 public ActionResult CartSummary()
 {
     ViewData["CartCount"] = CartItems.Sum(o => o.Amount);
     return(PartialView("CartSummary"));
 }
 public IActionResult AddItemToCartAsync(CartItems item)
 {
     return(View());
 }
        //[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static int SetSessionValue(int ID, int Type, string Size)
        {
            string Name = "CartPicks";
            //string sessionVal = String.Empty;
            List <CartItems> cartItems = new List <CartItems>();


            if (HttpContext.Current.Session[Name] != null)
            {
                try
                {
                    cartItems = (List <CartItems>)HttpContext.Current.Session[Name];
                    CartItems newItem = new CartItems();
                    bool      hasItem = cartItems.Any(c => c.ItemId == ID && c.TypeCheck == Size);
                    if (!hasItem)
                    {
                        newItem.ItemId = ID;

                        if (Type == 0)
                        {
                            newItem.CatId  = 1;
                            newItem.GrpChk = true;
                        }
                        else
                        {
                            //if (Type == 3)
                            //{
                            //    newItem.CatId = 3;
                            //}
                            //else
                            //{
                            //    newItem.CatId = 5;
                            //}
                            newItem.CatId  = Type;
                            newItem.GrpChk = false;
                        }
                        newItem.Qty       = 1;
                        newItem.TypeCheck = Size;
                        cartItems.Add(newItem);


                        HttpContext.Current.Session[Name] = cartItems;

                        return(1);
                    }
                    else
                    {
                        var cartItems2 = (List <CartItems>)HttpContext.Current.Session["CartPicks"];

                        if (cartItems2 != null)
                        {
                            var cartItem = cartItems2.First(p => p.ItemId == ID && p.TypeCheck == Size);
                            int qty      = cartItem.Qty + 1;
                            cartItem.Qty       = qty;
                            cartItem.TypeCheck = Size;

                            HttpContext.Current.Session["CartPicks"] = cartItems;
                        }

                        return(2);
                    }
                }
                catch
                {
                    return(0);

                    throw;
                }
            }
            else
            {
                return(0);
            }
        }
Exemple #6
0
 public void ClearCart()
 {
     CartItems.RemoveAll(r => r.isProduct == true);
     CartItems.RemoveAll(r => r.isProduct == false);
 }
Exemple #7
0
 public bool ContainsGiftVoucherProducts()
 => CartItems.Any(x => x.Product.ProductCategory == ProductCategory.GiftVoucher);
        /// <returns>Success</returns>
        /// <exception cref="SwaggerException">A server side error occurred.</exception>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        public async System.Threading.Tasks.Task <CartItems> AddAsync(long id, CartItems items, System.Threading.CancellationToken cancellationToken)
        {
            if (id == null)
            {
                throw new System.ArgumentNullException("id");
            }

            var urlBuilder_ = new System.Text.StringBuilder();

            urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/Cart/Add/{id}");
            urlBuilder_.Replace("{id}", System.Uri.EscapeDataString(ConvertToString(id, System.Globalization.CultureInfo.InvariantCulture)));

            var client_ = _httpClient;

            try
            {
                using (var request_ = new System.Net.Http.HttpRequestMessage())
                {
                    var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(items, _settings.Value));
                    content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json");
                    request_.Content             = content_;
                    request_.Method = new System.Net.Http.HttpMethod("POST");
                    request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json"));

                    PrepareRequest(client_, request_, urlBuilder_);
                    var url_ = urlBuilder_.ToString();
                    request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
                    PrepareRequest(client_, request_, url_);

                    var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);

                    try
                    {
                        var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value);
                        if (response_.Content != null && response_.Content.Headers != null)
                        {
                            foreach (var item_ in response_.Content.Headers)
                            {
                                headers_[item_.Key] = item_.Value;
                            }
                        }

                        ProcessResponse(client_, response_);

                        var status_ = ((int)response_.StatusCode).ToString();
                        if (status_ == "200")
                        {
                            var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            var result_ = default(CartItems);
                            try
                            {
                                result_ = Newtonsoft.Json.JsonConvert.DeserializeObject <CartItems>(responseData_, _settings.Value);
                                return(result_);
                            }
                            catch (System.Exception exception_)
                            {
                                throw new SwaggerException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_);
                            }
                        }
                        else
                        if (status_ == "400")
                        {
                            var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            var result_ = default(CartError);
                            try
                            {
                                result_ = Newtonsoft.Json.JsonConvert.DeserializeObject <CartError>(responseData_, _settings.Value);
                            }
                            catch (System.Exception exception_)
                            {
                                throw new SwaggerException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_);
                            }
                            throw new SwaggerException <CartError>("Bad Request", (int)response_.StatusCode, responseData_, headers_, result_, null);
                        }
                        else
                        if (status_ != "200" && status_ != "204")
                        {
                            var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null);
                        }

                        return(default(CartItems));
                    }
                    finally
                    {
                        if (response_ != null)
                        {
                            response_.Dispose();
                        }
                    }
                }
            }
            finally
            {
            }
        }
Exemple #9
0
        public static void NotifyNewOrder(OSUser user, Cart cart, string saleReferenceID)
        {
            var cartItems = CartItems.GetOrderDetails(cart.ID);

            var stateTitle = Cities.GetCityName(user.StateID.Value);
            var cityTitle  = Cities.GetCityName(user.CityID.Value);

            StringBuilder smsBody   = new StringBuilder();
            StringBuilder emailBody = new StringBuilder();

            #region SMS Body

            smsBody.Append("سفارش جدید: \n" + cart.ToPay.Value.ToPrice() + "\n");

            foreach (var item in cartItems)
            {
                smsBody.Append(item.ProductTitle);
                if (item.ProductVarentID.HasValue)
                {
                    smsBody.Append(" " + item.VarientTitle);
                }
                smsBody.Append("\n");
            }

            smsBody.Append(cart.PaymentMethodType.GetEnumDisplay() + "\n" + cart.SendMethodType.GetEnumDisplay());

            #endregion SMS Body

            #region Email Body

            emailBody.Append("سفارش جدید: <br/>" + cart.ToPay.Value.ToPrice() + "<br/>");
            emailBody.Append("محصولات: <br/>");

            foreach (var item in cartItems)
            {
                emailBody.Append(item.ProductTitle);
                if (item.ProductVarentID.HasValue)
                {
                    emailBody.Append(" " + item.VarientTitle);
                }
                emailBody.Append("<br/>");
            }

            emailBody.AppendFormat("نام و نام خانوادگی: {0} <br/>" +
                                   "{1}" +
                                   "شماره همراه: {2} <br/>" +
                                   "روش پرداخت: {3} <br/>" +
                                   "روش ارسال: {4} <br/>" +
                                   "استان: {5} <br/>" +
                                   "شهر: {6} <br/>" +
                                   "آدرس: {7}",
                                   user.Firstname + " " + user.Lastname,
                                   saleReferenceID != "-1" ? "کد رهگیری: " + saleReferenceID + "<br/>" : String.Empty,
                                   user.Mobile,
                                   cart.PaymentMethodType.GetEnumDisplay(),
                                   cart.SendMethodType.GetEnumDisplay(),
                                   stateTitle,
                                   cityTitle,
                                   user.HomeAddress);

            #endregion Email Body

            EmailServices.NotifyAdminsByEmail(AdminEmailType.NewOrder, emailBody.ToString(), user.Id);
            SMSServices.SendSMS("09120062417", smsBody.ToString(), user.Id);
        }
Exemple #10
0
        public ActionResult Add(
            int?productVarientID = null,
            int?productID        = null,
            int?packageID        = null,
            byte quantity        = 1)
        {
            var jsonSuccessResult = new JsonSuccessResult();

            try
            {
                Cart cart = CartController.GetCart(HttpContext);

                bool exists = true;
                bool canAdd = true;

                if (!CartItems.Exists(cart.ID, productVarientID, productID, packageID))
                {
                    canAdd = Products.CanAddToCart(productVarientID, productID, packageID);

                    if (canAdd)
                    {
                        var cartItem = new CartItem();

                        cartItem.CartID = cart.ID;

                        cartItem.ProductVarientID = productVarientID;
                        cartItem.ProductID        = productID;
                        cartItem.PackageID        = packageID;

                        cartItem.DateTime = DateTime.Now;
                        cartItem.Quantity = quantity;
                        cartItem.Price    = -1;

                        CartItems.Insert(cartItem);
                    }

                    exists = false;
                }

                var cartItems = CartItems.GetByCartID(cart.ID, UserID);

                int total         = 0,
                    totalDiscount = 0;

                foreach (var item in cartItems)
                {
                    totalDiscount += item.Quantity * (item.DiscountPercent > 0 ? item.DiscountPrice : item.Price);
                    total         += item.Quantity * item.Price;
                }

                jsonSuccessResult.Data = new
                {
                    Exists        = exists,
                    CanAdd        = canAdd,
                    CartItems     = cartItems,
                    Total         = total,
                    TotalDiscount = totalDiscount,
                };
                jsonSuccessResult.Success = true;
            }
            catch (DbException ex)
            {
                jsonSuccessResult.Errors  = ex.Errors.ToArray();
                jsonSuccessResult.Success = false;
            }
            catch (Exception ex)
            {
                jsonSuccessResult.Errors  = new string[] { ex.Message };
                jsonSuccessResult.Success = false;
            }

            return(new JsonResult()
            {
                Data = jsonSuccessResult
            });
        }
Exemple #11
0
        public JsonResult Payment(OSUser osUser, SendMethodType sendMethodType, PaymentMethodType paymentMethodType, string userDescription)
        {
            var jsonSuccessResult = new JsonSuccessResult();

            try
            {
                var payDate = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString().PadLeft(2, '0') + DateTime.Now.Day.ToString().PadLeft(2, '0');
                var payTime = DateTime.Now.Hour.ToString().PadLeft(2, '0') + DateTime.Now.Minute.ToString().PadLeft(2, '0') + DateTime.Now.Second.ToString().PadLeft(2, '0');
                var orderID = payDate + payTime;

                string userID;
                int?   cityID;

                if (User.Identity.IsAuthenticated)
                {
                    userID = UserID;
                    cityID = OSUsers.GetByID(UserID).CityID;
                }
                else
                {
                    cityID = osUser.CityID;

                    IdentityResult result = registerUser(ref osUser);

                    if (result.Succeeded)
                    {
                        UserNotifications.Send(StaticValues.AdminID, String.Format("ثبت نام کاربر - در فرم سبد خرید '{0}'", osUser.UserName), "/Admin/OSUsers/Edit/" + osUser.Id, NotificationType.Success);
                        userID = osUser.Id;
                    }
                    else
                    {
                        throw new Exception(result.Errors.Aggregate((a, b) => a + ", " + b));
                    }
                }

                int total         = 0,
                    totalDiscount = 0,
                    delivaryPrice = -1;

                var cart      = GetCart(HttpContext);
                var cartItems = CartItems.GetByCartID(cart.ID, (User.Identity.IsAuthenticated ? userID : null));
                var listGifts = new List <CartItemGift>();

                foreach (var item in cartItems)
                {
                    var price = (item.DiscountPercent > 0 ? item.DiscountPrice : item.Price);

                    #region Update CartItem

                    var cartItem = CartItems.GetByID(item.ID);
                    cartItem.Price          = price;
                    cartItem.IsFreeDelivery = item.IsFreeDelivery;
                    CartItems.Update(cartItem);

                    #endregion Update CartItem

                    totalDiscount += item.Quantity * price;
                    total         += item.Quantity * item.Price;

                    foreach (var gift in item.Gifts)
                    {
                        listGifts.Add(new CartItemGift
                        {
                            CartItemID = item.ID,
                            GiftID     = gift.GiftID,
                            Price      = gift.Price,
                            LastUpdate = DateTime.Now
                        });
                    }
                }

                if (
                    (sendMethodType == SendMethodType.Free && cityID == 468) ||      // مشهد
                    (StaticValues.MaxPriceFreeDelivery && totalDiscount >= 10000) || // طرح های بالای ارسال
                    (cartItems.Any(a => a.IsFreeDelivery))                           // محصولات دارای ارسال رایگان
                    )
                {
                    delivaryPrice = 50000;
                }
                else
                {
                    delivaryPrice = StaticValues.DeliveryPrice;
                }

                // ثبت هدایا
                if (listGifts.Count > 0)
                {
                    CartItemGifts.Insert(listGifts);
                }

                var toPay = (totalDiscount + delivaryPrice);

                string refID = String.Empty;

                if (paymentMethodType == PaymentMethodType.Online)
                {
                    Logs.Alert(Utilities.GetIP(), "PaymentMethodType.Online", String.Format("payDate: {0}, payTime: {1}, orderID: {2}, toPay: {3}", payDate, payTime, orderID, toPay));
                    refID = connectToMellat(payDate, payTime, orderID, toPay);
                }

                #region Update Cart

                cart.UserID            = userID;
                cart.SendMethodType    = sendMethodType;
                cart.PaymentMethodType = paymentMethodType;
                cart.Tax             = Int32.Parse(StaticValues.Tax);
                cart.IP              = Utilities.GetIP();
                cart.UserDescription = userDescription;

                cart.Total         = total;
                cart.DelivaryPrice = delivaryPrice;
                cart.TotalDiscount = totalDiscount;
                cart.ToPay         = toPay;

                cart.DateTime = cart.LastUpdate = DateTime.Now;
                cart.CartGuid = null;

                if (paymentMethodType == PaymentMethodType.Online)
                {
                    cart.CartStatus = CartStatus.DuringPay;
                }
                else if (paymentMethodType == PaymentMethodType.Card || paymentMethodType == PaymentMethodType.Home)
                {
                    cart.CartStatus = CartStatus.FuturePay;
                }

                cart.SendStatus = SendStatus.NotChecked;
                cart.OrderID    = orderID;

                Carts.Update(cart);

                #endregion Update Cart

                logPaymentData(orderID, toPay, cart.ID);

                jsonSuccessResult.Success = true;

                if (paymentMethodType == PaymentMethodType.Online)
                {
                    jsonSuccessResult.Data = new
                    {
                        PgwSite = StaticValues.PgwSite,
                        RefID   = refID
                    }
                }
                ;
                else
                {
                    jsonSuccessResult.Data = new
                    {
                        ToPayPrice = toPay
                    };

                    OSUser user;
                    // اطلاع رسانی به مدیر سایت
                    if (User.Identity.IsAuthenticated)
                    {
                        user = OSUsers.GetByID(UserID);
                    }
                    else
                    {
                        user = osUser;
                    }

                    NotifyNewOrder(user, cart, "-1");
                }
            }
            catch (DbException ex)
            {
                jsonSuccessResult.Errors  = ex.Errors.ToArray();
                jsonSuccessResult.Success = false;

                Logs.Alert(Utilities.GetIP(), "Payment Error", ex.Errors.Aggregate((a, b) => a + ", " + b) + "_" + ex.StackTrace, LogType.Error);
            }
            catch (Exception ex)
            {
                jsonSuccessResult.Errors  = new string[] { ex.Message };
                jsonSuccessResult.Success = false;

                Logs.Alert(Utilities.GetIP(), "Payment Error", ex.Message + "_" + ex.StackTrace, LogType.Error);
            }

            return(new JsonResult()
            {
                Data = jsonSuccessResult,
            });
        }
Exemple #12
0
 public int TotalQuantity()
 {
     return(CartItems.Sum(x => x.Quantity));
 }
Exemple #13
0
 public object Get(CartItems request)
 {
     return(new CartItemsResponse {
         CartItems = GetCartBotsJsonData()
     });
 }
Exemple #14
0
 public void Delete(CartItems entity)
 {
     _wingtiptoysContext.Remove(entity);
     _wingtiptoysContext.SaveChanges();
 }
Exemple #15
0
 public decimal CartNonDiscountedPriceExcludingGiftVouchers() =>
 CartItems.Where(y => y.Product.ProductCategory != ProductCategory.GiftVoucher)
 .Sum(x => x.UnitPrice * x.Qty);
 /// <returns>Success</returns>
 /// <exception cref="SwaggerException">A server side error occurred.</exception>
 public System.Threading.Tasks.Task <CartItems> AddAsync(long id, CartItems items)
 {
     return(AddAsync(id, items, System.Threading.CancellationToken.None));
 }
Exemple #17
0
 public decimal CartProductCategoryTotal(ProductCategory productCategory) =>
 CartItems.Where(y => y.Product.ProductCategory == productCategory)
 .Sum(x => x.UnitPrice * x.Qty);
        public IActionResult AddToCart(int id)
        {
            //Check the Product ID is valid
            if(id == 0)
            {
                //Temp Data allows you to store values across requests
                TempData["Message"] = "Invalid Cart ID";
                return RedirectToAction("index");
            }

            var cartId = HttpContext.Session.GetInt32("CartId");

            //Retrieve the Shopping Cart
            Carts cart = dbContext.Carts.Find(cartId ?? 0);

            //If the Cart is null
            if(cart == null)
            {
                //Create the Shopping Cart
                cart = new Carts();
                dbContext.Carts.Add(cart);

                //Save the Cart to the Database
                dbContext.SaveChanges();

                //Save the new Cart ID to the Session
                HttpContext.Session.SetInt32("CartId", cart.CartId);
            }


            //Get the CartItem for this Product from the shopping Cart
            var cartItem = dbContext.CartItems
                                    .Where(c => c.ProductId == id && c.CartId  == cart.CartId)
                                    .FirstOrDefault();
            if(cartItem == null)
            {
                //Then Create Cart Item
                cartItem = new CartItems
                {
                    CartId = cart.CartId,
                    ProductId = id,
                    Quantity = 1
                };
                
                dbContext.CartItems.Add(cartItem);
                TempData["Message"] = "Product was Added to the Cart";
            }
            else
            {
                //Increment the Cart Item Quantity
                cartItem.Quantity = cartItem.Quantity + 1;
                dbContext.Update(cartItem);

                TempData["Message"] = "Product quantity was updated";
            }
            dbContext.SaveChanges();

            //Save the CartItem Count in session so we can retrieve it in the Layout Page
            HttpContext.Session.SetInt32("CartCount", cart.CartItems.Count);

            return RedirectToAction("Index");
        }
Exemple #19
0
        public Cart(Basket apiBasket) : this()
        {
            if (apiBasket.Items.Any())
            {
                foreach (var item in apiBasket.Items)
                {
                    CartItemCount += (int)item.Quantity;
                    var cartItem = new CartItem
                    {
                        Name       = item.Name,
                        ProductId  = item.Id.ToString(),
                        Quantity   = (int)item.Quantity,
                        ItemPrice  = new Price(item.BasePrice.ToString()),
                        TotalPrice = new Price(item.AdjustedPrice.ToString())
                    };

                    if (item.PriceAdjustments.Any())
                    {
                        cartItem.ListPrice      = new Price(item.Price.ToString());
                        cartItem.CouponDiscount = new Price(item.PriceAdjustments.FirstOrDefault().Discount.ToString())
                        {
                            Label = item.PriceAdjustments.FirstOrDefault().Description
                        };
                    }

                    CartItems.Add(cartItem);
                }

                // Summary
                Summary.Costs.Add(new Price(apiBasket.ProductSubTotal.ToString())
                {
                    Label = "Subtotal: "
                });

                if (apiBasket.PriceAdjustments.Any())
                {
                    var discount    = 0.0M;
                    var description = string.Empty;
                    apiBasket.PriceAdjustments.ForEach(x => { discount += x.Discount; description += "<br>" + x.Description; });
                    Summary.Costs.Add(new Price(discount.ToString())
                    {
                        Label = string.Format("Order Discount: {0}", description)
                    });
                }
                if (apiBasket.ShippingTotal > 0)
                {
                    Summary.Costs.Add(new Price(apiBasket.ShippingTotal.ToString())
                    {
                        Label = "Shipping: "
                    });
                }

                Summary.Total = new Price(apiBasket.OrderTotal.ToString())
                {
                    Label = "Estimated Total: "
                };

                // Coupons
                apiBasket.Coupons.ForEach(x =>
                {
                    var message = string.Empty;

                    switch (x.StatusCode)
                    {
                    case CouponCodeStatusCodeEnum.applied:
                        message = Config.Constants.CouponAppliedMessage;
                        break;

                    case CouponCodeStatusCodeEnum.no_applicable_promotion:
                        message = Config.Constants.CouponNAMessage;
                        break;

                    default:
                        message = Config.Constants.CouponInvalidMessage;
                        break;
                    }

                    Coupons.Add(new CouponCodeBase
                    {
                        Code        = x.Code,
                        CouponValue = new Price(),
                        Message     = string.Format(message, x.Code)
                    });
                });
            }
        }
Exemple #20
0
 public bool Add(CartItems cartItem)
 {
     this.cartItemsRepository.Add(cartItem);
     return(true);
 }
Exemple #21
0
        public Task <List <CartItems> > AddToCart(CartItems CartItem)
        {
            ShoppingCart _shoppingCart = new ShoppingCart(_context);

            return(_shoppingCart.AddToCart(CartItem));
        }
        protected void LoadProduct()
        {
            string    id = Request.QueryString.Get("id");
            DataTable tb;

            object[] parameter = new object[1];
            object[] listPr    = new object[1];
            parameter[0]  = "@id";
            listPr[0]     = id;
            tb            = DataProvider.Instance.ExecuteQr("selectProductById", parameter, listPr);
            Session["id"] = id;
            Products product = new Products(tb.Rows[0]);
            string   html    = "<div class=\"main_image\">";

            html += "<img src=\"img/" + product.Image + ".jpg\">";
            html += "</div>";
            Title = product.Name;
            product_detail.InnerHtml   = html;
            product_name_asp.InnerHtml = product.Name.ToUpper();
            price_asp.InnerHtml        = string.Format("{0:0,0 đ}", product.Price);
            discount_price.InnerHtml   = string.Format("{0:0,0 đ}", (product.Price - product.Discount));
            row_thuongHieu.InnerHtml   = product.SupName.ToUpper();
            row_discount.InnerHtml     = string.Format("{0:0,0 đ}", product.Discount);
            string availiable;

            if (product.Availiable)
            {
                availiable = "Có sẵn";
            }
            else
            {
                availiable = "Liên hệ";
            }
            row_availiable.InnerHtml = availiable;

            string isNew;

            if (product.Lastest)
            {
                isNew = "Hàng mới";
            }
            else
            {
                isNew = "Không";
            }
            row_isNewProduct.InnerHtml = isNew;

            string isBest;

            if (product.BestSeller)
            {
                isBest = "Hàng bán chạy";
            }
            else
            {
                isBest = "Không";
            }

            row_isSellerProduct.InnerHtml = isBest;
            row_gift.InnerHtml            = product.Gift;
            row_category.InnerHtml        = product.CateName;
            row_description.InnerHtml     = product.Description;
            addtocart.HRef = "chi_tiet_san_pham.aspx?id=" + product.Id + "&action=add";
            buynow.HRef    = "chi_tiet_san_pham.aspx?id=" + product.Id + "&action=add&redirect=true";

            if (Session["id"] != null && Request.QueryString.Get("action") == "add")
            {
                List <CartItems> cart = new List <CartItems>();
                if (Session["cart"] == null)
                {
                    Session["cart"] = cart;
                }
                else
                {
                    cart = Session["cart"] as List <CartItems>;
                }
                CartItems demo    = new CartItems();
                Boolean   isExist = false;
                foreach (CartItems item in cart)
                {
                    if (item.Id == product.Id)
                    {
                        item.Number++;
                        isExist = true;
                        break;
                    }
                }
                if (!isExist)
                {
                    demo.Id       = product.Id;
                    demo.Name     = product.Name;
                    demo.Image    = product.Image;
                    demo.Price    = product.Price;
                    demo.Discount = product.Discount;
                    demo.Number   = 1;
                    cart.Add(demo);
                }
                Session["cart"] = cart;
                if (Request.QueryString.Get("redirect") == "true")
                {
                    Response.Redirect("gio_hang.aspx");
                }
                else
                {
                    Response.Redirect("chi_tiet_san_pham.aspx?id=" + product.Id);
                }
            }
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        APIResponse ResponseENUM   = APIResponse.NOT_OK;
        string      ResponseString = "";

        try
        {
            Cart CartObj = null;
            if (CookieProxy.Instance().HasKey("Cart"))
            {
                int PBSId = int.Parse(Request.Form["pbsid"].ToString());
                CartObj = new JavaScriptSerializer().Deserialize <Cart>(CookieProxy.Instance().GetValue("Cart").ToString());
                bool AlreadyHasProductInCart = false;
                foreach (CartItems Cart in CartObj.CartItems)
                {
                    if (Cart.ProductObj.pbsID == PBSId)
                    {
                        ResponseENUM            = APIResponse.NOT_OK;
                        ResponseString          = "PRODUCT ALREADY ADDED TO CART, PLEASE MODIFY THE QUANTITY";
                        AlreadyHasProductInCart = true;
                        break;
                    }
                }
                if (AlreadyHasProductInCart == false)
                {
                    ProductByStore PBSPbj = new ProductByStore();
                    PBSPbj.SetProductByStoreID(PBSId);
                    CartItems CartItemsObj = new CartItems
                    {
                        HasQuantity = true,
                        ProductObj  = new ProductByStoreBusinessLayerTemplate().Select(PBSPbj)
                    };
                    // reset the quantity to 1, we want the user quantity not the product quantity
                    CartItemsObj.ProductObj.Quantity = 1;
                    CartObj.CartItems.Add(CartItemsObj);
                    CookieProxy.Instance().SetValue("Cart", new JavaScriptSerializer().Serialize(CartObj), DateTime.Now.AddDays(5));
                    ResponseENUM   = APIResponse.OK;
                    ResponseString = "SUCCESS";
                }
            }
            else
            {
                CartObj = new Cart
                {
                    CartItems = new List <CartItems>()
                };
                int       PBSId        = int.Parse(Request.Form["pbsid"].ToString());
                CartItems CartItemsObj = new CartItems
                {
                    HasQuantity = true,
                    ProductObj  = new ProductByStoreBusinessLayerTemplate().Select(new ProductByStore()
                    {
                        ProductByStoreID = PBSId
                    })
                };
                // reset the quantity to 1, we want the user quantity (user has initially selected the quantity) not the product quantity
                CartItemsObj.ProductObj.Quantity = 1;
                CartObj.CartItems.Add(CartItemsObj);
                CookieProxy.Instance().SetValue("Cart", new JavaScriptSerializer().Serialize(CartObj), DateTime.Now.AddDays(5));
                ResponseENUM   = APIResponse.OK;
                ResponseString = "SUCCESS";
            }
        }
        catch (Exception ex)
        {
            Logger.Instance().Log(Warn.Instance(), ex);
            ResponseENUM   = APIResponse.NOT_OK;
            ResponseString = "ERROR";
        }
        finally
        {
            var ReturnObj = new
            {
                Response = ResponseENUM.ToString(),
                ResponseString
            };
            Response.Write(new JavaScriptSerializer().Serialize(ReturnObj));
        }
    }
 public async Task UpdateCartItem(CartItems cartItems)
 {
     _context.CartItems.Update(cartItems);
     await _context.SaveChangesAsync();
 }
 public Money GetShipmentItemsTotal(Currency currency) => CartItems.Aggregate(new Money(0, currency), (current, item) => current + item.DiscountedPrice.GetValueOrDefault());
 private void UpdateItemCount()
 {
     _totalItems = CartItems.Sum(i => i.Quantity);
 }
Exemple #27
0
 private void InsertNewCartItem(int productId, int quantity, decimal displayedPrice)
 {
     CartItems.Add(CartItem.Create(productId, quantity, displayedPrice, CartCookie));
 }
Exemple #28
0
 /// <summary>
 /// Usunięcie elementu z koszyka na podstawie przekazanego obiektu
 /// </summary>
 /// <param name="item"></param>
 public void DeleteFromCart(ElectronicDeviceViewModel item)
 {
     CartItems.Remove(item);
     TotalPrice -= item.Price;
     NumberOfElements--;
 }
Exemple #29
0
        public static bool SetSessionValue(string ID, int Type, string Size)
        {
            string Name = "CartPicks";
            //string sessionVal = String.Empty;
            List <CartItems> cartItems = new List <CartItems>();


            if (HttpContext.Current.Session[Name] != null)
            {
                try
                {
                    cartItems = (List <CartItems>)HttpContext.Current.Session[Name];
                    CartItems newItem = new CartItems();
                    bool      hasItem = cartItems.Any(c => c.ItemId == int.Parse(ID) && c.TypeCheck == Size);
                    if (!hasItem)
                    {
                        newItem.ItemId = int.Parse(ID);

                        if (Type == 0)
                        {
                            newItem.CatId  = 1;
                            newItem.GrpChk = true;
                        }
                        else
                        {
                            //if (Type == 3)
                            //{
                            //    newItem.CatId = 3;
                            //}
                            //else
                            //{
                            //    newItem.CatId = 5;
                            //}
                            newItem.CatId  = Type;
                            newItem.GrpChk = false;
                        }
                        newItem.Qty       = 1;
                        newItem.TypeCheck = Size;
                        cartItems.Add(newItem);


                        HttpContext.Current.Session[Name] = cartItems;

                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
                catch
                {
                    return(false);

                    throw;
                }
            }
            else
            {
                return(false);
            }
        }
Exemple #30
0
    //Get Selected Movie
    private CartItems GetSelectedTicket()
    {
        DataView pricesTable = (DataView)SqlMovieSource.Select(DataSourceSelectArguments.Empty);
        pricesTable.RowFilter = "Age = '" + ddlPrices.SelectedItem.Text + "'";
        DataRowView row = (DataRowView)pricesTable[0];

        Label lblTitle = (Label)fvMovieDetails.FindControl("lblTitle");

        int movieID = (int)row["MovieID"];
        string title = lblTitle.Text;
        int priceID = (int)row["PriceID"];
        decimal price = (decimal)row["Price"];
        string age = row["Age"].ToString();
        int quantity = 0;

        if (txtQuantity.Text.Trim().Length > 0)
            quantity = Convert.ToInt16(txtQuantity.Text);

        CartItems c = new CartItems(movieID, title, priceID, price, age, quantity);

        return c;
    }
Exemple #31
0
 public void Update(CartItems entityToUpdate, CartItems entity)
 {
     //entityToUpdate = _wingtiptoysContext.Categories
     //    .Include(a => a.Products);
     _wingtiptoysContext.SaveChanges();
 }