コード例 #1
0
 public ShoppingCartController(
     ShoppingCartDbContext shoppingCartDbContext,
     IMapper mapper)
 {
     this.shoppingCartDbContext = shoppingCartDbContext;
     this.mapper = mapper;
 }
コード例 #2
0
        public ActionResult Checkout()
        {
            var  db       = new ShoppingCartDbContext();
            User userAuth = UserController.GetUserFromCookie(Request.Cookies["ShoppingCart_Team7B"]);

            if (userAuth == null)
            {
                return(RedirectToAction("Login", "User"));
            }

            User     user     = db.User.Where(x => x.UserId == userAuth.UserId).FirstOrDefault();
            Purchase purchase = new Purchase();

            foreach (var cartGroup in user.Cart.CartGroups)
            {
                purchase.PurchaseGroups.Add(new PurchaseGroup(cartGroup.Quantity, cartGroup.Product));
            }
            user.Purchases.Add(purchase);
            foreach (var cartGroup in user.Cart.CartGroups.ToList())
            {
                db.CartGroup.Remove(cartGroup);
            }
            db.SaveChanges();
            return(RedirectToAction("ViewPurchases", "Purchases"));
        }
コード例 #3
0
 public async Task <List <Products> > getAllProducts()
 {
     using (var shoppingCartDbContext = new ShoppingCartDbContext())
     {
         return(await shoppingCartDbContext.Products.ToListAsync());
     }
 }
コード例 #4
0
 public ShopController(IShopData shopData, IHostingEnvironment hostingEnvironment, ShoppingCartDbContext db)
 {
     _db = db;
     _hostingEnvironment = hostingEnvironment;
     _shopData           = shopData;
     mainShopViewModel   = new MainShopViewModel();
 }
コード例 #5
0
 public async Task <List <Cart> > getCart()
 {
     using (var shoppingCartDbContext = new ShoppingCartDbContext())
     {
         return(await shoppingCartDbContext.Carts.ToListAsync());
     }
 }
コード例 #6
0
 public static void ClearData(ShoppingCartDbContext context)
 {
     ExecuteDeleteSQL(context, "[dbo].[ShoppingCartItems]");
     ExecuteDeleteSQL(context, "[dbo].[Products]");
     ResetIdentity(context, "[dbo].[ShoppingCartItems]");
     ResetIdentity(context, "[dbo].[Products]");
 }
コード例 #7
0
 // GET: Login
 public ActionResult Login(string username, string password)
 {
     if (HttpContext.Request.HttpMethod == "POST")
     {
         var  db   = new ShoppingCartDbContext();
         User user = db.User.Where(x => x.Username == username).FirstOrDefault();
         if (user == null)
         {
             return(RedirectToAction("Login"));
         }
         var    sha1         = new SHA1CryptoServiceProvider();
         string passwordHash = Convert.ToBase64String(sha1.ComputeHash(Encoding.UTF8.GetBytes(password)));
         if (user.Username == username && user.Password == passwordHash)
         {
             Session session = new Session(user);
             Response.Cookies["ShoppingCart_Team7B"]["sessionId"] = session.SessionId;
             db.Session.Add(session);
             db.SaveChanges();
             return(RedirectToAction("ListProducts", "Product"));
         }
         else
         {
             return(RedirectToAction("Login"));
         }
     }
     return(View());
 }
コード例 #8
0
    public static void Initialize(IServiceProvider serviceProvider)
    {
        using (var context = new ShoppingCartDbContext(
                   serviceProvider.GetRequiredService <DbContextOptions <ShoppingCartDbContext> >()))
        {
            #region ShipmentMethod
            if (!context.ShipmentMethods.Any())
            {
                context.ShipmentMethods.AddRange(
                    new ShipmentMethod()
                {
                    Name             = "Self pick up",
                    ShipmentMethodId = Guid.Parse("866f8387-147e-4bc5-812e-b45cdd862238")
                },
                    new ShipmentMethod()
                {
                    Name             = "Default shipment method",
                    ShipmentMethodId = Guid.Parse("866f3387-147e-4bc5-812e-b45c8d862238")
                }
                    );
            }
            #endregion ShipmentMethod

            context.SaveChanges();
        }
    }
コード例 #9
0
 public static void InitializeData(ShoppingCartDbContext context)
 {
     context.Database.EnsureDeleted();
     context.Database.Migrate();
     ClearData(context);
     SeedData(context);
 }
