예제 #1
0
 public ManageController(CartContext cartContext, DataContext context, CustomLogger logger, UserManager <User> userManager)
 {
     _cartContext = cartContext;
     _context     = context;
     _logger      = logger;
     _userManager = userManager;
 }
예제 #2
0
        public ActionResult Index(Models.DB.Models.OrderInfo postback)
        {
            if (this.ModelState.IsValid)
            {
                using (CartContext db = new CartContext())
                {
                    var currCart = cartFunction.GetCurrCart();
                    //var currCart = (CartItem)System.Web.HttpContext.Current.Session["Cart"];
                    var newOrder = new OrderInfo()
                    {
                        CusName     = postback.CusName,
                        CusPhone    = postback.CusPhone,
                        TableNo     = postback.TableNo,
                        Total       = currCart.TotalAmount,
                        OrderStatus = "Payment"
                    };
                    //int currOID = newOrder.OrderID;

                    db.OrderInfos.Add(newOrder);
                    db.SaveChanges();

                    var Order = currCart.ToOrderDetailList(newOrder.OrderID);
                    db.OILs.AddRange(Order);
                    db.SaveChanges();

                    currCart.ClearCart();
                    return(RedirectToAction("Info", new { id = newOrder.OrderID }));
                    //return PartialView("_CartPartial");
                }
                //return RedirectToAction("Action", new { id = currOID });
            }
            //return RedirectToAction("Action", new { id = currOID });
            return(View());
        }
        public void ThenTheImageOfTheShownProductIsTheSameAsTheImageOfTheProductWeChose(string src)
        {
            string url = Driver_init.CartPageWithOrders.GetImageSrc(0);

            CartContext.ClickLinkOfProduct(Driver_init.CartPageWithOrders, 0);
            GoodStateVerificationContext.VerifyProductImageInCart(Driver_init.SingleBookPage, src);
        }
        public void ThenThePriceOfTheShownProductIsTheSameAsThePriceOfTheProductWeChose()
        {
            int price = Driver_init.CartPageWithOrders.GetPriceForType(0);

            CartContext.ClickLinkOfProduct(Driver_init.CartPageWithOrders, 0);
            GoodStateVerificationContext.VerifyItemPriceInCart(Driver_init.SingleBookPage, price);
        }
예제 #5
0
        private ActionResult CreateUser(LoginModel Model)
        {
            User user = new User
            {
                Username = Model.Username,
                Password = Model.Password
            };

            if (ModelState.IsValid)
            {
                using (CartContext db = new CartContext())
                {
                    var obj = db.User.Where(a => a.Username.Equals(user.Username) && a.Password.Equals(user.Password)).FirstOrDefault();
                    if (obj != null)
                    {
                        Session["UserID"]   = obj.UserId.ToString();
                        Session["UserName"] = obj.Username.ToString();
                        return(RedirectToAction("Index", "Home"));
                    }
                    else
                    {
                        ViewBag.Message = "User does not exist or Password is incorrect";
                        return(View("Login"));
                    }
                }
            }
            else
            {
                return(View("Login"));
            }
        }
        public void ThenTheNameOfTheShownProductIsTheSameAsTheNameOfTheProductWeChose()
        {
            string name = Driver_init.CartPageWithOrders.GetProductName(0);

            CartContext.ClickLinkOfProduct(Driver_init.CartPageWithOrders, 0);
            GoodStateVerificationContext.VerifyItemNameInCart(Driver_init.SingleBookPage, name);
        }
예제 #7
0
파일: Menu.cs 프로젝트: alisherKAK/homeWork
        public static Product ChoseProductMenu()
        {
            do
            {
                try
                {
                    Console.WriteLine("Выберите товар:");
                    using (var context = new CartContext())
                    {
                        var products = context.Products.ToList();
                        for (int i = 0; i < products.Count; ++i)
                        {
                            Console.WriteLine($"{i+1}) {products[i].ProductType.Name}:{products[i].Price}\n" +
                                              $"Дата производства: {products[i].ProducedDate} Срок годности: {products[i].ExpirationDate}");
                        }
                    }

                    int productIndex;

                    if (int.TryParse(Console.ReadLine().Trim(), out productIndex))
                    {
                        using (var context = new CartContext())
                        {
                            return(context.Products.ToList()[productIndex - 1]);
                        }
                    }

                    throw new ArgumentException("Число было введено неверно");
                }
                catch (ArgumentException exception)
                {
                    Console.WriteLine(exception.Message);
                }
            } while (true);
        }
