public async Task <string> AddItem(int id) { if (String.IsNullOrEmpty(HttpContext.Session.GetString("Id"))) { return(null); } if (await _context.Cart.AnyAsync(c => c.Product == id)) { return(""); } Cart cart = new Cart(); cart.Product = id; cart.User = HttpContext.Session.GetString("Id"); cart.Quantity = 1; _context.Cart.Add(cart); await _context.SaveChangesAsync(); var model = from m in _context.Cart select m; model = model.Where(m => m.User == HttpContext.Session.GetString("Id")); List <Cart> cartArr = await model.ToListAsync(); return(cartArr.Count.ToString()); }
public async Task <IActionResult> PutCountry(int id, Country country) { if (id != country.CountryId) { return(BadRequest()); } _context.Entry(country).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!CountryExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public async Task <IActionResult> Signup([Bind("Id, Password, Repassword, Name, Phone, Email, Address")] CreateAccountView model) { if (ModelState.IsValid) { if (model.Password != model.Repassword) { ModelState.AddModelError("Repassword", "Mật khẩu không khớp"); return(View(model)); } if (_context.Account.Any(key => key.Id == model.Id)) { ModelState.AddModelError("Id", "Tên tài khoản đã tồn tại"); return(View(model)); } Account account = new Account(); account.Id = model.Id; account.Password = model.Password; account.Name = model.Name; account.Privilege = 2; account.Phone = model.Phone; account.Email = model.Email; account.Address = model.Address; _context.Account.Add(account); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Success))); } return(View(model)); }
public async Task <IActionResult> PutProduct(int id, Product product) { if (id != product.Id) { return(BadRequest()); } _context.Entry(product).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ProductExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public async Task <IActionResult> PutInvoiceItems(int id, InvoiceItems invoiceItems) { if (id != invoiceItems.Id) { return(BadRequest()); } db.Entry(invoiceItems).State = EntityState.Modified; try { await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!InvoiceItemsExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public async Task <IActionResult> PutEmployee(int id, Employee employee) { if (id != employee.Id) { return(BadRequest()); } _context.Entry(employee).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!EmployeeExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public async Task <IActionResult> PutTeam(int id, Team team) { if (id != team.TeamId) { return(BadRequest()); } _context.Entry(team).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!TeamExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public async Task <IActionResult> Edit(int id, [Bind("Id,ImagePath")] Info info) { if (id != info.Id) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(info); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!InfoExists(info.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(info)); }
public async Task AddCoffeeData(CoffeeMachineData coffeeMachineData) { var myCoffeeDataToAdd = mapper.Map <CoffeeDataEntity>(coffeeMachineData); await coffeeContext.CoffeeDataEntities.AddAsync(myCoffeeDataToAdd); await coffeeContext.SaveChangesAsync(); }
public async Task <ActionResult <UsersDTO> > RegisterUser( string inUsername, string inEmail, string inFirst_name, string inLast_name, string inPassword, string inContact_number ) { if (isUsernameTaken(inUsername)) { return(new JsonResult(new { Status = "error", Message = "Username is taken" })); } if (isEmailTaken(inEmail)) { return(new JsonResult(new { Status = "error", Message = "Email is taken" })); } Users users = new Users { username = inUsername, email = inEmail, first_name = inFirst_name, last_name = inLast_name, password = Encryption.HashPassword(inPassword), contact_number = inContact_number, created_at = DateTime.Now, updated_at = DateTime.Now, isActive = true, isDelted = false, isAdmin = false }; db.Users.Add(users); try { await db.SaveChangesAsync(); } catch (Exception e) { return(new JsonResult(new { Status = "error", Message = "An error has occured" })); } UsersDTO userDTO = new UsersDTO { Id = users.Id, username = users.username, email = users.email, first_name = users.first_name, last_name = users.last_name, contact_number = users.contact_number, created_at = users.created_at, updated_at = users.updated_at, isAdmin = users.isAdmin, isActive = users.isActive, isDeleted = users.isDelted }; return(new JsonResult(new { Status = "success", Message = userDTO })); }
public async Task <IActionResult> Create([Bind("Id,Name,Img,Price,Weight,Description,RoastLevel,Taste,RoastDate")] Coffee coffee) { if (ModelState.IsValid) { _context.Add(coffee); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(coffee)); }
public async Task <IActionResult> Create([Bind("Id,NamaKopi,AsalKopi,JenisKopi,DeskripsiKopi")] Coffee coffee) { if (ModelState.IsValid) { _context.Add(coffee); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(coffee)); }
public async Task <IActionResult> CreateProduct(CreateProductView model) { Product product = new Product(); if (model.Image != null) { var uniqueFileName = GetUniqueFileName(model.Image.FileName); var uploads = Path.Combine(_hostingEnvironment.WebRootPath, "images"); var filePath = Path.Combine(uploads, uniqueFileName); model.Image.CopyTo(new FileStream(filePath, FileMode.Create)); product.Name = model.Name; product.Note = model.Note; product.Price = model.Price; product.Genre = model.Genre; product.Image = uniqueFileName; } else { return(View(model)); } if (ModelState.IsValid) { _context.Product.Add(product); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Product))); } return(View(model)); }
public async Task <IActionResult> Checkout(CheckoutView model) { if (!ModelState.IsValid) { return(View("Index", model)); } string user = HttpContext.Session.GetString("Id"); IQueryable <Cart> cart = from m in _context.Cart select m; cart = cart.Where(m => m.User == user); List <Cart> carts = await cart.ToListAsync(); string itemString = ""; string quantityString = ""; string priceString = ""; int total = 0; foreach (Cart c in carts) { Product p = await _context.Product.FindAsync(c.Product); itemString += p.Name + ";"; quantityString += c.Quantity + ";"; priceString += p.Price + ";"; total += c.Quantity * p.Price; } itemString = itemString.TrimEnd(';'); quantityString = quantityString.TrimEnd(';'); priceString = priceString.TrimEnd(';'); string time = String.Format("{0: dd/MM/yyyy hh:mm}", DateTime.Now); Bill bill = new Bill() { User = user, Name = model.Name, Address = model.Address, Phone = model.Phone, Email = model.Email, Code = model.Code, Note = model.Note, Items = itemString, Quantity = quantityString, Price = priceString, Discount = 0, Ship = 15, Total = total + model.Ship - model.Discount, PaymentMethod = model.PaymentMethod, Time = time, Status = 0 }; _context.Bill.Add(bill); _context.Cart.RemoveRange(carts); await _context.SaveChangesAsync(); return(View()); }
public async Task <User> PostUser(User user) { _context.User.Add(user); await _context.SaveChangesAsync(); return(user); }
public async Task <ActionResult <InvoicesDTO> > addInvoice(int inUserID, string discountCode = null) { Users user = await db.Users.FindAsync(inUserID); if (user == null) { return(new JsonResult(new { Status = "error", Message = "User Not Found" })); } Invoices invoices = new Invoices { User = user, UserID = user.Id, tax = 0, total = 0, isFreeShipping = false, created_at = DateTime.Now, updated_at = DateTime.Now }; if (discountCode != null) { DiscountCodes discCodes = await db.DiscountCodes.Where(ds => ds.code.Equals(discountCode.ToUpper())).FirstOrDefaultAsync(); if (discCodes != null) { invoices.discount_code = discCodes.code; invoices.discount_percentage = discCodes.percentage; } } db.Invoices.Add(invoices); try { await db.SaveChangesAsync(); } catch (Exception e) { return(new JsonResult(new { Status = "error", Message = "Error creating invoice" })); } InvoicesDTO invcDTO = new InvoicesDTO { Id = invoices.Id, total = invoices.total, tax = invoices.tax, discount_code = invoices.discount_code, discount_percentage = invoices.discount_percentage, isFreeShipping = invoices.isFreeShipping, UserID = invoices.UserID, created_at = invoices.created_at, updated_at = invoices.created_at, invoiceItems = null }; return(new JsonResult(new { Status = "success", Message = invcDTO })); }
public async Task AddCoffee(CoffeeModel coffeeToAdd) { if (coffeeToAdd == null) { throw new Exception("You should not add null entries!"); } if (!IsCoffeeValid(coffeeToAdd)) { throw new Exception("The coffee you are trying to add is not valid"); } var coffeeEntityToAdd = mapper.Map <CoffeeEntity>(coffeeToAdd); coffeeEntityToAdd.EspressoMachine = await espressoMachineService.GetEspressoMachine(coffeeToAdd.IsEsspreso); await context.Coffees.AddAsync(coffeeEntityToAdd); await context.SaveChangesAsync(); }
public async Task SaveAsync() { if (_transaction != null) { await _transaction.CommitAsync(); await _context.SaveChangesAsync(); _transaction = null; } }
public async Task <IActionResult> Create([Bind("ID,Name,Customer,TimeOrdered")] Order order) { if (ModelState.IsValid) { _context.Add(order); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(order)); }
public async Task <IActionResult> BookATable(BookATable model) { if (!ModelState.IsValid) { return(View("Index", model)); } _context.BookATable.Add(model); await _context.SaveChangesAsync(); return(View()); }
public async Task <ActionResult <ProductOptionsDTO> > PostProductOptions( int inPrice, int inWeight, int inQuantity, int inProductID ) { Products prod = db.Products.FindAsync(inProductID).Result; if (prod == null) { return(new JsonResult(new { Status = "Error", Message = "No Product with the id of " + inProductID })); } ProductOptions productOptions = new ProductOptions { price = inPrice, weight = inWeight, quantity = inQuantity, ProductID = inProductID, created_at = DateTime.Now, updated_at = DateTime.Now, isAvailable = true, isDeleted = false, Product = prod }; try { db.ProductOptions.Add(productOptions); await db.SaveChangesAsync(); updateMaxMinPrice(productOptions.ProductID, productOptions.price); ProductOptionsDTO prodOptDTO = new ProductOptionsDTO { price = inPrice, weight = inWeight, quantity = inQuantity, ProductID = inProductID, created_at = DateTime.Now, updated_at = DateTime.Now, isAvailable = true, isDeleted = false }; return(prodOptDTO); } catch (Exception ex) { return(new JsonResult(new { Status = "Error", ex.Message })); }; }
public async Task <IActionResult> Create([FromBody] Info info) { try { _context.Infos.Add(info); await _context.SaveChangesAsync(); return(Ok()); } catch (Exception ex) { return(BadRequest(ex)); } }
public async Task <ActionResult <Products> > PostProducts( string inName, string inDesc, string inRegion, string inRoast, int inAltitude_max, int inAltitude_min, string inBean_type, string inImage_url ) { Products products = new Products { name = inName, desc = inDesc, max_price = 0, min_price = 0, region = inRegion, roast = inRoast, altitude_max = inAltitude_max, altitude_min = inAltitude_min, bean_type = inBean_type, image_url = inImage_url, created_at = DateTime.Now, updated_at = DateTime.Now, isDeleted = false }; db.Products.Add(products); try { await db.SaveChangesAsync(); } catch (Exception e) { return(ValidationProblem()); } return(CreatedAtAction("GetProducts", new { id = products.Id }, products)); }
public async Task <EspressoMachineEntity> GetEspressoMachine(bool isEspressoMachine) { var espressoMachineToReturn = await coffeeContext.EspressoMachines.FirstOrDefaultAsync(x => x.IsEspressor == isEspressoMachine); if (espressoMachineToReturn != null) { return(espressoMachineToReturn); } var espressorMachineToAdd = GetNewEspressoMachine(isEspressoMachine); await coffeeContext.EspressoMachines.AddAsync(espressorMachineToAdd); await coffeeContext.SaveChangesAsync(); return(espressorMachineToAdd); }
public async Task <Event> PostEvent(Domain.Dtos.EventForCreationDto eventModel) { var user = await usersService.GetUserByDeviceId(eventModel.DeviceId); var newEvent = new Event { StartDate = DateTime.Now.AddHours(1), UserId = user.UserId }; _context.Event.Add(newEvent); await _context.SaveChangesAsync(); return(newEvent); }
public async Task <IActionResult> Edit(int id, [Bind("ID,Name,Container,Unit")] Ingredient ingredient, int Container) { var cont = (from c in _context.Ingredients where c.ID == id select c.Container).FirstOrDefault(); var unit = (from c in _context.Ingredients where c.ID == id select c.Unit).FirstOrDefault(); if (id != ingredient.ID) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Database.ExecuteSqlCommand("UPDATE dbo.Ingredient SET Container = @container WHERE ID = @contID", new SqlParameter("@container", cont + Container), new SqlParameter("@contID", id)); _context.Database.ExecuteSqlCommand("UPDATE dbo.Ingredient SET Unit = @unit WHERE ID = @unitID", new SqlParameter("@unit", unit + Container * 15), new SqlParameter("@unitID", id)); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!IngredientExists(ingredient.ID)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(ingredient)); }
public async Task <IActionResult> Create([Bind("ID,Name,Customer,TimeOrdered")] Order order, string Name) { var coffeebean = (from c in _context.Ingredients where c.Name == "CoffeeBean" select c.Unit).FirstOrDefault(); var sugar = (from c in _context.Ingredients where c.Name == "Sugar" select c.Unit).FirstOrDefault(); var milk = (from c in _context.Ingredients where c.Name == "Milk" select c.Unit).FirstOrDefault(); var bagcoffee = (from c in _context.Ingredients where c.Name == "CoffeeBean" select c.Container).FirstOrDefault(); var packsugar = (from c in _context.Ingredients where c.Name == "Sugar" select c.Container).FirstOrDefault(); var cartonmilk = (from c in _context.Ingredients where c.Name == "Milk" select c.Container).FirstOrDefault(); switch (Name) { case "Double Americano": if (coffeebean >= 3) { coffeebean = coffeebean - 3; _context.Database.ExecuteSqlCommand("UPDATE dbo.Ingredient SET Unit = " + coffeebean + " WHERE ID = 1"); _context.SaveChanges(); } else { return(RedirectToAction(nameof(Index)).WithWarning("Order has failed due to insufficient unit of ingredient")); } break; case "Sweet Latte": if (coffeebean >= 2 & sugar >= 5 & milk >= 3) { coffeebean = coffeebean - 2; sugar = sugar - 5; milk = milk - 3; _context.Database.ExecuteSqlCommand("UPDATE dbo.Ingredient SET Unit = " + coffeebean + " WHERE ID = 1"); _context.Database.ExecuteSqlCommand("UPDATE dbo.Ingredient SET Unit = " + sugar + " WHERE ID = 2"); _context.Database.ExecuteSqlCommand("UPDATE dbo.Ingredient SET Unit = " + milk + " WHERE ID = 3"); _context.SaveChanges(); } else { return(RedirectToAction(nameof(Index)).WithWarning("Order has failed due to insufficient unit of ingredient")); } break; case "Flat White": if (coffeebean >= 2 & sugar >= 1 & milk >= 4) { coffeebean = coffeebean - 2; sugar = sugar - 1; milk = milk - 4; _context.Database.ExecuteSqlCommand("UPDATE dbo.Ingredient SET Unit = " + coffeebean + " WHERE ID = 1"); _context.Database.ExecuteSqlCommand("UPDATE dbo.Ingredient SET Unit = " + sugar + " WHERE ID = 2"); _context.Database.ExecuteSqlCommand("UPDATE dbo.Ingredient SET Unit = " + milk + " WHERE ID = 3"); _context.SaveChanges(); } else { return(RedirectToAction(nameof(Index)).WithWarning("Order has failed due to insufficient unit of ingredient")); } break; default: break; } var beanhigh = bagcoffee * 15; var beanlow = (bagcoffee - 1) * 15; var sugarhigh = packsugar * 15; var sugarlow = (packsugar - 1) * 15; var milkhigh = cartonmilk * 15; var milklow = (cartonmilk - 1) * 15; if (!(coffeebean > beanlow && coffeebean <= beanhigh)) { bagcoffee--; _context.Database.ExecuteSqlCommand("UPDATE dbo.Ingredient SET Container = " + bagcoffee + " WHERE ID = 1"); _context.SaveChanges(); } if (!(sugar > sugarlow && sugar <= sugarhigh)) { packsugar--; _context.Database.ExecuteSqlCommand("UPDATE dbo.Ingredient SET Container = " + packsugar + " WHERE ID = 2"); _context.SaveChanges(); } if (!(milk > milklow && milk <= milkhigh)) { cartonmilk--; _context.Database.ExecuteSqlCommand("UPDATE dbo.Ingredient SET Container = " + cartonmilk + " WHERE ID = 3"); _context.SaveChanges(); } if (ModelState.IsValid) { _context.Add(order); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index)).WithSuccess("Order has been successfully submitted")); } return(View(order)); }