コード例 #10
0
        public async Task <OrderItem> CreateOrderItemAsync(Guid orderId, Guid productId, int quantity, CancellationToken cancellationToken = default)
        {
            using (ShoppingCartDbContext context = _dbContextFactory())
            {
                OrderEntity order = context.Orders.SingleOrDefault(a => a.Id == orderId);

                if (order == null)
                {
                    throw new OrderNotFoundException($"Order with ID {orderId} not found");
                }

                ProductEntity product = context.Products.SingleOrDefault(a => a.Id == productId);

                if (product == null)
                {
                    throw new ProductNotFoundException($"Product with ID {productId} not found");
                }

                OrderItemEntity orderItem = new OrderItemEntity
                {
                    Id       = Guid.NewGuid(),
                    Order    = order,
                    Product  = product,
                    Quantity = quantity,
                };

                context.OrderItems.Add(orderItem);

                await context.SaveChangesAsync(cancellationToken);

                return(BuildOrderItemFromEntity(orderItem));
            }
        }
コード例 #11
0
 public OrderItem GetOrderItem(Guid orderItemId)
 {
     using (ShoppingCartDbContext context = _dbContextFactory())
     {
         return(BuildOrderItemFromEntity(context.OrderItems.Include(a => a.Product).SingleOrDefault(a => a.Id == orderItemId)));
     }
 }
コード例 #12
0
    public static void Initialize(IServiceProvider serviceProvider)
    {
        using (var context = new ShoppingCartDbContext(
                   serviceProvider.GetRequiredService <DbContextOptions <ShoppingCartDbContext> >()))
        {
            #region PaymentOption
            if (!context.PaymentMethods.Any())
            {
                context.PaymentMethods.AddRange(
                    new PaymentMethod()
                {
                    Name            = "Mpesa",
                    PaymentMethodId = Guid.Parse("816f2387-147e-4bc5-812e-b45cdd862238")
                },

                    new PaymentMethod()
                {
                    Name            = "Cash on delivery",
                    PaymentMethodId = Guid.Parse("866f8387-147e-4bc5-812e-b45cdd862238")
                }
                    );
            }
            #endregion PaymentOption
            context.SaveChanges();
        }
    }
コード例 #13
0
 public async Task <Products> getProductById(int id)
 {
     using (var shoppingCartDbContext = new ShoppingCartDbContext())
     {
         return(await shoppingCartDbContext.Products.FindAsync(id));
     }
 }
コード例 #14
0
 public LoginController(ShoppingCartDbContext db, UserManager <IdentityUser> userManager, SignInManager <IdentityUser> signInManager, ILoginData loginData)
 {
     _userManager   = userManager;
     _signInManager = signInManager;
     _loginData     = loginData;
     _db            = db;
 }
 public ProductUpdatedConsumer(
     ShoppingCartDbContext shoppingCartDbContext,
     IMapper mapper)
 {
     this.shoppingCartDbContext = shoppingCartDbContext;
     this.mapper = mapper;
 }
コード例 #16
0
        // private readonly Cart _cart;

        public CartController(IItemData itemData, ShoppingCartDbContext db, ICartData cartData) // Cart cart, meka contructor eka ethulata danna
        {
            _itemData = itemData;
            //_cart = cart;
            _db       = db;
            _cartData = cartData;
        }
コード例 #17
0
ファイル: Util.cs プロジェクト: diwei-tan/ASP.NET-MVC
 public static List <Product> GetProducts()
 {
     using (var db = new ShoppingCartDbContext())
     {
         return(db.Product.ToList());
     }
 }
コード例 #18
0
        public async Task <Order> CreateOrderAsync(Guid customerId, CancellationToken cancellationToken = default)
        {
            using (ShoppingCartDbContext context = _dbContextFactory())
            {
                CustomerEntity customer = context.Customers.SingleOrDefault(a => a.Id == customerId);

                if (customer == null)
                {
                    throw new CustomerNotFoundException($"Customer with ID {customerId} not found");
                }

                OrderEntity entity = new OrderEntity
                {
                    Id        = Guid.NewGuid(),
                    CreatedAt = DateTimeOffset.UtcNow,
                    Customer  = customer,
                };

                context.Orders.Add(entity);

                await context.SaveChangesAsync(cancellationToken);

                return(BuildOrderFromEntity(entity));
            }
        }
コード例 #19
0
ファイル: Util.cs プロジェクト: diwei-tan/ASP.NET-MVC
 public static List <Product> GetProducts(string search)
 {
     using (var db = new ShoppingCartDbContext())
     {
         return(db.Product.Where(x => x.Name.Contains(search)).ToList());
     }
 }