예제 #8
0
        public CreateCart(ILogger <CreateCart> logger, IDiagnosticContext diagnosticsContext, IStringLocalizer <Program> localizer, IClock clock, CartContext context)
        {
            if (logger is null)
            {
                throw new ArgumentNullException(nameof(logger));
            }

            if (diagnosticsContext is null)
            {
                throw new ArgumentNullException(nameof(diagnosticsContext));
            }

            if (localizer is null)
            {
                throw new ArgumentNullException(nameof(localizer));
            }

            if (clock is null)
            {
                throw new ArgumentNullException(nameof(clock));
            }

            if (context is null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            Logger             = logger;
            DiagnosticsContext = diagnosticsContext;
            Localizer          = localizer;
            Clock   = clock;
            Context = context;
        }
예제 #9
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, CartContext dbcontext)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });


            ////dbcontext.Database.EnsureDeleted();
            dbcontext.Database.EnsureCreated();

            //new CartSeeder(dbcontext);
        }
예제 #10
0
        public GetCartById(ILogger <GetCartById> logger, IDiagnosticContext diagnosticsContext, IStringLocalizer <Program> localizer, IMapper mapper, CartContext context)
        {
            if (logger is null)
            {
                throw new ArgumentNullException(nameof(logger));
            }

            if (diagnosticsContext is null)
            {
                throw new ArgumentNullException(nameof(diagnosticsContext));
            }

            if (localizer is null)
            {
                throw new ArgumentNullException(nameof(localizer));
            }

            if (mapper is null)
            {
                throw new ArgumentNullException(nameof(mapper));
            }

            if (context is null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            Logger             = logger;
            DiagnosticsContext = diagnosticsContext;
            Localizer          = localizer;
            Mapper             = mapper;
            Context            = context;
        }
예제 #11
0
        public async Task <bool> HealthCheck()
        {
            var dbContextOptionsBuilder = new DbContextOptionsBuilder <CartContext>();

            dbContextOptionsBuilder.UseSqlServer(Configuration["ConnectionString"],
                                                 sqlServerOptionsAction: sqlOptions =>
            {
                sqlOptions.
                MigrationsAssembly(
                    typeof(Startup).
                    GetTypeInfo().
                    Assembly.
                    GetName().Name);

                //Configuring Connection Resiliency:
                sqlOptions.
                EnableRetryOnFailure(maxRetryCount: 5,
                                     maxRetryDelay: TimeSpan.FromSeconds(30),
                                     errorNumbersToAdd: null);
            });

            using (var dbContext = new CartContext(dbContextOptionsBuilder.Options))
            {
                var count = await dbContext.ShoppingCartItems.CountAsync();

                return(count > 0);
            }
        }
        public virtual PaymentWidgetResult BuildWidget(CartContext cartContext, ProviderOptionIdentifier paymentOptionIdentifier)
        {
            if (cartContext == null || !cartContext.PaymentFlowResults.Any() || !cartContext.Cart.Order.OrderPaymentLinks.Any())
            {
                return(null);
            }

            foreach (var paymentLink in cartContext.Cart.Order.OrderPaymentLinks)
            {
                var payment = _paymentService.Get(paymentLink.PaymentSystemId);
                if (payment.PaymentOption.ProviderId == paymentOptionIdentifier.ProviderId && payment.PaymentOption.OptionId == paymentOptionIdentifier.OptionId)
                {
                    var paymentFlowResult = cartContext.PaymentFlowResults.SingleOrDefault(x => x.PaymentSystemId == payment.SystemId &&
                                                                                           x.PaymentFlowOperation == Sales.Payments.PaymentFlowOperation.InitializePayment &&
                                                                                           x.Success);
                    if (paymentFlowResult != null && paymentFlowResult.PaymentFlowAction is ShowHtmlSnippet paymentFlowAction)
                    {
                        return(new PaymentWidgetResult
                        {
                            Id = paymentOptionIdentifier,
                            ResponseString = paymentFlowAction.HtmlSnippet
                        });
                    }
                    break;
                }
            }

            return(null);
        }
 public Task HandleMessage(ProductPriceChangedMessageEvent productPriceChanged)
 {
     return(Task.Run(async() =>
     {
         var cartItemsAffected = CartContext.CartItems.Where(item => item.ProductId == productPriceChanged.ProductId);
         foreach (var cartItem in cartItemsAffected)
         {
             var oldPrice = cartItem.Price;
             if (productPriceChanged.Price != oldPrice)
             {
                 cartItem.Price = productPriceChanged.Price;
                 var cartParent = await CartContext.Carts.FirstOrDefaultAsync(cart => cart.Id == cartItem.CartId);
                 // No user information, don't send email
                 if (cartParent == null)
                 {
                     return;
                 }
                 //Send email about price change
                 EventBus.Publish(new CartPriceChangedMessageEvent()
                 {
                     CartItemName = cartItem.ProductName, NewPrice = cartItem.Price, OldPrice = oldPrice, UserId = cartParent.UserId, CartId = cartParent.Id
                 });
             }
         }
         await CartContext.SaveChangesAsync();
     }));
 }
예제 #14
0
 protected RequestModel(
     CartContext cartContext,
     CountryService countryService)
 {
     _cartContext  = cartContext;
     _websiteModel = new Lazy <WebsiteModel>(() => ChannelModel.Channel.WebsiteSystemId.GetValueOrDefault().MapTo <Website>().MapTo <WebsiteModel>());
     _countryModel = new Lazy <CountryModel>(() => (countryService.Get(Cart?.Order.CountryCode)?.SystemId ?? ChannelModel.Channel.CountryLinks.FirstOrDefault().CountrySystemId).MapTo <CountryModel>());
 }
예제 #15
0
 public RequestModelImpl(
     CartContext cartContext,
     CountryService countryService)
     : base(
         cartContext,
         countryService)
 {
 }
예제 #16
0
 public Uow(CartContext cartContext, IRepository <Product> productRepository, IRepository <Category> categoryRepository, IRepository <CheckOut> checkoutRepository, IRepository <Cart> cartRepository)
 {
     _cartContext        = cartContext ?? throw new ArgumentNullException(nameof(cartContext));
     _productRepository  = productRepository ?? throw new ArgumentNullException(nameof(productRepository));
     _categoryRepository = categoryRepository ?? throw new ArgumentNullException(nameof(categoryRepository));
     _checkoutRepository = checkoutRepository ?? throw new ArgumentNullException(nameof(checkoutRepository));
     _cartRepository     = cartRepository ?? throw new ArgumentNullException(nameof(cartRepository));
 }
예제 #17
0
 // Gets a single identity
 public CartItemEntity Get(int id)
 {
     using (CartContext ctx = new CartContext())
     {
         var cartItems = ctx.CartItems.SingleOrDefault(x => x.Id == id);
         return(cartItems);
     }
 }
예제 #18
0
 // Removes one product type from the cart
 public void Remove(int productId, string userId)
 {
     using (CartContext ctx = new CartContext())
     {
         var cartItems = ctx.CartItems.Where(x => x.ProductId == productId && x.UserId == userId);
         ctx.CartItems.RemoveRange(cartItems);
         ctx.SaveChanges();
     }
 }
예제 #19
0
        public async Task <ActionResult> ShowCart()
        {
            //从Cookie中获取用户的名字
            Request.Cookies.TryGetValue("username", out string username);

            CartContext cartContext = HttpContext.RequestServices.GetService(typeof(dotNet期末项目.Models.CartContext)) as CartContext;

            return(Ok(await cartContext.Check(username)));
        }
예제 #20
0
 // Changes the quantity of a product in the cart
 public void Update(int productId, int quantity, string userId)
 {
     using (var ctx = new CartContext())
     {
         var item = ctx.CartItems.SingleOrDefault(i => i.ProductId == productId && i.UserId == userId);
         item.Quantity = quantity;
         ctx.SaveChanges();
     }
 }
예제 #21
0
 public ProfileController(UserManager <User> userManager, SignInManager <User> signInManager,
                          RoleManager <IdentityRole> roleManager, CustomLogger logger, CartContext cartContext)
 {
     _userManager   = userManager;
     _signInManager = signInManager;
     _roleManager   = roleManager;
     _logger        = logger;
     _cartContext   = cartContext;
 }
 public ShoppingCartController(
     CartContext cartContext
     , IEventStore eventStore
     , IProductCatalogueClient productCatalogueClient
     )
 {
     _cartContext            = cartContext;
     _eventStore             = eventStore;
     _productCatalogueClient = productCatalogueClient;
 }
 public AccountController(UserManager <User> userManager, SignInManager <User> signInManager,
                          EmailService emailService, CustomLogger logger, CartContext cartContext, RoleManager <IdentityRole> roleManager)
 {
     _userManager   = userManager;
     _signInManager = signInManager;
     _emailService  = emailService;
     _logger        = logger;
     _cartContext   = cartContext;
     _roleManager   = roleManager;
 }
예제 #24
0
        public async Task <ActionResult> AddCart([FromForm] Cart cart)
        {
            CartContext cartContext = HttpContext.RequestServices.GetService(typeof(dotNet期末项目.Models.CartContext)) as CartContext;

            if (await cartContext.AddCart(cart))
            {
                return(Ok("Add to cart successfully!"));
            }
            return(StatusCode(500, "Fail!"));
        }
예제 #25
0
파일: Menu.cs 프로젝트: alisherKAK/homeWork
        public static void  ShowAllUsersProducts(User user)
        {
            using (var context = new CartContext())
            {
                var cartProducts = context.Carts.Where(cart => cart.User.Id == user.Id).SingleOrDefault().CartProducts.ToList();

                cartProducts.ForEach(cartProduct => Console.WriteLine($"{cartProduct.Product.ProductType.Name}:{cartProduct.Product.Price}\n" +
                                                                      $"Дата производства: {cartProduct.Product.ProducedDate} Срок годности: {cartProduct.Product.ExpirationDate}"));
            }
        }
예제 #26
0
파일: Menu.cs 프로젝트: alisherKAK/homeWork
        public static User Entry()
        {
            string login    = SetInformations.SetLogin();
            string password = SetInformations.SetPassword();

            using (var context = new CartContext())
            {
                return(context.Users.Where(user => user.Login == login && user.Password == password).SingleOrDefault());
            }
        }
예제 #27
0
        // Gets entities with a key (id) and lists it's properties
        public IEnumerable <CartItemEntity> Get(string userId)
        {
            using (CartContext ctx = new CartContext())
            {
                var cartItems = ctx.CartItems
                                .Where(x => x.UserId == userId).ToList();

                return(cartItems);
            }
        }
예제 #28
0
        public async Task <ActionResult> DeleteCart(string username, string goodname)
        {
            CartContext cartContext = HttpContext.RequestServices.GetService(typeof(dotNet期末项目.Models.CartContext)) as CartContext;
            bool        result      = await cartContext.DeleteOne(username, goodname);

            if (result)
            {
                return(Ok("Delete successfully!"));
            }
            return(StatusCode(500, "Fail!"));
        }
 public override IEnumerable <Discount> Process(CartContext cart)
 {
     if (cart.TotalPrice > this._minDiscountPrice)
     {
         yield return(new Discount
         {
             Amount = this._discountAmount,
             Rule = this,
             Products = cart.PurchasedItems.ToArray()
         });
     }
 }
예제 #30
0
        public CartController(CartContext context)
        { // DI to inject the database context
            _context = context;

            if (_context.CartItems.Count() == 0)
            {// Adds an item to the DB if the DB is empty
                _context.CartItems.Add(new CartItem {
                    productID = 2125, productName = "Cheese", quantity = 5, shoppingCartID = 1
                });
                _context.SaveChanges();
            }
        }