[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest)] //the entire parameter must be serialized to a string (no individual raw POST values) public CartResponse Create(string cartName, bool activate) { var response = new CartResponse(); Guid userId = ProfileContext.Current.UserId; if (!CartNameIsValid(cartName)) { response.Message = "Invalid Wish List name! The Wish List name may only contain letters, numbers, spaces, and underscores"; response.Status = CartResponseStatus.ERROR; } else if (CartNameIsDuplicate(userId, cartName)) { response.Message = "Invalid Wish List name! There is already a Wish List with this name"; response.Status = CartResponseStatus.ERROR; } else { NWTD.Orders.Cart.CreateCart(ProfileContext.Current.Profile.Account, cartName); if (activate) { NWTD.Profile.ActiveCart = cartName; } response.Message = "New Wish List Successfully Created"; } return(response); }
protected void Page_Load(object sender, EventArgs e) { //Response.Redirect("/Developing.htm"); using (DBDataContext db = new DBDataContext()) { City[] cityList = (from CITY in db.Cities orderby CITY.Name select CITY).ToArray(); ddlCities.DataSource = cityList; ddlCities.DataTextField = "Name"; ddlCities.DataValueField = "ID"; ddlCities.DataBind(); foreach (ListItem li in ddlCities.Items) { li.Attributes.Add("dLimit", cityList.Where(C => C.ID == int.Parse(li.Value)).First().FreeDelivery.ToString()); if (li.Value == Cart.SelectedCity) { li.Selected = true; txtDeliveryLimit.InnerText = li.Attributes["dLimit"]; } } if (Request.Cookies["selectedCityToDeliver"] == null && ddlCities.Items.Count > 0) { txtDeliveryLimit.InnerText = ddlCities.Items[0].Attributes["dLimit"]; } } CartResponse cr = new CartResponse(); cartTotal.InnerHtml = cr.price.ToString(); cartCount.InnerHtml = cr.count.ToString(); }
public IActionResult GenerateCart([FromBody] List <ProductToCartRequest> request) { var productContext = _dbContext.Set <Product>(); var products = new List <CartProduct>(); foreach (var req in request) { var dbProduct = productContext.FirstOrDefault(x => string.Equals(x.Id.ToString(), req.Id, StringComparison.OrdinalIgnoreCase)); if (dbProduct != null) { products.Add(new CartProduct { Name = dbProduct.DisplayName, Amount = req.Amount, ProductId = dbProduct.Id.ToString(), DiscountedPrice = dbProduct.DiscountedPrice, Total = (dbProduct.DiscountedPrice == 0 ? dbProduct.Price : dbProduct.DiscountedPrice) * req.Amount, Price = dbProduct.Price }); } } var cart = new CartResponse() { Products = products, CompletePrice = products.Sum(y => y.Total) }; return(Ok(cart)); }
private async Task <CartResponse> CreateUserCart(int quantity) { // Arrange var request = new { Url = "/api/Cart", Body = new AddItemToCartCommand { ProductInfo = new ProductRequest { Id = testProductId, Quantity = quantity }, UserId = testUserId } }; // Act var response = await client.PostAsync(request.Url, ContentHelper.GetStringContent(request.Body)); // Assert response.EnsureSuccessStatusCode(); CartResponse cart = await GetCartFromResponseAsync(response); return(cart); }
private void DisplayCart(CartResponse c) { lblCartID.Text = c.CartID.ToString(); lblCreateDate.Text = c.CreateDate.ToString(); lblModifyDate.Text = c.ModifyDate.ToString(); lblTotal.Text = c.Total.ToString(); gvCart.DataSource = BuildProductDataTable(c.CartItems); gvCart.DataBind(); }
private void ValidateCart(CartResponse cart, string userId, string productId, int quantity) { cart.Should().NotBeNull(); cart.UserId.Should().BeEquivalentTo(testUserId); cart.Items.Should().NotBeNullOrEmpty(); cart.TotalPrice.Should().BeGreaterThan(0); var product = cart.Items.FirstOrDefault(w => w.Id == ObjectId.Parse(productId)); product.Should().NotBeNull(); product.Quantity.Should().BeGreaterOrEqualTo(quantity); }
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest)] //the entire parameter must be serialized to a string (no individual raw POST values) public CartResponse AddItem(CartItem item, string cartname) { NWTD.Profile.EnsureCustomerCart(); CartResponse response = new CartResponse(); if (string.IsNullOrEmpty(cartname)) { cartname = global::NWTD.Profile.ActiveCart; } CartHelper ch = new CartHelper(cartname); Entry itemToAdd = CatalogContext.Current.GetCatalogEntry(item.Code, new Mediachase.Commerce.Catalog.Managers.CatalogEntryResponseGroup(CatalogEntryResponseGroup.ResponseGroup.CatalogEntryFull)); if (itemToAdd == null) { response.Status = CartResponseStatus.ERROR; response.Message = String.Format("The item with ISBN number {0} does not exist.", item.Code); return(response); } //if this item is already in the cart, get it's quantity, then add it to the entered quantity decimal addedQuantity = item.Quantity; LineItem existingItem = ch.LineItems.SingleOrDefault(li => li.CatalogEntryId == itemToAdd.ID); //this is from back when we used let people select quantities when adding to the cart //if (existingItem != null) item.Quantity += existingItem.Quantity; if (existingItem != null) { response.Message = string.Format("{0} is already in your Wish List and cannot be added a second time. If you need more, please return to your Wish List and increase the quantity of the existing item.", item.Code); response.Status = CartResponseStatus.WARNING; return(response); } try { ch.AddEntry(itemToAdd, item.Quantity); response.Message = String.Format("Added {0} item(s) with ISBN number {1} to the Wish List ({2}).", addedQuantity.ToString(), item.Code, cartname); var addedItem = new CartItem(); addedItem.Code = item.Code; addedItem.Quantity = item.Quantity; response.ItemsAdded.Add(addedItem); //too bad this doesn't work... //ch.Cart.Modified = DateTime.Now; //ch.Cart.AcceptChanges(); return(response); } catch (Exception ex) { response.Status = CartResponseStatus.ERROR; response.Message = ex.Message; return(response); } }
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest)] //the entire parameter must be serialized to a string (no individual raw POST values) public CartResponse Delete(string cartName) { Guid userId = ProfileContext.Current.UserId; CartHelper helper = new CartHelper(cartName, userId); var response = new CartResponse(); helper.Cart.Delete(); helper.Cart.AcceptChanges(); return(response); }
public static async Task <CartResponse> GetCartItems(int user_id) { CartResponse cart = new CartResponse(); using (HttpClient httpClient = new HttpClient(new NativeMessageHandler())) { var response = await httpClient.GetAsync(String.Format(Config.GetCartItems, user_id)); var json = await response.Content.ReadAsStringAsync(); cart = JsonConvert.DeserializeObject <CartResponse>(json); } return(cart); }
public static async Task <CartResponse> UpdateCartItemQuantity(Dictionary <string, int> data) { CartResponse cart = new CartResponse(); using (HttpClient httpClient = new HttpClient(new NativeMessageHandler())) { var jsonData = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json"); var response = await httpClient.PostAsync(Config.DeleteCartItem, jsonData); var json = await response.Content.ReadAsStringAsync(); cart = JsonConvert.DeserializeObject <CartResponse>(json); } return(cart); }
/// <summary> /// Request shopping cart. /// </summary> /// <param name="request">Shopping cart request message.</param> /// <returns>Shopping cart response message.</returns> public CartResponse GetCart(CartRequest request) { var response = new CartResponse(request.RequestId); // Validate client tag and access token if (!ValidRequest(request, response, Validate.ClientTag | Validate.AccessToken)) { return(response); } // Always return recomputed shopping cart response.Cart = Mapper.ToDataTransferObject(_shoppingCart); return(response); }
public CartResponse TryToAddCart(CartRequest cartRequest) { var product = _productRepository.GetProduct(cartRequest.ProductId); string cartResponseMessage; if (product == null) { throw new ProductNotFoundException($"There is no product for this id :{cartRequest.ProductId}", $"Bu ürün Id si ile ürün bulunamadı ÜrünId:{cartRequest.ProductId}"); } if (cartRequest.Quantity > product.Stock) { throw new ProductStockExceedException($"The amount({cartRequest.Quantity}) you want to add is more than the stock amount({product.Stock}) of the product", $"Eklemek istediğiniz miktar({cartRequest.Quantity}) ürünün stok miktarından({product.Stock}) fazladır"); } var cartInRepo = _cartRepository.GetCart(product.Id); if (cartInRepo != null) { cartInRepo.Quantity += cartRequest.Quantity; _cartRepository.UpdateCard(cartInRepo); cartResponseMessage = $"Cart Updated"; } else { var newCart = new Cart(GenerateUniqueId(), cartRequest.ProductId, cartRequest.Quantity); _cartRepository.InsertCard(newCart); cartResponseMessage = $"Cart Inserted"; } product.Stock -= cartRequest.Quantity; _productRepository.UpdateProduct(product); var response = new CartResponse { Message = cartResponseMessage, AllCarts = _cartRepository.GetAllCarts() }; return(response); }
public CartResponse GetCart(string cartId) { var client = new RestClient(Setting.CartServiceEndPoint); var request = new RestRequest("/Cart/{CartId}"); request.AddUrlSegment("CartId", cartId); var response = client.Execute <CartAddResponse>(request); var result = new CartResponse { CartId = response.Data.CartId, ProductIds = response.Data.ProductIds, ItemCount = response.Data.ProductIds.Count() }; return(result); }
public async Task <ActionResult <CartResponse> > GetMyCart() { var customerId = getUserMetaData().Id; var cachedValue = await cache.TryGet(customerId); if (cachedValue != null) { return(Ok(CartResponse.Of(cachedValue))); } var newCart = new Cart(customerId); await cache.Set(newCart); return(Ok(CartResponse.Of(newCart))); }
public IActionResult GetCart() { var userContext = _dbContext.Set <User>() .Include(x => x.Cart) .Include(x => x.Cart.ProductCarts) .ThenInclude(pc => pc.Product); var userEmail = User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Name)?.Value; if (userEmail == null) { return(BadRequest("Your session has ended please try to login again")); } var user = userContext.FirstOrDefault(x => x.Email == userEmail); if (user == null) { return(BadRequest("Your session has ended")); } if (user.Cart == null) { var emptyCart = new CartResponse() { Products = new List <CartProduct>(), CompletePrice = 0 }; return(Ok(emptyCart)); } var products = user.Cart.ProductCarts.Select(x => new CartProduct { Name = x.Product.DisplayName, Amount = x.Amount, ProductId = x.ProductId.ToString(), DiscountedPrice = x.Product.DiscountedPrice, Total = (x.Product.DiscountedPrice == 0 ? x.Product.Price : x.Product.DiscountedPrice) * x.Amount, Price = x.Product.Price }).ToList(); var cart = new CartResponse() { Products = products, CompletePrice = products.Sum(y => y.Total) }; return(Ok(cart)); }
public CartResponse Select(string cartName) { CartResponse response = new CartResponse(); if (Mediachase.Commerce.Orders.Cart.LoadByCustomerAndName(ProfileContext.Current.UserId, cartName) != null) { NWTD.Profile.ActiveCart = cartName; global::NWTD.Orders.Cart.Reminder = false; response.Status = CartResponseStatus.OK; response.Message = string.Format("{0} is now the active Wish List.", cartName); } else { response.Status = CartResponseStatus.ERROR; response.Message = string.Format("There is no Wish List named {0} for this user.", cartName); } return(response); }
public ShoppingCart GetCart() { CartRequest request = new CartRequest(); request.RequestId = NewRequestId; request.AccessToken = AccessToken; request.ClientTag = ClientTag; request.Action = "Read"; CartResponse response = ActionServiceClient.GetCart(request); if (request.RequestId != response.CorrelationId) { throw new ApplicationException("GetCart: Request and CorrelationId do not match."); } return(response.Cart); }
/// <summary> /// Sets (add, edit, delete) shopping cart data. /// </summary> /// <param name="request">Shopping cart request message.</param> /// <returns>Shopping cart response message.</returns> public CartResponse SetCart(CartRequest request) { CartResponse response = new CartResponse(); response.CorrelationId = request.RequestId; // Validate client tag and access token if (!ValidRequest(request, response, Validate.ClientTag | Validate.AccessToken)) { return(response); } if (request.Action == "Read") { // Do nothing, just return cart } else if (request.Action == "Create") { _shoppingCart.AddItem(request.CartItem.Id, request.CartItem.Name, request.CartItem.Quantity, request.CartItem.UnitPrice); } else if (request.Action == "Update") { // Either shipping method or quantity requires update if (!string.IsNullOrEmpty(request.ShippingMethod)) { _shoppingCart.ShippingMethod = (ShippingMethod)Enum.Parse(typeof(ShippingMethod), request.ShippingMethod); } else { _shoppingCart.UpdateQuantity(request.CartItem.Id, request.CartItem.Quantity); } } else if (request.Action == "Delete") { _shoppingCart.RemoveItem(request.CartItem.Id); } _shoppingCart.ReCalculate(); response.Cart = Mapper.ToDataTransferObject(_shoppingCart); return(response); }
public async Task <ActionResult <CartResponse> > UpdateMyCart([FromBody] UpdateCartRequest request) { var customerId = getUserMetaData().Id; var cart = await cache.TryGet(customerId); if (cart == null) { cart = new Cart(customerId); } if (request.Count <= 0) { throw new WWSException("Count must be positive", StatusCodes.Status400BadRequest); } try { var item = await inventoryApiClient.GetInventoryItem(request.ItemId).ConfigureAwait(false); var updatedCart = cartService.AddCartItem(cart, item, request); await cache.Invalidate(customerId); await cache.Set(updatedCart); return(Ok(CartResponse.Of(updatedCart))); } catch (StockIsNotEnoughException) { throw new WWSException("Not enough item in stock", StatusCodes.Status400BadRequest); } catch (Refit.ApiException ex) { if (ex.StatusCode == HttpStatusCode.NotFound) { throw new WWSException("Item not found", StatusCodes.Status404NotFound); } else { throw; } } }
protected void btnOrder_Click(object sender, EventArgs e) { using(DBDataContext db = new DBDataContext()) { CartResponse cr = new CartResponse(); Order o = new Order() { Appartmant = txtAppartment.Text.Trim(), Building = txtBuilding.Text.Trim(), City = txtCity.Text.Trim(), Comments = txtComment.Text.Trim(), CreatedOn = DateTime.Now, DeliveryCost = cr.delivery, Email = txtEmail.Text.Trim(), Name = txtName.Text.Trim(), Phone = txtPhone.Text.Trim(), Pnone2 = txtPhone2.Text.Trim(), Status = (int)OrderStatus.ZAKAZAN, Street = txtStreet.Text.Trim(), }; db.Orders.InsertOnSubmit(o); db.SubmitChanges(); Cart cart = Cart.GetCurrentCart(); foreach (CartItem ci in cart.Items) { Item itm = db.Items.First(I=>I.ID == ci.ItemID); OrderDetail od = new OrderDetail() { ItemID = ci.ItemID, ItemCount = ci.ItemCount, Order = o, PricePerItem = itm.TotalPrice }; db.OrderDetails.InsertOnSubmit(od); } db.SubmitChanges(); SMSManager.SendSMSV2ToUser(o.Phone, o.ID, (cr.price + cr.delivery)); SMSManager.SendSMSV2ToAdmin(o.Phone, o.Name, o.ID, cr.count, cr.price); cart.ClearCart(); } Response.Redirect(ResolveUrl("~/CartPage.aspx?accepted=1")); }
//读取购物车 private static async Task <string?> ResponseGetCartGames(Bot bot, ulong steamID) { if ((steamID == 0) || !new SteamID(steamID).IsIndividualAccount) { throw new ArgumentOutOfRangeException(nameof(steamID)); } if (!bot.HasAccess(steamID, BotConfig.EAccess.Master)) { return(null); } if (!bot.IsConnectedAndLoggedOn) { return(FormatBotResponse(bot, Strings.BotNotConnected)); } CartResponse cartResponse = await WebRequest.GetCartGames(bot).ConfigureAwait(false); StringBuilder response = new(); string walletCurrency = bot.WalletCurrency != ECurrencyCode.Invalid ? bot.WalletCurrency.ToString() : "钱包区域未知"; if (cartResponse.cartData.Count > 0) { response.AppendLine(FormatBotResponse(bot, string.Format("购物车总额: {0} {1}", cartResponse.totalPrice / 100.0, walletCurrency))); foreach (CartData cartItem in cartResponse.cartData) { response.AppendLine(string.Format("{0} {1} {2}", cartItem.path, cartItem.name, cartItem.price)); } response.AppendLine(FormatBotResponse(bot, cartResponse.purchaseSelf ? "为自己购买" : "")); response.AppendLine(FormatBotResponse(bot, cartResponse.purchaseGift ? "作为礼物购买" : "")); } else { response.AppendLine(FormatBotResponse(bot, "购物车是空的")); } return(response.Length > 0 ? response.ToString() : null); }
/// <summary> /// Sets shipping method used to compute shipping charges. /// </summary> /// <param name="shippingMethod">The name of the shipper.</param> /// <returns>Updated shopping cart.</returns> public ShoppingCart SetShippingMethod(string shippingMethod) { CartRequest request = new CartRequest(); request.RequestId = NewRequestId; request.AccessToken = AccessToken; request.ClientTag = ClientTag; request.Action = "Update"; request.ShippingMethod = shippingMethod; CartResponse response = ActionServiceClient.SetCart(request); if (request.RequestId != response.CorrelationId) { throw new ApplicationException("SetShippingMethod: Request and CorrelationId do not match."); } return(response.Cart); }
public CartResponse AddCart(string cartId, int productId) { var client = new RestClient(Setting.CartServiceEndPoint); var request = new RestRequest("/Cart", Method.POST); request.AddJsonBody(new CartAddRequest { CartId = cartId, ProductId = productId }); var response = client.Execute <CartAddResponse>(request); var result = new CartResponse { CartId = response.Data.CartId, ProductIds = response.Data.ProductIds, ItemCount = response.Data.ProductIds.Count() }; return(result); }
public static CartResponse ToCartResponse(this CartReadModel cartReadModel) { var response = new CartResponse { CartId = cartReadModel.Id, CustomerId = cartReadModel.CustomerId, TotalPrice = cartReadModel.TotalPrice }; foreach (var item in cartReadModel.CartItems) { response.Items.Add(new CartItemResponse { ProductName = item.ProductName, Price = item.Price, Quantity = item.Quantity }); } return(response); }
/// <summary> /// Adds an item to the shopping cart. /// </summary> /// <param name="productId">Unique product identifier or item.</param> /// <param name="name">Item name.</param> /// <param name="quantity">Quantity of items.</param> /// <param name="unitPrice">Unit price for each item.</param> /// <returns>Updated shopping cart.</returns> public ShoppingCart AddItem(int productId, string name, int quantity, double unitPrice) { CartRequest request = new CartRequest(); request.RequestId = NewRequestId; request.AccessToken = AccessToken; request.ClientTag = ClientTag; request.Action = "Create"; request.CartItem = new ShoppingCartItem { Id = productId, Name = name, Quantity = quantity, UnitPrice = unitPrice }; CartResponse response = ActionServiceClient.SetCart(request); if (request.RequestId != response.CorrelationId) { throw new ApplicationException("AddItem: Request and CorrelationId do not match."); } return(response.Cart); }
/// <summary> /// Removes a line item from the shopping cart. /// </summary> /// <param name="productId">The item to be removed.</param> /// <returns>Updated shopping cart.</returns> public ShoppingCart RemoveItem(int productId) { CartRequest request = new CartRequest(); request.RequestId = NewRequestId; request.AccessToken = AccessToken; request.ClientTag = ClientTag; request.Action = "Delete"; request.CartItem = new ShoppingCartItem { Id = productId }; CartResponse response = ActionServiceClient.SetCart(request); if (request.RequestId != response.CorrelationId) { throw new ApplicationException("RemoveItem: Request and CorrelationId do not match."); } return(response.Cart); }
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest)] //the entire parameter must be serialized to a string (no individual raw POST values) public CartResponse Update(string cartName, string newName) { Guid userId = ProfileContext.Current.UserId; var response = new CartResponse(); Mediachase.Commerce.Orders.Cart test = Mediachase.Commerce.Orders.Cart.LoadByCustomerAndName(userId, newName); if (!CartNameIsValid(newName)) { response.Message = "Invalid Wish List name! The Wish List name may only contain letters, numbers, spaces, and underscores"; response.Status = CartResponseStatus.ERROR; } else if (CartNameIsDuplicate(userId, newName)) { //uh oh, there's already a cart by this name! response.Status = CartResponseStatus.ERROR; response.Message = string.Format("A Wish List with the name {0} already exists", newName); } else { CartHelper helper = new CartHelper(cartName, userId); helper.Cart.Name = newName; if (helper.Cart.OrderForms[cartName] != null) { OrderForm childForm = helper.Cart.OrderForms[cartName]; childForm.Name = newName; childForm.AcceptChanges(); } helper.Cart.AcceptChanges(); if (NWTD.Profile.ActiveCart.Equals(cartName)) { NWTD.Profile.ActiveCart = newName; //if it's the active cart, we need to update that information in state } response.Message = "Successfully updated the Wish List."; } return(response); }
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest)] //the entire parameter must be serialized to a string (no individual raw POST values) public CartResponse AddItems(List <CartItem> items, string cartname) { CartResponse response = new CartResponse(); List <string> messages = new List <string>(); foreach (CartItem item in items) { CartResponse addResponse = this.AddItem(item, cartname); if (addResponse.Status == CartResponseStatus.ERROR || addResponse.Status == CartResponseStatus.WARNING) { messages.Add(string.Format("The item with ISBN number {0} could not be added to your Wish List. {1} <br />", item.Code, addResponse.Message)); response.Status = CartResponseStatus.WARNING; } else { response.ItemsAdded.Add(item); messages.Add(response.Message); } } response.Message = string.Join(Environment.NewLine, messages.ToArray()); return(response); }
public List <CartResponse> GetAllCart(int userId) { try { using (this.connection) { SqlCommand command = new SqlCommand("spGetAllCart", this.connection); command.CommandType = CommandType.StoredProcedure; command.Parameters.AddWithValue("@UserId", userId); List <CartResponse> cartRsponse = new List <CartResponse>(); CartResponse cart = new CartResponse(); this.connection.Open(); SqlDataReader dataReader = command.ExecuteReader(); while (dataReader.Read()) { if (dataReader != null) { cart.CartId = (int)dataReader["CartId"]; cart.BookQuantity = (int)dataReader["BookQuanity"]; cart.UserId = (int)dataReader["UserId"]; cart.BookName = dataReader["BookName"].ToString(); cart.BookAutherName = dataReader["BookAutherName"].ToString(); cart.BookPrice = (int)dataReader["BookPrice"]; cart.BookImage = dataReader["BookImage"].ToString(); cartRsponse.Add(cart); break; } } return(cartRsponse); } } catch (Exception e) { throw new Exception(e.Message); } }
protected void Page_Load(object sender, EventArgs e) { CartResponse cr = new CartResponse(); CartItems.InnerText = Cart.GetCurrentCart().Items.Count == 0 ? "Корзина пуста" : string.Format("В корзине товаров: {0} На сумму: {1} руб.", cr.count, cr.price); }
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest)] //the entire parameter must be serialized to a string (no individual raw POST values) public CartResponse Copy(string cartName, string newName, bool activate) { var response = new CartResponse(); //the response for the operation if (string.IsNullOrEmpty(newName)) { newName = string.Format("Copy of {0}", cartName); } Guid userId = ProfileContext.Current.UserId; //make sure there isn't already a cart with the same name if (!CartNameIsValid(newName)) { response.Message = "Invalid Wish List name! The Wish List name may only contain letters, numbers, spaces, and underscores"; response.Status = CartResponseStatus.ERROR; } else if (CartNameIsDuplicate(userId, newName)) { response.Message = "Invalid Wish List name! There is already a Wish List with this name"; response.Status = CartResponseStatus.ERROR; } else { CartHelper originalCartHelper = new CartHelper(cartName, userId); //create the new cart Mediachase.Commerce.Orders.Cart cartToAdd = NWTD.Orders.Cart.CreateCart(ProfileContext.Current.Profile.Account, newName); //now, we'll need a CartHelper to start adding the lines CartHelper newCartHelper = new CartHelper(cartToAdd); //now add all the same line items to the new cart, copying any relevant metadata (gratis and quantity) foreach (LineItem lineItem in originalCartHelper.LineItems) { //get the entry Entry entry = CatalogContext.Current.GetCatalogEntry(lineItem.CatalogEntryId, new Mediachase.Commerce.Catalog.Managers.CatalogEntryResponseGroup(CatalogEntryResponseGroup.ResponseGroup.CatalogEntryFull)); if (entry != null) { newCartHelper.AddEntry(entry, lineItem.Quantity); } //get the item we just added and set its gratis LineItem addedItem = newCartHelper.LineItems.Single(li => li.CatalogEntryId == entry.ID); addedItem["Gratis"] = lineItem["Gratis"]; //addedItem.ShippingAddressId = lineItem.ShippingAddressId; newCartHelper.RunWorkflow("CartValidate"); cartToAdd.AcceptChanges(); } //save the changes cartToAdd.AcceptChanges(); if (activate) { NWTD.Profile.ActiveCart = cartToAdd.Name; response.Message = "Wish List succesfully copied and made active"; } else { response.Message = "Wish List succesfully copied"; } } return(response); }
protected void Page_PreRender(object sender, EventArgs e) { using (DBDataContext DB = new DBDataContext()) { Cart cart = Cart.GetCurrentCart(); int[] cartIds = cart.Items.Select(CI => CI.ItemID).ToArray(); var list = (from I in DB.Items where cartIds.Contains(I.ID) select new { ID = I.ID, Name = I.Name, Price = I.TotalPrice, WholePrice = I.TotalWholePrice, WholeMin = I.WholeMinCount, ShortDescription = I.ShortDescription, Count = cart.GetByItemID(I.ID).ItemCount }).ToList(); lvCartItems.DataSource = from I in list select new { I.ID, I.Name, I.WholeMin, I.Price, I.WholePrice, I.Count, TotalPrice = I.Count * (cart.Items.First(ITM => ITM.ItemID == I.ID).ItemCount < I.WholeMin ? I.Price : I.WholePrice), I.ShortDescription }; lvCartItems.DataBind(); CartResponse cr = new CartResponse(); lblTotalCount.Text = cr.count.ToString(); lblTotalPrice.Text = (cr.price + cr.delivery).ToString(); trSummary.Visible = trDelivery.Visible = divMakeOrder.Visible = cr.count != 0; lblDeliveryPrice.Text = cr.delivery.ToString(); } }
async void getData() { try { if (Application.Current.Properties.ContainsKey("user_id")) { Config.ShowDialog(); var cartItems = await CartLogic.GetCartItems(int.Parse(Application.Current.Properties["user_id"].ToString())); if (cartItems.status == 200) { if (!string.IsNullOrEmpty(cartItems.coupon_code_id)) { CouponCodeId = cartItems.coupon_code_id; } if (string.IsNullOrEmpty(cartItems.coupon_code_id)) { IsCodeVisible.IsVisible = false; IsApplyVisible.IsVisible = true; } else { IsCodeVisible.IsVisible = true; IsApplyVisible.IsVisible = false; Code.Text = cartItems.coupon_code; } _cart = cartItems; listProducts.ItemsSource = cartItems.data.cart_data; if (_cart.data.user_address == null && _address_id == 0) { addAddress.IsVisible = false; } else { addAddress.IsVisible = true; if (_address_id == 0) { _address_id = cartItems.data.user_address.id; _full_address = cartItems.data.user_address.full_address; _address_type = cartItems.data.user_address.address_type; _default_address = cartItems.data.user_address.default_address == 0 ? "" : " (Default)"; } addAddress.Text = _address_id != 0 ? _full_address : cartItems.data.user_address.full_address; } item_total.Text = "Rs " + cartItems.total_amount; delivery_fee.Text = "Rs " + Convert.ToDecimal(cartItems.delivery_charges); to_pay.Text = "Rs " + cartItems.cost; total_discount.Text = "- Rs " + cartItems.promo_amount; Config.HideDialog(); if (string.IsNullOrEmpty(cartItems.coupon_code_id)) { discount_layout.IsVisible = false; } else { discount_layout.IsVisible = true; } } else { EmptyCart(); } } else { EmptyCart(); } Config.HideDialog(); } catch (Exception ex) { Config.ErrorStore("CheckoutPage-getData", ex.Message); Config.HideDialog(); EmptyCart(); Config.ErrorSnackbarMessage(Config.ApiErrorMessage); } }
//Get cart private void Handle(GetCart command) { Respond(CartResponse.FromCartState(cartState)); }