コード例 #20
0
 public ActionResult Mypurchases()
 {
     using (var db = new ShoppingCartDbContext())
     {
         string sessionId = (string)Session["SessionId"];
         //select purchases based on customer id and session id from DB
         var mypurchases = (from cp in db.CustomerPurchase
                            join customer in db.Customer
                            on cp.CustomerId equals customer.Id
                            join product in db.Product
                            on cp.ProductId equals product.Id
                            where customer.SessionId == sessionId
                            select new {
             cp.ActivationCode,
             cp.DatePurchased,
             product.Name,
             product.Description,
             product.Img
         });
         List <MyPurchaseModel> PmList = new List <MyPurchaseModel>();
         foreach (var purchase in mypurchases)
         {
             MyPurchaseModel pm = new MyPurchaseModel();
             pm.ActivationCode = purchase.ActivationCode;
             pm.DateOfPurchase = purchase.DatePurchased;
             pm.Name           = purchase.Name;
             pm.Description    = purchase.Description;
             pm.Image          = purchase.Img;
             PmList.Add(pm);
         } // add List to MypurchaseModel
         ViewData["mypurchases"] = PmList;;
         return(View());
     }
 }
コード例 #21
0
        // GET: Checkout
        public ActionResult Check()
        {
            List <Product> purchases = (List <Product>)Session["cart"]; // add session["cart"] products to list

            using (var db = new ShoppingCartDbContext())
            {
                if (Session["SessionId"] != null)//check if sessionId is null
                {
                    string   SessionId = (string)Session["SessionId"];
                    Customer customer  = db.Customer.Where(x => x.SessionId == SessionId).FirstOrDefault(); // retrieve customer based on SessionId

                    double   currentTime = DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
                    DateTime dateTimeNow = new DateTime(1970, 1, 1);
                    dateTimeNow = dateTimeNow.AddSeconds(currentTime);
                    string dateNow = dateTimeNow.ToString("dd MMMM yyyy"); //convert datetime to string (from seconds)
                    foreach (var purchase in purchases)
                    {
                        CustomerPurchase cp = new CustomerPurchase();
                        cp.CustomerId     = customer.Id;
                        cp.ProductId      = purchase.Id;
                        cp.ActivationCode = Guid.NewGuid().ToString();
                        cp.DatePurchased  = dateNow;
                        cp.Customer       = customer;
                        cp.Product        = purchase;
                        db.CustomerPurchase.Add(cp); // add customer puchases to DB
                    }
                    db.SaveChanges();                //Save changes
                }
                Session["cart"]  = null;             // after successful purchase empty cart
                Session["count"] = 0;                // empty count of cart
                return(RedirectToAction("Mypurchases"));
            }
        }
コード例 #22
0
        public ActionResult ListProducts(string searchStr)
        {
            User user = UserController.GetUserFromCookie(Request.Cookies["ShoppingCart_Team7B"]);

            if (user == null)
            {
                return(RedirectToAction("Login", "User"));
            }
            ViewData["user"] = user;
            var db          = new ShoppingCartDbContext();
            var productList = db.Product.ToList();

            if (searchStr == null || searchStr == "")
            {
                ViewData["productList"] = productList;
            }
            else
            {
                var filteredProductList = new List <Product>();
                searchStr = searchStr.ToLower();
                foreach (var product in productList)
                {
                    if (product.ProductName.ToLower().Contains(searchStr) || product.Description.ToLower().Contains(searchStr))
                    {
                        filteredProductList.Add(product);
                    }
                }
                ViewData["productList"] = filteredProductList;
                ViewData["searchStr"]   = searchStr;
            }
            return(View());
        }
コード例 #23
0
        public ActionResult Checkout(string SessionId)
        {
            if (!Util.SessionExist(SessionId))
            {
                return(RedirectToAction("Login", "Login"));
            }

            //get current time
            int      curUnix  = (int)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
            Customer customer = Util.GetCustomerBySessionId(SessionId);

            //For each item in the cart, add to customer purchased under the user
            TempCart Cart = (TempCart)Session[SessionId];

            using (var db = new ShoppingCartDbContext())
            {
                foreach (CartItem item in Cart.Items)
                {
                    for (int i = 0; i < item.Quantity; i++)
                    {
                        CustomerPurchase purchase = new CustomerPurchase();
                        purchase.CustomerId     = customer.Id;
                        purchase.ProductId      = item.Id;
                        purchase.DatePurchased  = curUnix;
                        purchase.ActivationCode = Guid.NewGuid().ToString();
                        db.CustomerPurchase.Add(purchase);
                    }
                }
                db.SaveChanges();
            }

            //Cart has been checked out, remove old cart, reset cart and redirect to view purchase
            Session[SessionId] = new TempCart();
            return(RedirectToAction("MyPurchase", "ViewPurchase", new { SessionId }));
        }
