protected void rpNews_ItemCommand(object source, RepeaterCommandEventArgs e) { string strCommand = e.CommandName; int nID = ConvertData.ConvertToInt(e.CommandArgument); Basket objBasket = new Basket(); switch (strCommand) { case "Delete": int nDelete = objBasket.DeleteById(nID); BindDataToGrid(1); break; case "Edit": string sEdit = Constants.ROOT + Pages.BackEnds.ADMIN + "?" + Constants.PAGE + "=" + Pages.BackEnds.STR_ORDER_ADD + "&" + Constants.ACTION + "=" + Constants.ACTION_EDIT + "&" + Constants.ACTION_ID + "=" + nID; Response.Redirect(sEdit); break; case "Active": int nActive = objBasket.UpdateStatus(nID, EnumeType.INACTIVE); BindDataToGrid(1); break; case "Inactive": int nInactive = objBasket.UpdateStatus(nID, EnumeType.ACTIVE); BindDataToGrid(1); break; } }
public PostageResult CalculatePostageFor(Basket basket) { if (basket == null) { throw new ArgumentNullException("basket"); } var postages = postageRepository.GetAll(); var postZone = basket.Country.PostZone; var totalWeight = (int)basket.BasketItems .Sum(bi => bi.TotalWeight); var postageToApply = postages .Where(p => totalWeight <= p.MaxWeight && p.IsActive) .OrderBy(p => p.MaxWeight) .FirstOrDefault(); var postageDescription = string.Format("for {0}", basket.Country.Name); if (postageToApply == null) return PostageResult.WithDefault(postZone, postageDescription); var multiplier = postZone.Multiplier; var total = new Money(Math.Round(postageToApply.Price.Amount * multiplier, 2, MidpointRounding.AwayFromZero)); return PostageResult.WithPrice(total, postageDescription); }
public void SetUp() { var size = new Size { Name = "Medium", IsActive = true, IsInStock = true }; var product = new Product { Name = "Widget", Description = "Our best Widget", }; using (DomainEvent.TurnOff()) { product.AddSize(size); } InSession(session => session.Save(product)); sizeId = size.Id; var basket = new Basket(); InSession(session => session.Save(basket)); basketId = basket.Id; }
static void PopulateOrderForView(Order order, Basket basket) { if (order.Basket == null) order.Basket = basket; if (order.Contact == null) order.Contact = new Contact(); if (order.Contact1 == null) order.Contact1 = new Contact(); if (order.Card == null) order.Card = new Card(); }
public void SetUpTest() { _basket = new Basket(); _basket.Items.Add(new BasketItem { Id = 2 }); _basket.State = BasketState.ContainsStuff; Console.WriteLine(); }
/// <summary> /// remove unlisted symbols, leaving only verified symbols remaining. /// tradelink has a list of verified nasdaq and nyse symbols, but it is not guaranteed to be all inclusive. /// </summary> /// <param name="input"></param> /// <returns></returns> public static Basket RemoveUnlisted(Basket input) { Basket output = new BasketImpl(); for (int i =0; i<input.Count; i++) if (NYSE.isListed(input[i].symbol) || NASDAQ.isListed(input[i].symbol)) output.Add(input[i]); return output; }
public void SetUpTest() { _basket = new Basket(); _basket.Items.Add(new BasketItem { Id = 2 }); _basket.State = BasketState.Archived; Console.WriteLine(); }
public void Setup() { _basket = new Basket(new BasketService( new ProductRepository(), new DiscountOfferCalculatorService(new DiscountOfferRepository()), new BulkBuytOfferCalculatorService(new BulkBuyOfferRepository()), new NonOfferCalculatorService())); }
public void Can_Serialize_Class_with_Typed_Dictionary() { var basket = new Basket(); basket.Items.Add(new Item { type = 1, color = 2 }, 10); basket.Items.Add(new Item { type = 4, color = 1 }, 20); Serialize(basket); }
protected void lbtSusscess_Click(object sender, EventArgs e) { Basket objBasket = new Basket(); objBasket.Data.BasketName = "Đơn hàng ngày " + DateTime.Now.ToString("hh:mm:ss tt mm/dd/yyyy "); objBasket.Data.CustomerName = txtFullName.Text; if (fileYC.Value != "") { objBasket.Data.BasketContent = Support.UploadFile(fileYC, "fileyc"); } else { objBasket.Data.BasketContent = ""; } objBasket.Data.CustomerAddress = txtAddress.Text; objBasket.Data.CustomerTel = txtPhone.Text; objBasket.Data.CustomerEmail = txtEmail.Text; objBasket.Data.Status = 0; objBasket.Data.DateCreated = ConvertData.ConvertToString(ConvertData.ConvertDatetimeToInt(DateTime.Today)); int nResult = objBasket.Insert(); //insert item to table basket details string nID = Request.QueryString["id"]; int nCount = nID.Split('-').Length - 1; ArrayList alProducts = new ArrayList(nID.Split('-')); BasketDetail objBasketDetail = new BasketDetail(); string strInsert; if (nResult > 0) { for (int i = 0; i < nCount; i++) { objBasketDetail.Data.ProductID2 = ConvertData.ConvertToInt(alProducts[i]); objBasketDetail.Data.BasketID = nResult; objBasketDetail.Data.Quantity = 1; objBasketDetail.Insert(); } if (Request.Cookies["simpleCart"] != null) { HttpCookie myCookie = new HttpCookie("simpleCart"); myCookie.Expires = DateTime.Now.AddDays(-1d); Response.Cookies.Add(myCookie); } Response.Redirect("Default.aspx?mess=2"); } else { strInsert = "Đơn đặt hàng bị lỗi ! bạn vui lòng pm Y!M hỗ trợ để chúng tôi giúp bạn. Thân ái"; MessageBoxss.Show(strInsert); } }
public void ShouldAddItemsToTheBasket() { var basket = new Basket(); var item2 = new Item { NoOfProducts = 2, PriceOfProduct = "3", ProductName = "Milk", ItemCreatedDate = new DateTime(2013, 09, 18), ItemExpiryDate = new DateTime(2013, 09, 21) }; int count = basket.AddItemsToTheBasket(item2).Count; Assert.That(count, Is.EqualTo(1)); }
static Basket() { if (HttpContext.Current.Session["ShoppingCart"] == null) { Instance = new Basket(); Instance.Items = new List<BasketItem>(); HttpContext.Current.Session["ShoppingCart"] = Instance; } else { Instance = (Basket)HttpContext.Current.Session["ShoppingCart"]; } }
/// <summary> /// removes all elements of baskets that match. /// unmatching elements are ignored /// </summary> /// <param name="mb"></param> public void Remove(Basket mb) { List<int> remove = new List<int>(); for (int i = 0; i < symbols.Count; i++) for (int j = 0; j < mb.Count; j++) if (symbols[i].Symbol == mb[j].Symbol) remove.Add(i); for (int i = remove.Count - 1; i >= 0; i--) symbols.RemoveAt(remove[i]); }
public void AddItem([FromBody] OnlineStore.Contracts.Basket addItem) { var basketId = dbContext.Baskets.FirstOrDefault(k => k.BasketName == addItem.BasketName); if (basketId != null) { var bskId = dbContext.Items.Where(i => i.BasketId == basketId.BasketId).ToList(); var getItem = addItem.BasketItems.First(); var item = dbContext.Items.FirstOrDefault(k => k.BasketId == basketId.BasketId && k.ProductId == getItem.ProductId); if (item == null) { item = new Item { ProductId = getItem.ProductId, BasketId = basketId.BasketId, Price = getItem.Price, Quantity = getItem.Quantity }; dbContext.Items.AddObject(item); } else { item.Quantity++; } dbContext.SaveChanges(); dbContext.AcceptAllChanges(); } else { basketId = new Basket { BasketName = addItem.BasketName, CustomerId = addItem.CustomerId, CreatedDateTime = DateTime.Now, IsCheckedOut = false }; dbContext.Baskets.AddObject(basketId); dbContext.SaveChanges(); var itemToAdd = addItem.BasketItems.First(); var item = dbContext.Products.First(p => p.ProductId == itemToAdd.ProductId); dbContext.Items.AddObject(new Item { BasketId = basketId.BasketId, ProductId = item.ProductId, Price = item.Price, Quantity = 1 }); dbContext.SaveChanges(); } }
public static void Main(string[] args) { Basket<int> basket = new Basket<int>(5); Producer producer = new ProducerImpl(basket); Consumer consumer = new ConsumerImpl(basket); producer.produce(); consumer.consume(); Console.ReadLine(); }
/// <summary> /// gets symbols removed from newbasket, given original basket /// </summary> /// <param name="old"></param> /// <param name="newb"></param> /// <returns></returns> public static Basket Subtract(Basket old, Basket newb) { if (old.Count == 0) return new BasketImpl(); Basket rem = new BasketImpl(); foreach (Security sec in old) { if (!newb.ToString().Contains(sec.Symbol)) rem.Add(sec); } return rem; }
public void AddBasket(int lastID, DateTime? date) { //TODO: modify AddProduct method and ModifyProduct make one method remove code duplication Basket tmpProduct = new Basket() { ID = (lastID++), CreationDate = date }; _basketDataProvider.Add(tmpProduct); }
public double CalculateBasket(int[] books) { Basket basket = new Basket(); foreach (int bookCode in books) { basket.AddBookToCheapestPack(bookCode); } return basket.GetTotalPrice(); }
public CreateBasketResponse CreateBasket(CreateBasketRequest request) { CreateBasketResponse response = new CreateBasketResponse(); Basket basket = new Basket(); basket.SetDeliveryOption(GetCheapestDeliveryOption()); AddProductsToBasket(request.ProductsToAdd, basket); ThrowExceptionIfBasketIsInvalid(basket); _basketRepository.Save(basket); _uow.Commit(); response.Basket = basket.ConvertToBasketView(); return response; }
public void TestAddProductToBasket() { var product = new Product { Id = 1 }; var basket = new Basket { Products = new Collection<BasketProduct>() }; this._fakePersistence.Setup(p => p.Add(It.IsAny<BasketProduct>())).Callback(() => { return; }); this._target.AddProductToBasket(basket, product, 1); Assert.IsTrue(basket.Products.Any(bp => bp.Product == product)); }
public void Updates_country() { var basket = new Basket(); basketRepository.Expect(x => x.GetById(22)).Return(basket); var form = BuildPlaceOrderRequest(true); context.HttpContext.Request.Expect(x => x.Form).Return(form); var order = (Order)binder.BindModel(context, new ModelBindingContext()); basket.CountryId.ShouldEqual(1); }
public void AddItem(Basket addItem) { HttpClient client = new HttpClient(); MediaTypeFormatter formatter = new JsonMediaTypeFormatter(); HttpContent content = new ObjectContent<Basket>(addItem, formatter); var response = client.PostAsync(string.Format("http://localhost:38696/api/MyCart"), content).Result; if (response.IsSuccessStatusCode) { } }
/// <summary> /// Add a <see cref="Product"/> to an existing <see cref="Basket"/>. /// </summary> /// <param name="basket">The <see cref="Basket"/> to add a <see cref="Product"/> too.</param> /// <param name="productToAdd">The new <see cref="Product"/> for the <paramref name="basket"/>.</param> /// <param name="quantity">The quantity of <see cref="Product"/> for the <paramref name="basket"/>.</param> /// <returns>The <see cref="Basket"/>.</returns> public Basket AddProductToBasket(Basket basket, Product productToAdd, int quantity) { var basketProduct = new BasketProduct { Basket = basket, Product = productToAdd, Quantity = quantity }; basket.Products.Add(basketProduct); this._persistence.Change(basket); this._persistence.Commit(); return basket; }
public void GetCurrentBasket_should_return_the_basket_collections_current_basket() { var basket = new Basket {Id = 201}; var oldBasket = new Basket {Id = 200}; user.AddBasket(basket); user.AddBasket(oldBasket); var currentBasket = basketService.GetCurrentBasketForCurrentUser(); currentBasket.ShouldBeTheSameAs(basket); }
/// <summary> /// removes duplicate symbols /// </summary> /// <param name="input"></param> /// <returns></returns> public static Basket RemoveDupe(Basket input) { List<string> cache = new List<string>(); Basket output = new BasketImpl(); for (int i = 0; i < input.Count; i++) if (!cache.Contains(input[i].Symbol)) { output.Add(input[i]); cache.Add(input[i].Symbol); } return output; }
public void ShouldCheckOutTheSelectedItemsFromTheBasket() { var item1 = new Item { ProductName = "Butter", PriceOfProduct = "3", NoOfProducts = 2, ItemCreatedDate = new DateTime(2013, 09, 18), ItemExpiryDate = new DateTime(2013, 09, 21) }; var item2 = new Item { ProductName = "Milk", PriceOfProduct = "2", NoOfProducts = 2, ItemCreatedDate = new DateTime(2013, 09, 18), ItemExpiryDate = new DateTime(2013, 09, 21) }; IBasket basket = new Basket(); basket.AddItemsToTheBasket(item1); basket.AddItemsToTheBasket(item2); var checkout = new Checkout(basket); IList<Item> itemsForCheckout = checkout.ItemsSelectedForCheckOut().ToList(); Assert.That(itemsForCheckout.Count, Is.EqualTo(2)); }
private ShopViewData IndexViewData(Basket basket) { if (basket.Country == null) { basket.Country = countryRepository.GetById(basket.CountryId); } var countries = countryRepository.GetAll().Active().InOrder(); return ShopView.Data.WithBasket(basket) .WithCountries(countries) .WithTotalPostage(postageService.CalculatePostageFor(basket)); }
/// <summary> /// checks if the bubble is in the basket or not! /// </summary> /// <param name="basket">the basket. Passed just to get the xy position of the basket</param> /// <returns>true if the ball is in the basket</returns> public bool checkBasketCatch(Basket basket) { //compare the position of the particle with the position of the basket if ((Position.X + CircleTexture.Width / 2 > basket.Position.X && //check if it is in the right bound Position.X + CircleTexture.Width / 2 < basket.Position.X + basket.BasketTexture.Width) &&//check if it is in the left bound Position.Y + CircleTexture.Height > basket.Position.Y) {//make sure it is below the top of the basket Remove = true;//if it is, remove it! return true; } return false; }
public static void Main() { Console.WriteLine("How many of each Harry Potter book does the customer have?"); Basket basket = new Basket(); List<Book> books = new List<Book>(); basket.BooksInBasket = books; for (int i = 1; i <= 5; i++) { Console.WriteLine("Copies of Book" + i + "?"); string userInput = Console.ReadLine(); int NumberOfBook = int.Parse(userInput); if (NumberOfBook != 0) { for (int j = 1; j <= NumberOfBook; j++) { Book book = new Book(); book.BookId = i; basket.BooksInBasket.Add(book); } } } var booksCount = basket.BooksInBasket.Count(); var costBeforeDiscounts = booksCount*8; int finalPrice; Console.WriteLine("There are " + booksCount + " books in the basket..."); Console.ReadLine(); var distinctBooks = GetNumberOfDistinctBooks(basket.BooksInBasket); Console.WriteLine(distinctBooks + " distinct books"); if (distinctBooks < 2) { finalPrice = costBeforeDiscounts; Console.WriteLine("Final price is " + finalPrice); } else { switch (distinctBooks) { case 2: double discount = (distinctBooks * 8)*0.95; break; } } Console.ReadLine(); }
private static void AddOrderLinesFromBasket(Order order, Basket basket) { foreach (var basketItem in basket.BasketItems) { var productName = basketItem.Size.Product.Name + (basketItem.Size.Name == "-" ? "" : " - " + basketItem.Size.Name); order.AddLine( productName, basketItem.Quantity, basketItem.Size.Product.Price, basketItem.Size.Product.UrlName, basketItem.Size.Product.Id, basketItem.Size.Name); } }
public void Pickup(Basket b) { b.CatchApple(this); Destroy(); }
public virtual pci.Basket GetPciBasket(Customer customer, Basket basket) { var pciBasket = new pci.Basket { ID = basket.Id.ToString(), IsAgent = false, ISOCurrencyCode = _currencyService.GetCurrencyIsoCodeById(basket.CurrencyId.ToString()), IsFromUS = _siteService.GetMicroSiteById(customer.MicroSiteId).IsUS, Total = basket.Total, CountryCode = basket.PurchaseLanguage }; var itemsToAdd = new List <pci.BasketLine>(); foreach (var basketLine in basket.BasketLines) { var item = new pci.BasketLine { Name = _ticketService.GetTicketById(basketLine.TicketId.ToString()).Name, //***get ticket name from related ticket TicketQuantity = basketLine.TicketQuantity ?? 0, TicketType = basketLine.TicketType, Total = (basketLine.LineTotal != null)? basketLine.LineTotal.Value : (decimal)0.0, Date = DateTime.Now }; if (basketLine.FixedDateTicket != null && basketLine.FixedDateTicket.Value) { item.Date = basketLine.TicketDate; } itemsToAdd.Add(item); } pciBasket.Items = itemsToAdd.ToArray(); string email; if (!string.IsNullOrWhiteSpace(customer.FriendlyEmail)) { email = customer.FriendlyEmail; } else { email = customer.Email.Trim().StartsWith(customer.Id + "_") ? customer.Email.Trim().Replace(customer.Id + "_", string.Empty) : customer.Email.Trim(); } var user = new pci.User { FirstName = customer.Firstname, LastName = customer.Lastname, AddressLine1 = customer.AddressLine1, City = customer.City, PostCode = customer.PostCode, CountryCode = customer.CountryId, EmailAddress = email, FullName = customer.Firstname + " " + customer.Lastname }; pciBasket.User = user; return(pciBasket); }
public ExpressCheckoutResult DoExpressCheckout() { HttpContext context = HttpContext.Current; TraceContext trace = context.Trace; string traceCategory = this.GetType().ToString(); ExpressCheckoutSession paypalSession = ExpressCheckoutSession.Current; if (paypalSession == null) { //EXIT WITH EXCEPTION ErrorType[] customErrorList = new ErrorType[1]; ErrorType customError = new ErrorType(); customError.ErrorCode = "SESSION"; customError.ShortMessage = "Missing Token"; customError.LongMessage = "The PayPal session token was expired or unavailable. Please try again."; customErrorList[0] = customError; return(new ExpressCheckoutResult(0, string.Empty, customErrorList)); } trace.Write(traceCategory, "Detected PayPal Token:" + paypalSession.Token); trace.Write(traceCategory, "Token Expiration:" + paypalSession.TokenExpiration.ToLongDateString()); if (string.IsNullOrEmpty(paypalSession.PayerID)) { //EXIT WITH EXCEPTION ErrorType[] customErrorList = new ErrorType[1]; ErrorType customError = new ErrorType(); customError.ErrorCode = "SESSION"; customError.ShortMessage = "Missing Payer ID"; customError.LongMessage = "The PayPal Payer ID is not present."; customErrorList[0] = customError; return(new ExpressCheckoutResult(0, string.Empty, customErrorList)); } trace.Write(traceCategory, "Detected PayPal Payer ID:" + paypalSession.PayerID); //GET THE CURRENCY FOR THE TRANSACTION string storeCurrencyCode = Token.Instance.Store.BaseCurrency.ISOCode; CurrencyCodeType baseCurrencyCode = PayPalProvider.GetPayPalCurrencyType(storeCurrencyCode); //CREATE THE EXPRESS CHECKOUT DoExpressCheckoutPaymentRequestType expressCheckoutRequest = new DoExpressCheckoutPaymentRequestType(); expressCheckoutRequest.DoExpressCheckoutPaymentRequestDetails = new DoExpressCheckoutPaymentRequestDetailsType(); expressCheckoutRequest.DoExpressCheckoutPaymentRequestDetails.Token = paypalSession.Token; expressCheckoutRequest.DoExpressCheckoutPaymentRequestDetails.PaymentAction = this.UseAuthCapture ? PaymentActionCodeType.Sale : PaymentActionCodeType.Authorization; expressCheckoutRequest.DoExpressCheckoutPaymentRequestDetails.PaymentActionSpecified = true; expressCheckoutRequest.DoExpressCheckoutPaymentRequestDetails.PayerID = paypalSession.PayerID; expressCheckoutRequest.Version = "1.0"; //SET THE ORDER TOTAL AMOUNTS Basket basket = Token.Instance.User.Basket; trace.Write(traceCategory, "Set Order Totals"); LSDecimal curOrderTotal = basket.Items.TotalPrice(); LSDecimal curShippingTotal = basket.Items.TotalPrice(OrderItemType.Shipping) + GetShippingCouponTotal(basket.Items); LSDecimal curHandlingTotal = basket.Items.TotalPrice(OrderItemType.Handling); LSDecimal curTaxTotal = basket.Items.TotalPrice(OrderItemType.Tax); LSDecimal curItemTotal = curOrderTotal - (curShippingTotal + curHandlingTotal + curTaxTotal); //MAKE SURE OUR BREAKDOWN IS VALID if ((curShippingTotal < 0) || (curHandlingTotal < 0) || (curTaxTotal < 0) || (curItemTotal < 0)) { //THE BREAKDOWN IS INVALID, DO NOT INCLUDE IT IN THE REQUEST curShippingTotal = 0; curHandlingTotal = 0; curTaxTotal = 0; curItemTotal = curOrderTotal; } //SET THE PAYMENT DETAILS expressCheckoutRequest.DoExpressCheckoutPaymentRequestDetails.PaymentDetails = new PaymentDetailsType[1]; expressCheckoutRequest.DoExpressCheckoutPaymentRequestDetails.PaymentDetails[0] = new PaymentDetailsType(); PaymentDetailsType paymentDetails = expressCheckoutRequest.DoExpressCheckoutPaymentRequestDetails.PaymentDetails[0]; paymentDetails.OrderTotal = new BasicAmountType(); paymentDetails.OrderTotal.currencyID = baseCurrencyCode; paymentDetails.OrderTotal.Value = string.Format("{0:##,##0.00}", curOrderTotal); paymentDetails.ItemTotal = new BasicAmountType(); paymentDetails.ItemTotal.currencyID = baseCurrencyCode; paymentDetails.ItemTotal.Value = string.Format("{0:##,##0.00}", curItemTotal); paymentDetails.ShippingTotal = new BasicAmountType(); paymentDetails.ShippingTotal.currencyID = baseCurrencyCode; paymentDetails.ShippingTotal.Value = string.Format("{0:##,##0.00}", curShippingTotal); paymentDetails.HandlingTotal = new BasicAmountType(); paymentDetails.HandlingTotal.currencyID = baseCurrencyCode; paymentDetails.HandlingTotal.Value = string.Format("{0:##,##0.00}", curHandlingTotal); paymentDetails.TaxTotal = new BasicAmountType(); paymentDetails.TaxTotal.currencyID = baseCurrencyCode; paymentDetails.TaxTotal.Value = string.Format("{0:##,##0.00}", curTaxTotal); trace.Write(traceCategory, "Order Total: " + curOrderTotal); trace.Write(traceCategory, "Item Total: " + curItemTotal); trace.Write(traceCategory, "Shipping Total: " + curShippingTotal); trace.Write(traceCategory, "Handling Total: " + curHandlingTotal); trace.Write(traceCategory, "Tax Total: " + curTaxTotal); //SET THE BUTTON SOURCE trace.Write(traceCategory, "Set Button Source"); paymentDetails.ButtonSource = "ablecommerce-EC"; //SET THE NOTIFY URL string notifyUrl = GetStoreUrl() + "/ProcessPayPal.ashx"; trace.Write(traceCategory, "IPN Callback URL: " + notifyUrl); paymentDetails.NotifyURL = notifyUrl; //WE HAVE ALL NECESSARY INFORMATION TO DO EXPRESS CHECKOUT //COMMIT THE ORDER BEFORE SUBMITTING THE PAYPAL TRANSACTION //CREATE THE ABLECOMMERCE PAYMENT ITEM Payment checkoutPayment = new Payment(); checkoutPayment.PaymentMethodId = GetPayPalPaymentMethodId(false); checkoutPayment.Amount = curOrderTotal; checkoutPayment.CurrencyCode = baseCurrencyCode.ToString(); //AT THIS POINT, EXECUTE THE CHECKOUT TO SUBMIT THE ORDER CheckoutRequest checkoutRequest = new CheckoutRequest(checkoutPayment); CheckoutResponse checkoutResponse = basket.Checkout(checkoutRequest); int orderId = checkoutResponse.OrderId; //LOAD THE ORDER AND RE-OBTAIN THE PAYMENT RECORD TO AVOID DATA INCONSISTENCIES Order order = OrderDataSource.Load(orderId); if (order == null) { //EXIT WITH EXCEPTION ErrorType[] customErrorList = new ErrorType[1]; ErrorType customError = new ErrorType(); customError.ErrorCode = "ORDER"; customError.ShortMessage = "Your order could not be completed at this time."; customError.LongMessage = "Your order could not be completed at this time and payment was not processed. " + string.Join(" ", checkoutResponse.WarningMessages.ToArray()); customErrorList[0] = customError; return(new ExpressCheckoutResult(0, string.Empty, customErrorList)); } int findPaymentId = checkoutPayment.PaymentId; foreach (Payment payment in order.Payments) { if (payment.PaymentId == findPaymentId) { checkoutPayment = payment; } } //SET THE DESCRIPTION paymentDetails.OrderDescription = "Order #" + order.OrderNumber.ToString(); paymentDetails.Custom = orderId.ToString(); //EXECUTE PAYPAL REQUEST trace.Write(traceCategory, "Do Request"); DoExpressCheckoutPaymentResponseType expressCheckoutResponse = (DoExpressCheckoutPaymentResponseType)SoapCall("DoExpressCheckoutPayment", expressCheckoutRequest); ErrorType[] responseErrors = null; PaymentStatus finalPaymentStatus = PaymentStatus.Unprocessed; bool isPendingeCheck = false; if (expressCheckoutResponse != null) { if (expressCheckoutResponse.Errors == null) { //CREATE THE PAYPAL TRANSACTION RECORD Transaction checkoutTransaction = new Transaction(); PaymentInfoType paymentInfo = expressCheckoutResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0]; isPendingeCheck = (paymentInfo.PaymentStatus == PaymentStatusCodeType.Pending && paymentInfo.PendingReason == PendingStatusCodeType.echeck); PaymentStatusCodeType paymentStatus = paymentInfo.PaymentStatus; switch (paymentStatus) { case PaymentStatusCodeType.Completed: case PaymentStatusCodeType.Processed: case PaymentStatusCodeType.Pending: if (isPendingeCheck) { finalPaymentStatus = PaymentStatus.CapturePending; checkoutTransaction.ResponseCode = "PENDING"; checkoutTransaction.ResponseMessage = "echeck"; } else { finalPaymentStatus = (paymentStatus != PaymentStatusCodeType.Pending) ? PaymentStatus.Captured : PaymentStatus.Authorized; } checkoutTransaction.TransactionStatus = TransactionStatus.Successful; break; default: finalPaymentStatus = PaymentStatus.Unprocessed; checkoutTransaction.TransactionStatus = TransactionStatus.Failed; checkoutTransaction.ResponseCode = expressCheckoutResponse.Ack.ToString(); checkoutTransaction.ResponseMessage = paymentStatus.ToString().ToUpperInvariant(); break; } checkoutTransaction.TransactionType = this.UseAuthCapture ? TransactionType.Capture : TransactionType.Authorize; checkoutTransaction.Amount = AlwaysConvert.ToDecimal(paymentInfo.GrossAmount.Value, (Decimal)curOrderTotal); checkoutTransaction.AuthorizationCode = paymentInfo.TransactionID; checkoutTransaction.AVSResultCode = "U"; checkoutTransaction.ProviderTransactionId = paymentInfo.TransactionID; checkoutTransaction.Referrer = context.Request.ServerVariables["HTTP_REFERER"]; checkoutTransaction.PaymentGatewayId = this.PaymentGatewayId; checkoutTransaction.RemoteIP = context.Request.ServerVariables["REMOTE_ADDR"]; checkoutPayment.Transactions.Add(checkoutTransaction); //FIND THE WAITING FOR IPN TRANSACTION AND REMOVE int i = checkoutPayment.Transactions.Count - 1; while (i >= 0) { if (string.IsNullOrEmpty(checkoutPayment.Transactions[i].AuthorizationCode)) { checkoutPayment.Transactions.DeleteAt(i); } i--; } } else { //SOME SORT OF ERROR ATTEMPTING CHECKOUT responseErrors = expressCheckoutResponse.Errors; } } else { //NO RESPONSE, GENERATE CUSTOM ERROR responseErrors = new ErrorType[1]; ErrorType customError = new ErrorType(); customError.ErrorCode = "NORESP"; customError.ShortMessage = "No Response From Server"; customError.LongMessage = "The PayPal service is unavailable at this time."; responseErrors[0] = customError; } trace.Write(traceCategory, "Do Request Done"); //ERRORS IN RESPONSE? if ((responseErrors != null) && (responseErrors.Length > 0)) { //CREATE THE PAYPAL TRANSACTION RECORD FOR ERROR Transaction checkoutTransaction = new Transaction(); finalPaymentStatus = PaymentStatus.Unprocessed; checkoutTransaction.TransactionStatus = TransactionStatus.Failed; checkoutTransaction.Amount = curOrderTotal; checkoutTransaction.AuthorizationCode = string.Empty; checkoutTransaction.Referrer = context.Request.ServerVariables["HTTP_REFERER"]; checkoutTransaction.PaymentGatewayId = this.PaymentGatewayId; checkoutTransaction.RemoteIP = context.Request.ServerVariables["REMOTE_ADDR"]; checkoutTransaction.ResponseCode = responseErrors[0].ShortMessage; checkoutTransaction.ResponseMessage = responseErrors[0].LongMessage; checkoutPayment.Transactions.Add(checkoutTransaction); } //MAKE SURE PAYMENT STATUS IS CORRECT checkoutPayment.ReferenceNumber = paypalSession.Payer; checkoutPayment.PaymentStatus = finalPaymentStatus; if (isPendingeCheck) { checkoutPayment.PaymentStatusReason = "echeck"; } //RECALCULATE THE ORDER STATUS (BUG 6384) AND TRIGGER PAYMENT EVENTS (BUG 8650) order.Save(true, true); //CLEAR THE TOKENS SET IN SESSION paypalSession.Delete(); return(new ExpressCheckoutResult(orderId, string.Empty, responseErrors)); }
private void BindBasket(Basket basket) { //GET LIST OF PRODUCTS IList <BasketItem> _Products = new List <BasketItem>(); decimal _ProductTotal = 0; decimal _DiscountTotal = 0; bool showTaxLineItems = GetShowTaxLineItems(); // MAKE SURE ITEMS ARE PROPERTY SORTED BEFORE DISPLAY basket.Items.Sort(new BasketItemComparer()); foreach (BasketItem item in basket.Items) { if (item.OrderItemType == OrderItemType.Product) { if (!item.IsChildItem) { // ROOT LEVEL ITEMS GET ADDED _Products.Add(item); _ProductTotal += TaxHelper.GetShopExtendedPrice(basket, item); } else { BasketItem rootItem = item.GetParentItem(true); if (rootItem != null && rootItem.Product != null && rootItem.Product.Kit != null && rootItem.Product.Kit.ItemizeDisplay) { // ITEMIZED DISPLAY ENABLED, SHOW THIS CHILD ITEM _Products.Add(item); _ProductTotal += TaxHelper.GetShopExtendedPrice(basket, item); } } } else if (item.OrderItemType == OrderItemType.Discount) { _DiscountTotal += TaxHelper.GetShopExtendedPrice(basket, item); } else if (item.OrderItemType == OrderItemType.Tax && showTaxLineItems && AbleContext.Current.User.IsAnonymous && !AbleContext.Current.User.PrimaryAddress.IsValid) { _Products.Add(item); item.Name = "<span class=\"label\">" + item.Name + " (estimated)</span>"; } else if (item.OrderItemType == OrderItemType.Tax && showTaxLineItems) { _Products.Add(item); } } if (_Products.Count > 0) { //BIND BASKET ITEMS BasketRepeater.DataSource = _Products; BasketRepeater.DataBind(); if (_DiscountTotal != 0) { Discounts.Text = _DiscountTotal.LSCurrencyFormat("ulc"); DiscountsPanel.Visible = true; } else { DiscountsPanel.Visible = false; } Discounts.Text = _DiscountTotal.LSCurrencyFormat("ulc"); SubTotal.Text = (_ProductTotal + _DiscountTotal).LSCurrencyFormat("ulc"); //UPDATE CHECKOUT LINK //CheckoutLink.NavigateUrl = AbleCommerce.Code.NavigationHelper.GetCheckoutUrl(); ShowBasket(true); } else { ShowBasket(false); } }
public async Task Insert(Basket basket) { await Task.Run(() => this.mockDatabase.Baskets.Add(basket.Id, basket)); }
public async Task <IActionResult> UpdateBasket([FromBody] Basket value) { var basket = await _repository.UpdateBasketAsync(value); return(Ok(basket)); }
public void CanCheckoutAndCreateOrder() { IRepository <Customer> customers = new MockContext <Customer>(); IRepository <Product> products = new MockContext <Product>(); products.Insert(new Product() { Id = "1", Price = 10.00m }); products.Insert(new Product() { Id = "2", Price = 5.00m }); IRepository <Basket> baskets = new MockContext <Basket>(); Basket basket = new Basket(); basket.BasketItems.Add(new BasketItem() { ProductId = "1", Quantity = 2, BasketId = basket.Id }); basket.BasketItems.Add(new BasketItem() { ProductId = "1", Quantity = 1, BasketId = basket.Id }); baskets.Insert(basket); IBasketService basketService = new BasketService(products, baskets); IRepository <Order> orders = new MockContext <Order>(); IOrderService orderService = new OrderService(orders); customers.Insert(new Customer() { Id = "1", Email = "*****@*****.**", ZipCode = "20451" }); IPrincipal FakeUser = new GenericPrincipal(new GenericIdentity("*****@*****.**", "Forms"), null); var controller = new BasketController(basketService, orderService, customers); var httpContext = new MockHttpContext(); httpContext.User = FakeUser; httpContext.Request.Cookies.Add(new System.Web.HttpCookie("eCommerceBasket") { Value = basket.Id }); controller.ControllerContext = new System.Web.Mvc.ControllerContext(httpContext, new System.Web.Routing.RouteData(), controller); //Act Order order = new Order(); controller.CheckOut(order); //Assert Assert.AreEqual(2, order.OrderItems.Count); Assert.AreEqual(0, basket.BasketItems.Count); Order orderInRep = orders.Find(order.Id); Assert.AreEqual(2, orderInRep.OrderItems.Count); }
static void Main(string[] args) { var randomSeed = new Random(); var basket = new Basket(randomSeed); Console.WriteLine($"Basket's weight is {basket.Weight} kg."); // //Creating players: Console.Write("Enter the number of players (from 2 to 8): "); string input = Console.ReadLine(); int minPlayers = 2; int maxPlayers = 8; int numOfPlayers = InputValidation(input, minPlayers, maxPlayers); var playersList = new List <Player>(); for (int i = 1; i <= numOfPlayers; i++) { Console.WriteLine($"Select the type of {i} player"); Console.WriteLine("1 - Regular Player"); Console.WriteLine("2 - Notebook Player"); Console.WriteLine("3 - Uber-Player"); Console.WriteLine("4 - Cheater"); Console.WriteLine("5 - Uber-Cheater Player"); int type = InputValidation(Console.ReadLine(), 1, 5); switch (type) { case 1: playersList.AddPlayerToList(new RegularPlayer(randomSeed)); break; case 2: playersList.AddPlayerToList(new NotebookPlayer(randomSeed)); break; case 3: playersList.AddPlayerToList(new UberPlayer()); break; case 4: playersList.AddPlayerToList(new CheaterPlayer(randomSeed)); break; case 5: playersList.AddPlayerToList(new UberCheaterPlayer()); break; } } var totalTriesList = new List <List <int> >(); foreach (var player in playersList) { totalTriesList.Add(player.PersonalTries); } // //Let the game begin! for (int tries = 1; tries <= 100; tries++) { Console.WriteLine($"Try #{tries}"); foreach (var player in playersList) { int newTry = player.Guess(Basket.MinWeight, Basket.MaxWeight, ref totalTriesList); Console.WriteLine($"{player.TypeName} {player.Name} says {newTry}"); if (newTry == basket.Weight) { Console.WriteLine($"{player.TypeName} {player.Name} wins!"); Console.ReadKey(); return; } } Console.WriteLine(); } // //If nobody guessed correctly: var bestTriesList = new List <int>(); foreach (Player player in playersList) { player.BestTry = player.PersonalTries.GetBestTry(basket.Weight); Console.WriteLine($"{player.TypeName} {player.Name}'s closest guess is {player.BestTry}"); bestTriesList.Add(player.BestTry); } int totalBestTry = bestTriesList.GetBestTry(basket.Weight); foreach (Player player in playersList) { if (player.BestTry == totalBestTry) { Console.WriteLine($"{player.TypeName} {player.Name} wins! Their closest guess is {player.BestTry}"); } } Console.ReadKey(); }
public void SetUp() { _stock = new Stock(); _basket = new Basket(); }
protected int sid = 0;//结算供应商ID public void LoadPage() { sid = RequestTool.RequestInt("sid", 0); basket = new Basket(sid); bool offlinepay = false; if (CurrentUser.Transport_Price_id == "") { CurrentUser.Transport_Price_id = "0"; } List <Lebi_Transport_Price> prices = B_Lebi_Transport_Price.GetList("id in (" + CurrentUser.Transport_Price_id + ")", ""); if (prices.Count == 0) { Response.Write(Tag("请先选择配送方式")); Response.End(); return; } Lebi_Transport_Price currenttranprice = new Lebi_Transport_Price(); Lebi_Transport currenttran = new Lebi_Transport(); foreach (Lebi_Transport_Price price in prices) { currenttran = B_Lebi_Transport.GetModel(price.Transport_id); if (currenttran == null) { Response.Write(Tag("请先选择配送方式")); Response.End(); return; } if (basket.cashsupplierid == price.Supplier_id)//商城收款,供应商发货的情况必须用在线支付,所以下永远匹配不上。 { currenttranprice = price; } } string where = "IsUsed=1"; //if (prices.Count > 1 || currenttranprice.Supplier_id > 0 || basket.cashsupplierid > 0) //{ // where += " and Code='OnlinePay'"; //} //else //{ if (currenttran.IsCanofflinePay == 1 && currenttranprice.IsCanofflinePay == 1) { offlinepay = true; } if (offlinepay == false) { where += " and Code!='OfflinePay'"; } //} string onpaywhere = "IsUsed=1 and parentid=0 and ','+Language_ids+',' like '%," + CurrentLanguage.id + ",%'"; //string useragent=Request.UserAgent.ToString().ToLower(); //if (!useragent.Contains("micromessenger")) //{ // onpaywhere += " and Code!='weixinpay'"; //} if (CurrentSite.IsMobile == 1) { onpaywhere += " and (showtype='' or showtype like '%wap%')"; } else { onpaywhere += " and (showtype='' or showtype like '%web%')"; } Shop.Bussiness.SystemLog.Add(onpaywhere); pays = B_Lebi_Pay.GetList(where, "Sort desc"); if ((CurrentUser.Pay_id == 0 || pays.Count == 1) && pays.Count > 0) { CurrentUser.Pay_id = pays.FirstOrDefault().id; } onpays = B_Lebi_OnlinePay.GetList(onpaywhere, "Sort desc"); if (onpays.Count == 0) { CurrentUser.OnlinePay_id = 0; } else { if (CurrentUser.OnlinePay_id == 0 || onpays.Count == 1) { CurrentUser.OnlinePay_id = onpays.FirstOrDefault().id; } else { bool flag = false; foreach (Lebi_OnlinePay p in onpays) { if (p.id == CurrentUser.OnlinePay_id) { flag = true; break; } } if (flag == false) { CurrentUser.OnlinePay_id = onpays.FirstOrDefault().id; } } } }
public async Task PlaceOrder(Basket basket) { await httpClient.PostJsonAsync("/orders", basket); }
public virtual Task <Basket> CreateBasketModelAsync(int sessionId) { var basketModel = new Basket(sessionId); return(Task.FromResult(basketModel)); }
// Use this for initialization void Start() { basket = obj_basket.GetComponent <Basket>(); }
public void Setup() { basket = new Basket(); checkout = new Checkout(); }
public void AddProductToSell(string name, double price, Basket <Cheese> product) { throw new System.NotImplementedException(); }
void _strategy_SendBasket(Basket b, int id) { SendDebug("Basket subscription not implemented yet. StrategyBase should use the basket from basket.xml"); }
public OrderBySomething(Basket items, object criterio) { this.items = items; this.criterio = criterio; }
public void AddToBasket(Product product) { Basket basket = new Basket(); List <Product> products = new List <Product>(); //gets url of previous page string previousPage = (string)Session["Referrer"]; //assigns basket id from user identity basket.CustomerId = User.Identity.GetUserId(); //gets basketjson from GetBasket method JsonResult basketJsonResult = GetBasket(); Basket loadedBasket = (Basket)basketJsonResult.Data; //if there are no product in the basket create new basket cookie and add product, else add new product or update product quantity in existing product if (loadedBasket.Products == null) { products.Add(product); basket.Products = products; basket.CustomerId = User.Identity.GetUserId(); string basketJson = new JavaScriptSerializer().Serialize(basket); var cookie = new HttpCookie("Basket", basketJson) { Expires = DateTime.Now.AddHours(1) }; HttpContext.Response.SetCookie(cookie); } else { var cookie = Request.Cookies["Basket"]; basket = new JavaScriptSerializer().Deserialize <Basket>(cookie.Value); //for every product in the basket foreach (Product productLoop in basket.Products.ToList()) { //if the previous page session isn't null and the previous page was ViewBasket and a product, the current productLoop quantity becomes the product quantity if (previousPage != null && previousPage.Equals("ViewBasket") && product.Id == productLoop.Id) { productLoop.Quantity = product.Quantity; } //if product exists update productLoop quantity else if (product.Id == productLoop.Id) { productLoop.Quantity += product.Quantity; } //if previous page is just the product id, add new product to basket else if (previousPage.Equals(Convert.ToString(product.Id))) { basket.Products.Add(product); break; } } string basketJson = new JavaScriptSerializer().Serialize(basket); cookie = new HttpCookie("Basket", basketJson) { Expires = DateTime.Now.AddHours(1) }; Response.Cookies.Add(cookie); } }
public ExpressCheckoutResult SetExpressCheckout() { HttpContext context = HttpContext.Current; User user = Token.Instance.User; Basket basket = user.Basket; //MAKE SURE BASKET IS PROPERLY PACKAGED FOR CHECKOUT basket.Package(); //GET EXISTING SESSION IF IT IS PRESENT ExpressCheckoutSession existingSession = ExpressCheckoutSession.Current; if (existingSession != null) { WebTrace.Write("Existing session token: " + existingSession.Token); } //CREATE THE EXPRESS CHECKOUT REQUEST OBJECT SetExpressCheckoutRequestType expressCheckoutRequest = new SetExpressCheckoutRequestType(); expressCheckoutRequest.SetExpressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType(); if (existingSession != null) { expressCheckoutRequest.SetExpressCheckoutRequestDetails.Token = existingSession.Token; } expressCheckoutRequest.Version = "1.0"; //GET THE CURRENCY FOR THE TRANSACTION string baseCurrencyCode = Token.Instance.Store.BaseCurrency.ISOCode; CurrencyCodeType baseCurrency = PayPalProvider.GetPayPalCurrencyType(baseCurrencyCode); //BUILD THE REQUEST DETAILS SetExpressCheckoutRequestDetailsType expressCheckoutDetails = expressCheckoutRequest.SetExpressCheckoutRequestDetails; LSDecimal basketTotal = basket.Items.TotalPrice(); WebTrace.Write("Basket Total: " + basketTotal.ToString()); expressCheckoutDetails.OrderTotal = new BasicAmountType(); expressCheckoutDetails.OrderTotal.currencyID = baseCurrency; expressCheckoutDetails.OrderTotal.Value = string.Format("{0:##,##0.00}", basketTotal); expressCheckoutDetails.MaxAmount = new BasicAmountType(); expressCheckoutDetails.MaxAmount.currencyID = baseCurrency; expressCheckoutDetails.MaxAmount.Value = string.Format("{0:##,##0.00}", basketTotal + 50); //SET THE URLS string storeUrl = GetStoreUrl(); expressCheckoutDetails.ReturnURL = storeUrl + "/PayPalExpressCheckout.aspx?Action=GET"; expressCheckoutDetails.CancelURL = storeUrl + "/PayPalExpressCheckout.aspx?Action=CANCEL"; //SET THE CUSTOM VALUE TO THE USER ID FOR MATCHING DURING GET expressCheckoutDetails.Custom = "UID" + basket.UserId.ToString(); //SET THE CUSTOMER ADDRESS Address billingAddress = user.PrimaryAddress; AddressType address = new AddressType(); address.Name = billingAddress.FirstName + " " + billingAddress.LastName; address.Street1 = billingAddress.Address1; address.Street2 = billingAddress.Address2; address.CityName = billingAddress.City; address.PostalCode = billingAddress.PostalCode; if (billingAddress.Country != null) { address.Country = PayPalProvider.GetPayPalCountry(billingAddress.CountryCode); } else { address.Country = CountryCodeType.US; } address.CountrySpecified = true; expressCheckoutDetails.BuyerEmail = billingAddress.Email; expressCheckoutDetails.Address = address; //SET THE PAYMENT ACTION expressCheckoutDetails.PaymentAction = this.UseAuthCapture ? PaymentActionCodeType.Sale : PaymentActionCodeType.Authorization; expressCheckoutDetails.PaymentActionSpecified = true; //EXECUTE REQUEST SetExpressCheckoutResponseType expressCheckoutResponse; context.Trace.Write("DO SOAP CALL"); expressCheckoutResponse = (SetExpressCheckoutResponseType)SoapCall("SetExpressCheckout", expressCheckoutRequest); context.Trace.Write("CHECK SOAP RESULT"); if (expressCheckoutResponse == null) { ErrorType[] customErrorList = new ErrorType[1]; ErrorType customError = new ErrorType(); customError.ErrorCode = "NORESP"; customError.ShortMessage = "No Response From Server"; customError.LongMessage = "The PayPal service is unavailable at this time."; customErrorList[0] = customError; return(new ExpressCheckoutResult(0, string.Empty, customErrorList)); } //IF ERRORS ARE IN RESPONSE, RETURN THEM AND EXIT PROCESS if (expressCheckoutResponse.Errors != null) { return(new ExpressCheckoutResult(0, string.Empty, expressCheckoutResponse.Errors)); } //NO ERRORS FOUND, PUT PAYPAL DETAILS INTO SESSION context.Trace.Write("Store PayPal Token In Session"); ExpressCheckoutSession newSession = new ExpressCheckoutSession(); newSession.Token = expressCheckoutResponse.Token; newSession.TokenExpiration = DateTime.UtcNow.AddHours(3); newSession.Save(); context.Trace.Write("Saved PayPal Token:" + newSession.Token); context.Trace.Write("Token Expiration:" + newSession.TokenExpiration.ToLongDateString()); //RETURN TO CALLER INCLUDING REDIRECTION URL string redirectUrl = "https://www" + (this.UseSandbox ? ".sandbox" : string.Empty) + ".paypal.com/webscr?cmd=_express-checkout&token=" + expressCheckoutResponse.Token; return(new ExpressCheckoutResult(0, redirectUrl, null)); }
private void ProcessRules(BreadCrumbItem breadCrumbItem) { int id; if (breadCrumbItem.Url == "#") { return; } switch (breadCrumbItem.Url.ToLowerInvariant()) { case "~/admin/orders/shipments/editshipment.aspx": id = AlwaysConvert.ToInt(Request.QueryString["OrderShipmentId"]); breadCrumbItem.Url += "?OrderShipmentId=" + id; breadCrumbItem.Title = string.Format(breadCrumbItem.Title, id); break; case "~/admin/products/editproduct.aspx": case "~/admin/products/variants/variants.aspx": case "~/admin/products/variants/options.aspx": case "~/admin/products/digitalgoods/digitalgoods.aspx": case "~/admin/products/kits/editkit.aspx": case "~/admin/products/assets/images.aspx": case "~/admin/products/editproducttemplate.aspx": case "~/admin/products/specials/default.aspx": int categoryId = AbleCommerce.Code.PageHelper.GetCategoryId(); id = AbleCommerce.Code.PageHelper.GetProductId(); Product product = ProductDataSource.Load(id); if (categoryId > 0) { breadCrumbItem.Url += "?CategoryId=" + categoryId + "&ProductId=" + id; } else { breadCrumbItem.Url += "?ProductId=" + id; } breadCrumbItem.Title = string.Format(breadCrumbItem.Title, product.Name); break; case "~/admin/orders/vieworder.aspx": case "~/admin/orders/edit/editorderitems.aspx": case "~/admin/orders/viewdigitalgoods.aspx": case "~/admin/orders/payments/default.aspx": case "~/admin/orders/shipments/default.aspx": id = AbleCommerce.Code.PageHelper.GetOrderId(); Order order = OrderDataSource.Load(id); breadCrumbItem.Url += "?OrderNumber=" + order.OrderNumber; breadCrumbItem.Title = string.Format(breadCrumbItem.Title, order.OrderNumber); break; case "~/admin/marketing/coupons/editcoupon.aspx": id = AlwaysConvert.ToInt(Request.QueryString["CouponId"]); Coupon coupon = CouponDataSource.Load(id); breadCrumbItem.Url += "?CouponId=" + id; breadCrumbItem.Title = string.Format(breadCrumbItem.Title, coupon.Name); break; case "~/admin/products/variants/editoption.aspx": case "~/admin/products/variants/editchoices.aspx": id = AlwaysConvert.ToInt(Request.QueryString["OptionId"]); Option option = OptionDataSource.Load(id); breadCrumbItem.Url += "?OptionId=" + id; breadCrumbItem.Title = string.Format(breadCrumbItem.Title, option.Name); break; case "~/admin/products/giftwrap/editwrapgroup.aspx": id = AlwaysConvert.ToInt(Request.QueryString["WrapGroupId"]); WrapGroup wrapGroup = WrapGroupDataSource.Load(id); breadCrumbItem.Url += "?WrapGroupId=" + id; breadCrumbItem.Title = string.Format(breadCrumbItem.Title, wrapGroup.Name); break; case "~/admin/marketing/email/managelist.aspx": id = AlwaysConvert.ToInt(Request.QueryString["EmailListId"]); EmailList emailList = EmailListDataSource.Load(id); if (emailList != null) { breadCrumbItem.Url += "?EmailListId=" + id; breadCrumbItem.Title = string.Format(breadCrumbItem.Title, emailList.Name); } break; case "~/admin/marketing/discounts/editdiscount.aspx": id = AlwaysConvert.ToInt(Request.QueryString["VolumeDiscountId"]); VolumeDiscount discount = VolumeDiscountDataSource.Load(id); breadCrumbItem.Url += "?VolumeDiscountId=" + id; breadCrumbItem.Title = string.Format(breadCrumbItem.Title, discount.Name); break; case "~/admin/catalog/editwebpage.aspx": id = AbleCommerce.Code.PageHelper.GetWebpageId(); Webpage webpage = WebpageDataSource.Load(id); breadCrumbItem.Url += "?WebpageId=" + id; breadCrumbItem.Title = string.Format(breadCrumbItem.Title, webpage.Name); break; case "~/admin/catalog/editLink.aspx": id = AbleCommerce.Code.PageHelper.GetLinkId(); Link link = LinkDataSource.Load(id); breadCrumbItem.Url += "?LinkId=" + id; breadCrumbItem.Title = string.Format(breadCrumbItem.Title, link.Name); break; case "~/admin/people/users/edituser.aspx": id = AlwaysConvert.ToInt(Request.QueryString["UserId"]); User user = UserDataSource.Load(id); breadCrumbItem.Url += "?UserId=" + id; breadCrumbItem.Title = string.Format(breadCrumbItem.Title, user.UserName); break; case "~/admin/digitalgoods/editdigitalgood.aspx": case "~/admin/digitalgoods/serialkeyproviders/defaultprovider/configure.aspx": id = AlwaysConvert.ToInt(Request.QueryString["DigitalGoodId"]); DigitalGood dg = DigitalGoodDataSource.Load(id); if (dg != null) { breadCrumbItem.Url += "?DigitalGoodId=" + id; breadCrumbItem.Title = string.Format(breadCrumbItem.Title, dg.Name); } break; case "~/admin/products/producttemplates/editproducttemplate.aspx": id = AlwaysConvert.ToInt(Request.QueryString["ProductTemplateId"]); ProductTemplate template = ProductTemplateDataSource.Load(id); if (template == null) { InputField field = InputFieldDataSource.Load(AlwaysConvert.ToInt(Request.QueryString["InputFieldId"])); if (field != null) { template = field.ProductTemplate; id = template.Id; } } if (template != null) { breadCrumbItem.Url += "?ProductTemplateId=" + id; breadCrumbItem.Title = string.Format(breadCrumbItem.Title, template.Name); } else { } break; case "~/admin/reports/dailyabandonedbaskets.aspx": id = AlwaysConvert.ToInt(Request.QueryString["BasketId"]); Basket basket = BasketDataSource.Load(id); if (basket != null) { breadCrumbItem.Url += "?ReportDate=" + basket.User.LastActivityDate.Value.ToShortDateString(); } break; } // resolve relative urls if (breadCrumbItem.Url.StartsWith("~/")) { breadCrumbItem.Url = Page.ResolveUrl(breadCrumbItem.Url); } }
public GetExpressCheckoutResult GetExpressCheckout() { HttpContext context = HttpContext.Current; ExpressCheckoutSession existingSession = ExpressCheckoutSession.Current; if (existingSession == null) { ErrorType[] customErrorList = new ErrorType[1]; ErrorType customError = new ErrorType(); customError.ErrorCode = "SESSION"; customError.ShortMessage = "Missing Token"; customError.LongMessage = "The PayPal session token was expired or unavailable. Please try again."; customErrorList[0] = customError; return(new GetExpressCheckoutResult(null, customErrorList)); } context.Trace.Write("Detected PayPal Token:" + existingSession.Token); context.Trace.Write("Token Expiration:" + existingSession.TokenExpiration.ToLongDateString()); GetExpressCheckoutDetailsRequestType expressCheckoutRequest = new GetExpressCheckoutDetailsRequestType(); expressCheckoutRequest.Token = existingSession.Token; expressCheckoutRequest.Version = "1.0"; //EXECUTE REQUEST GetExpressCheckoutDetailsResponseType expressCheckoutResponse; expressCheckoutResponse = (GetExpressCheckoutDetailsResponseType)SoapCall("GetExpressCheckoutDetails", expressCheckoutRequest); if (expressCheckoutResponse == null) { ErrorType[] customErrorList = new ErrorType[1]; ErrorType customError = new ErrorType(); customError.ErrorCode = "NORESP"; customError.ShortMessage = "No Response From Server"; customError.LongMessage = "The PayPal service is unavailable at this time."; customErrorList[0] = customError; return(new GetExpressCheckoutResult(null, customErrorList)); } //IF ERRORS ARE IN RESPONSE, RETURN THEM AND EXIT PROCESS if (expressCheckoutResponse.Errors != null) { return(new GetExpressCheckoutResult(null, expressCheckoutResponse.Errors)); } //GET THE DETAILS OF THE REQUEST GetExpressCheckoutDetailsResponseDetailsType expressCheckoutDetails; expressCheckoutDetails = expressCheckoutResponse.GetExpressCheckoutDetailsResponseDetails; //MAKE SURE CUSTOMER IDS MATCH User currentUser = Token.Instance.User; if (expressCheckoutDetails.Custom != ("UID" + currentUser.UserId.ToString())) { ErrorType[] customErrorList = new ErrorType[1]; ErrorType customError = new ErrorType(); customError.ErrorCode = "USER"; customError.ShortMessage = "User Mismatch"; customError.LongMessage = "The PayPal basket did not have the expected user context."; customErrorList[0] = customError; Logger.Warn("Error in PayPal GetExpressCheckout. User ID detected in PayPal response: " + expressCheckoutDetails.Custom + ", Customer User ID: " + currentUser.UserId.ToString()); return(new GetExpressCheckoutResult(null, customErrorList)); } //CHECK WHETHER AN EXISTING USER IS ASSOCIATED WITH THE RETURNED PAYPAL ID //IF THE CURRENT USER DOES NOT MATCH, LOG IN THE PAYPAL USER ACCOUNT string paypalEmail = expressCheckoutDetails.PayerInfo.Payer; string paypalPayerID = expressCheckoutDetails.PayerInfo.PayerID; //PAYER ID IS SUPPOSED TO BE UNIQUE REGARDLESS OF EMAIL ADDRESS, LOOK FOR ASSOCIATED ACCT User paypalUser = UserDataSource.LoadForPayPalId(paypalPayerID); //IF NOT FOUND, SEE IF AN ACCOUNT EXISTS WITH THAT EMAIL AS USERNAME if (paypalUser == null) { paypalUser = UserDataSource.LoadForUserName(paypalEmail); } if (paypalUser != null) { //WE FOUND AN ACCOUNT FOR THIS PAYPAL USER context.Trace.Write(this.GetType().ToString(), "PAYPAL USER FOUND IN DATABASE"); if (currentUser.UserId != paypalUser.UserId) { //THE PAYPAL USER IS NOT THE CURRENT USER CONTEXT, SO TRANSFER THE BASKET context.Trace.Write(this.GetType().ToString(), "MOVE BASKET TO " + paypalUser.UserName); Basket.Transfer(currentUser.UserId, paypalUser.UserId, true); //REMOVE PAYPAL EXPRESS SESSION FROM OLD USER SESSION ExpressCheckoutSession.Delete(currentUser); } } else { //WE DID NOT FIND AN ACCOUNT context.Trace.Write(this.GetType().ToString(), "PAYPAL USER NOT FOUND IN DATABASE"); if (currentUser.IsAnonymous) { //CURRENT USER IS ANON, REGISTER A NEW USER ACCOUNT context.Trace.Write(this.GetType().ToString(), "REGISTERING " + paypalEmail); MembershipCreateStatus status; paypalUser = UserDataSource.CreateUser(paypalEmail, paypalEmail, StringHelper.RandomString(8), string.Empty, string.Empty, true, 0, out status); paypalUser.PayPalId = paypalPayerID; paypalUser.Save(); Basket.Transfer(currentUser.UserId, paypalUser.UserId, true); //REMOVE PAYPAL EXPRESS SESSION FROM OLD USER SESSION ExpressCheckoutSession.Delete(currentUser); } else { //UPDATE THE PAYPAL ID OF THE CURRENTLY AUTHENTICATED USER context.Trace.Write(this.GetType().ToString(), "ASSIGNING CURRENT USER TO " + paypalEmail); paypalUser = currentUser; paypalUser.PayPalId = paypalPayerID; paypalUser.Save(); } } //PAYPAL HAS AUTHENTICATED THE USER FormsAuthentication.SetAuthCookie(paypalUser.UserName, false); //UPDATE THE PRIMARY ADDRESS INFORMATION FOR THE USER Address billingAddress = paypalUser.PrimaryAddress; billingAddress.FirstName = expressCheckoutDetails.PayerInfo.PayerName.FirstName; billingAddress.LastName = expressCheckoutDetails.PayerInfo.PayerName.LastName; billingAddress.Company = expressCheckoutDetails.PayerInfo.PayerBusiness; billingAddress.Address1 = expressCheckoutDetails.PayerInfo.Address.Street1; billingAddress.Address2 = expressCheckoutDetails.PayerInfo.Address.Street2; billingAddress.City = expressCheckoutDetails.PayerInfo.Address.CityName; billingAddress.Province = expressCheckoutDetails.PayerInfo.Address.StateOrProvince; billingAddress.PostalCode = expressCheckoutDetails.PayerInfo.Address.PostalCode; billingAddress.CountryCode = expressCheckoutDetails.PayerInfo.Address.Country.ToString(); if (!string.IsNullOrEmpty(expressCheckoutDetails.ContactPhone)) { billingAddress.Phone = expressCheckoutDetails.ContactPhone; } billingAddress.Email = expressCheckoutDetails.PayerInfo.Payer; billingAddress.Residence = (!string.IsNullOrEmpty(billingAddress.Company)); paypalUser.Save(); //UPDATE THE SHIPPING ADDRESS IN THE BASKET Basket basket = paypalUser.Basket; basket.Package(); foreach (BasketShipment shipment in basket.Shipments) { shipment.AddressId = billingAddress.AddressId; } basket.Save(); //PUT PAYPAL DETAILS INTO SESSION context.Trace.Write(this.GetType().ToString(), "Saving ExpressCheckoutSession"); existingSession.Token = expressCheckoutDetails.Token; existingSession.TokenExpiration = DateTime.UtcNow.AddHours(3); existingSession.PayerID = paypalPayerID; existingSession.Payer = expressCheckoutDetails.PayerInfo.Payer; existingSession.Save(paypalUser); context.Trace.Write("Saved PayPal Token:" + existingSession.Token); context.Trace.Write("Token Expiration:" + existingSession.TokenExpiration.ToLongDateString()); return(new GetExpressCheckoutResult(paypalUser, null)); }
public void SaveBasket(DateTime date, string content) { var basket = new Basket(date, content); basketsDao.CreateBasket(basket); }
public void DeleteBasket(Basket basket) { _repository.Remove(basket); }
public ActionResult <Checkout> Checkout(Basket basket) { return(checkoutService.Checkout(basket)); }
public void CanCheckoutAndCreateOrder() { IRepository <Product> products = new MockContext <Product>(); IRepository <Customer> customers = new MockContext <Customer>(); products.Insert(new Product() { Id = "1", Price = 10.00m }); products.Insert(new Product() { Id = "2", Price = 11.00m }); IRepository <Basket> baskets = new MockContext <Basket>(); Basket basket = new Basket(); basket.BasketItems.Add(new BasketItem() { ProductId = "1", Quantity = 2, BasketId = basket.Id }); basket.BasketItems.Add(new BasketItem() { ProductId = "1", Quantity = 1, BasketId = basket.Id }); baskets.Insert(basket); IBasketService basketService = new BasketService(products, baskets); IRepository <Order> orders = new MockContext <Order>(); IOrderService orderService = new OrderService(orders); //Fake user email customers.Insert(new Customer() { Id = "1", Email = "*****@*****.**", ZipCode = "57000" }); IPrincipal FakeUser = new GenericPrincipal(new GenericIdentity("*****@*****.**", "Forms"), null); var controller = new BasketController(basketService, orderService, customers); var HttpContext = new MockHttpContext(); HttpContext.User = FakeUser; HttpContext.Request.Cookies.Add(new System.Web.HttpCookie("wappBasket") { Value = basket.Id }); controller.ControllerContext = new ControllerContext(HttpContext, new System.Web.Routing.RouteData(), controller); //Act Order order = new Order(); controller.Checkout(order); //Assert Assert.AreEqual(2, order.OrderItems.Count); Assert.AreEqual(0, basket.BasketItems.Count); Order orderInRep = orders.Find(order.Id); Assert.AreEqual(2, orderInRep.OrderItems.Count);//To check whether the item in repo or not }
public async Task DeleteBasketAsync(int basketId) { Basket basket = await GetBasket(basketId); await _basketRepository.DeleteAsync(basket); }
public virtual Task InsertBasketAsync(Basket basket) { _basketStorage.Add(basket); return(Task.CompletedTask); }
async Task <Basket> GetBasketByUserId(string userId) { Basket basket = (await _basketRepository.ListAsync(b => b.UserId == userId)).FirstOrDefault(); return(basket); }
public BasketBuilder() { _basket = WithNoItems(); }
public void AddBasket(Basket basket) { shoppingBasketDbContext.Baskets.Add(basket); }