private void CheckNullSession() { if (SessionExtensions.GetObjectFromJson <List <Item> >(HttpContext.Session, "cart") == null) { SessionExtensions.SetObjectAsJson <List <Item> >(HttpContext.Session, "cart", new List <Item>() { }); } }
public IActionResult Register(Users user) { if (ModelState.IsValid) { string query = $"INSERT INTO Users (FirstName, LastName, Email, Password, Created_at, Updated_at VALUES ('{user.FirstName}','{user.LastName}','{user.Email}','{user.Password}', NOW())"; _dbConnector.Execute(query); string query2 = $"SELECT email, password, firstname, id FROM users WHERE email = '{user.Email}'"; var theUser = _dbConnector.Query(query2); SessionExtensions.SetObjectAsJson(HttpContext.Session, "UserSession", theUser[0]); return(RedirectToAction("Welcome")); } }
public IActionResult Register(Users user) { if (ModelState.IsValid) { string query = $"INSERT INTO Users (FirstName, LastName, Email, Password, Created_at, Updated_at VALUES ('{user.FirstName}','{user.LastName}','{user.Email}','{user.Password}', NOW())"; DbConnector.Execute(query); string query2 = $"SELECT Email, Password, Firstname, id FROM users WHERE Email = '{user.Email}'"; var currentUser = DbConnector.Query(query2); SessionExtensions.SetObjectAsJson(HttpContext.Session, "UserInSession", currentUser[0]); return(RedirectToAction("Index")); } return(View("loginreg")); }
public IActionResult Login(string email, string password) { TempData["Error"] = null; Login theUser = new Login { loginEmail = email, loginPassword = password, }; if (TryValidateModel(theUser)) { string query = $"SELECT FirstName, Email, Password id FROM Users WHERE Email = '{theUser.loginEmail}'"; var currentUser = DbConnector.Query(query); if (currentUser.Count == 0) { //validating if the email is in the database string[] message = { "Email is not valid! Please try again!" }; TempData["Error"] = message; return(RedirectToAction("loginreg")); //if it is in the datebase check and see if the password is correct! } else if (password != (string)currentUser[0]["password"]) { string[] message = { "Password doesn't match the email! Please try again!" }; TempData["Error"] = message; return(RedirectToAction("loginreg")); } else { // Setting the session as an Json String to desirialize it later SessionExtensions.SetObjectAsJson(HttpContext.Session, "UserInSession", currentUser[0]); return(RedirectToAction("Welcome")); } } else { List <string> theErrors = new List <string>(); foreach (var error in ModelState.Values) { if (error.Errors.Count > 0) { theErrors.Add(error.Errors[0].ErrorMessage.ToString()); } } TempData["Error"] = theErrors; return(RedirectToAction("Index")); } }
public RedirectToActionResult AddToCart(int Id, string returnUrl, int quantity = 1) { if (SessionExtensions.GetObjectFromJson <Cart>(HttpContext.Session, "cart") == null) { Cart cart = new Cart(); cart.AddItem(repository.FindProduct(Id), quantity); SessionExtensions.SetObjectAsJson(HttpContext.Session, "cart", cart); } else { var cart = SessionExtensions.GetObjectFromJson <Cart>(HttpContext.Session, "cart"); cart.AddItem(repository.FindProduct(Id), quantity); SessionExtensions.SetObjectAsJson(HttpContext.Session, "cart", cart); } return(RedirectToAction("Index", new { returnUrl })); }
public IActionResult Index(string returnUrl) { if (SessionExtensions.GetObjectFromJson <Cart>(HttpContext.Session, "cart") != null) { return(View(new CartIndexViewModel() { Cart = SessionExtensions.GetObjectFromJson <Cart>(HttpContext.Session, "cart"), ReturnUrl = returnUrl ?? "/" })); } else { Cart cart = new Cart(); SessionExtensions.SetObjectAsJson(HttpContext.Session, "cart", cart); return(View(new CartIndexViewModel() { Cart = SessionExtensions.GetObjectFromJson <Cart>(HttpContext.Session, "cart"), ReturnUrl = returnUrl ?? "/" })); } }
public RedirectToActionResult RemoveFromCart(int Id, string returnUrl) { Product product = repository.FindProduct(Id); if (product != null) { if (SessionExtensions.GetObjectFromJson <Cart>(HttpContext.Session, "cart") == null) { Cart cart = new Cart(); cart.RemoveLine(product); SessionExtensions.SetObjectAsJson(HttpContext.Session, "cart", cart); } else { var cart = SessionExtensions.GetObjectFromJson <Cart>(HttpContext.Session, "cart"); cart.RemoveLine(product); SessionExtensions.SetObjectAsJson(HttpContext.Session, "cart", cart); } } return(RedirectToAction("Index", new { returnUrl })); }
public IActionResult Remove(int id) { CheckNullSession(); var itemList = SessionExtensions.GetObjectFromJson <List <Item> >(HttpContext.Session, "cart"); int index = IsInCart(id); // if product is in the list, reduce quantity if greater than 1, otherwise remove the product from the list if (index != -1) { if (itemList[index].Quantity > 1) { itemList[index].Quantity--; } else { itemList.RemoveAt(index); } } SessionExtensions.SetObjectAsJson <List <Item> >(HttpContext.Session, "cart", itemList); return(RedirectToAction("Index")); }
public async Task <IActionResult> Buy(int id) { //First make sure the current user can't add any of their products to cart. Note: views will also disable the buttons var pId = await(from p in _context.Product where p.UserId == _userManager.GetUserId(User) select p.ProductId).FirstOrDefaultAsync(); if (id == pId) { return(RedirectToAction("Index").WithDanger("Sorry!", "You can't purchase your own products.")); } //If user clicks add to cart and there is no cart session created, create a cart session CheckNullSession(); //if the session contains an empty list if (SessionExtensions.GetObjectFromJson <List <Item> >(HttpContext.Session, "cart").Count() == 0) { var itemList = new List <Item>(); //get product from the database, check its availability. If available add to the session list, else disallow adding to cart Product product = await _context.Product.FirstOrDefaultAsync(m => m.ProductId == id); if (product.Available > 0) { itemList.Add(new Item { Product = product, Quantity = 1 }); //set the session with the updated list SessionExtensions.SetObjectAsJson <List <Item> >(HttpContext.Session, "cart", itemList); } else { return(RedirectToAction("Index").WithDanger("Sorry!", "Item is currently unavailable.")); } } //if session contains an unempty list else { var itemList = SessionExtensions.GetObjectFromJson <List <Item> >(HttpContext.Session, "cart"); //find the index for the product in the list int index = IsInCart(id); //if not -1, item is in the list if (index != -1) { //check that the number of products available is greater than the quantity of products added to the cart. If so increase the quantity of the item in the list if (itemList[index].Product.Available > itemList[index].Quantity) { itemList[index].Quantity++; } else { return(RedirectToAction("Index", "Products").WithDanger("Sorry!", "You can not purchase more of this item.")); } } //if -1, item is not in the list. Get product from the database and add it to the list if available else { Product product = await _context.Product.FirstOrDefaultAsync(m => m.ProductId == id); if (product.Available > 0) { itemList.Add(new Item { Product = product, Quantity = 1 }); } else { return(RedirectToAction("Index", "Products").WithDanger("Sorry!", "Item is currently unavailable.")); } } SessionExtensions.SetObjectAsJson <List <Item> >(HttpContext.Session, "cart", itemList); } return(RedirectToAction("Index")); }
public async Task <IActionResult> Purchase(string items, double totalPrice) //items parameter is a list converted to JSON in the view (therefore sent as a string) { //create a new ShoppingCartViewModel with list of items the user has in the shopping cart ShoppingCartViewModel allPurchases = new ShoppingCartViewModel { Items = JsonConvert.DeserializeObject <List <Item> >(items), //deserialize items parameter TotalPrice = totalPrice }; List <Purchase> purchaseList = new List <Purchase>(); double amount; string seller; int available; //foreach item in allPurchases, add to the purchaseList (total price for a purchase is quantity times price) foreach (var item in allPurchases.Items) { amount = item.Product.Price * item.Quantity; seller = item.Product.UserId; purchaseList.Add(new Purchase { SellerId = seller, CustomerId = _userManager.GetUserId(User), Amount = amount }); //after adding item to purchaseList, update the Product table in the database by decreasing the Available field available = item.Product.Available - item.Quantity; Product product = new Product { ProductId = item.Product.ProductId, Available = available }; try { _context.Attach(product); _context.Entry(product).Property(p => p.Available).IsModified = true; await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ProductExists(product.ProductId)) { return(NotFound()); } else { throw; } } } //Create new purchases in the database from the purchaseList _context.AddRange(purchaseList); await _context.SaveChangesAsync(); //clear the shopping cart var itemList = SessionExtensions.GetObjectFromJson <List <Item> >(HttpContext.Session, "cart"); itemList.Clear(); SessionExtensions.SetObjectAsJson <List <Item> >(HttpContext.Session, "cart", itemList); return(RedirectToAction(nameof(Index))); }