コード例 #24
0
ファイル: Util.cs プロジェクト: diwei-tan/ASP.NET-MVC
 public static Customer GetCustomerBySessionId(string SessionId)
 {
     using (var db = new ShoppingCartDbContext())
     {
         Customer customer = db.Customer.Where(x => x.SessionId == SessionId).FirstOrDefault();
         return(customer);
     }
 }
コード例 #25
0
ファイル: Util.cs プロジェクト: diwei-tan/ASP.NET-MVC
 public static Product GetProductById(int Id)
 {
     using (var db = new ShoppingCartDbContext())
     {
         Product product = db.Product.Where(x => x.Id == Id).Single();
         return(product);
     }
 }
コード例 #26
0
ファイル: Util.cs プロジェクト: diwei-tan/ASP.NET-MVC
 public Product getProductById(int Id)
 {
     using (var db = new ShoppingCartDbContext())
     {
         Product product = db.Product.Where(x => x.Id == Id).FirstOrDefault();
         return(product);
     }
 }
コード例 #27
0
 public UserRepository(ShoppingCartDbContext context)
 {
     if (context != null)
     {
         this.context = context;
         table        = context.Set <T>();
     }
 }
コード例 #28
0
ファイル: ProductsController.cs プロジェクト: boqli/Solution3
 public ProductsController(IProductsService productsService, ICategoriesService categoriesService, ICartService cartService,
                           IWebHostEnvironment env, ShoppingCartDbContext context)
 {
     _productsService   = productsService;
     _categoriesService = categoriesService;
     _env         = env;
     _cartService = cartService;
     _context     = context;
 }
コード例 #29
0
 protected void Application_Start()
 {
     AreaRegistration.RegisterAllAreas();
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
     RouteConfig.RegisterRoutes(RouteTable.Routes);
     BundleConfig.RegisterBundles(BundleTable.Bundles);
     db = new ShoppingCartDbContext();
     db.Database.Initialize(force: true);
 }
コード例 #30
0
    public static void Initialize(IServiceProvider serviceProvider)
    {
        using (var context = new ShoppingCartDbContext(
                   serviceProvider.GetRequiredService <DbContextOptions <ShoppingCartDbContext> >()))
        {
            #region Products
            if (!context.Products.Any())
            {
                context.Products.AddRange(
                    new Product
                {
                    ProductName         = "Window Air 2",
                    ProductId           = Guid.NewGuid(),
                    ProductMediaFile    = "https://ionicframework.com/dist/preview-app/www/assets/img/nin-live.png",
                    ProductManufacturer = "LG",
                    ShopperReview       = new Random().Next(1, 5),
                    Price           = (decimal)(new Random().NextDouble()) * 100000m,
                    ProductCategory = Guid.Parse("816f2387-147e-4bc5-812e-b45add862208")
                },
                    new Product
                {
                    ProductName         = "Samsung Galaxy s9",
                    ProductId           = Guid.NewGuid(),
                    ProductMediaFile    = "https://ionicframework.com/dist/preview-app/www/assets/img/nin-live.png",
                    ProductManufacturer = "Samsung",
                    ShopperReview       = new Random().Next(1, 5),
                    Price           = (decimal)(new Random().NextDouble()) * 100000m,
                    ProductCategory = Guid.Parse("816f2387-147e-4bc5-812e-b45add862208")
                },

                    new Product
                {
                    ProductName         = "Dvd Home Theater System",
                    ProductId           = Guid.NewGuid(),
                    ProductMediaFile    = "https://ionicframework.com/dist/preview-app/www/assets/img/nin-live.png",
                    ProductManufacturer = "Samsung",
                    ShopperReview       = new Random().Next(1, 5),
                    Price           = (decimal)(new Random().NextDouble()) * 100000m,
                    ProductCategory = Guid.Parse("816f2387-147e-4bc5-812e-b45add862208")
                },

                    new Product
                {
                    ProductName         = "Dell Insprion 12645",
                    ProductId           = Guid.NewGuid(),
                    ProductMediaFile    = "https://ionicframework.com/dist/preview-app/www/assets/img/nin-live.png",
                    ProductManufacturer = "Dell",
                    ShopperReview       = new Random().Next(1, 5),
                    Price           = (decimal)(new Random().NextDouble()) * 100000m,
                    ProductCategory = Guid.Parse("816f2387-147e-4bc5-812e-b45add862208")
                }
                    );
                #endregion Products
            }
            context.SaveChanges();
        }
    }
コード例 #31
0
 public void Add(int? Id)
 {
     try
     {
         var prod = Items.Single(p => p.Id == Id);
         prod.Quantity++;
     }
     catch
     {
         using (var db = new ShoppingCartDbContext())
         {
             var prod = db.Products.Find(Id);
             prod.Quantity = 1;
             Items.Add(prod);
         }
     }
 }