public IHttpActionResult PutProduct(int id, Product product) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != product.ProductID) { return(BadRequest()); } db.Entry(product).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!ProductExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
public async Task <ProductCart> Add(ProductCart productCart) { _context.ProductCarts.Add(productCart); _context.SaveChanges(); return(productCart); }
public ActionResult Create([Bind(Include = "ItemId,CategoryId,ProductId,Title,Price,Descript,Image")] Item item) { if (ModelState.IsValid) { db.Item.Add(item); db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.CategoryId = new SelectList(db.Categories, "CategoryId", "Name", item.CategoryId); ViewBag.ProductId = new SelectList(db.Products, "ProductId", "Name", item.ProductId); return(View(item)); }
public IActionResult createcust(Customer newcustomer) { List <Customer> ReturnValues = _context.Customers.Where(user => user.CustomerName.Equals(newcustomer.CustomerName)).ToList(); foreach (var item in ReturnValues) { if (item.CustomerName == newcustomer.CustomerName) { TempData["error"] = "Customer already exists"; return(RedirectToAction("Customer")); } } _context.Customers.Add(newcustomer); _context.SaveChanges(); return(RedirectToAction("Customer")); }
public IActionResult AddProduct( int productId, string name, string description, decimal price, int stock, string url, int catogoryId) { using (EShopContext context = new EShopContext()) { var product = new Product(); product.ProductId = productId; product.ProductName = name; product.Description = description; product.Price = price; product.Stock = stock; product.PruductImageUrl = url; product.CatogoryId = catogoryId; context.Products.Add(product); context.SaveChanges(); return(Content("Ürün başarıyla kaydedildi")); } }
public IActionResult SignUp([FromBody] LoginModel Login) { IActionResult response = Unauthorized(); EShopContext EShopContext = new EShopContext(); if (EShopContext.Customers.Any(c => c.Username.ToLower() == Login.Username.ToLower())) { throw new BadRequestException("Username existed!"); } var Customer = new Customer(); Customer.Username = Login.Username; string ErrorMessValidationPass; if (!ValidatePassword(Customer.Username, out ErrorMessValidationPass)) { throw new BadRequestException(ErrorMessValidationPass); } Customer.Password = SecurePasswordHasher.Hash(Login.Password); EShopContext.Customers.Add(Customer); EShopContext.SaveChanges(); var CustomerEntity = new CustomerEntity(Customer); var tokenString = _JwtHandler.CreateToken(CustomerEntity); response = Ok(new { token = tokenString }); return(response); }
public ActionResult Register(RegisterModel model) { //чтобы "положить" сайт для проверки корректности работы журналирования ошибок //(надо еще в ~Models/AutoModels/RegisterModel закомментировать атрибут [Range(13, 98, ErrorMessage = "Вам должно быть 13 лет")] if (model.Age > 98) { try { throw new Exception("Слишком большой возраст"); } catch { ModelState.AddModelError("Age", "Слишком большой возраст"); } } if (model.Age == 155) { throw new Exception("Был введен возраст 155"); } //форма прошла валидацию? if (ModelState.IsValid) { User user = null; //использую данный способ взаимодейсвия с бд в качестве демонстрации (ПЛОХОЙ ТОН) using (EShopContext _context = new EShopContext()) { //проверка нет ли такого пользователя уже в бд user = _context.Users.FirstOrDefault(u => u.Email == model.Name); } //если его нет if (user == null) { using (EShopContext _context = new EShopContext()) { //то создаем его _context.Users.Add(new User { Email = model.Name, Password = model.Password, Age = model.Age, RoleId = 2 }); //новый пользователь при регистрации будет иметь по умолчанию роль user _context.SaveChanges(); //и сразу же заходим в систему user = _context.Users.Where(u => u.Email == model.Name && u.Password == model.Password).FirstOrDefault(); } //заходим в систему if (user != null) { FormsAuthentication.SetAuthCookie(model.Name, true); return(RedirectToAction("Index", "Home")); } } else { ModelState.AddModelError("", "Пользователь с данным логином уже существует!"); //Раскомментировать для проверки работы логирования //throw new Exception("Попытка зарегестрировать уже существующий аккаунт"); } } return(View(model)); }
public void UpdateCategory(Category category) { using (var context = new EShopContext()) { context.Entry(category).State = System.Data.Entity.EntityState.Modified; context.SaveChanges(); } }
public void UpdateProduct(Product product) { using (var context = new EShopContext()) { context.Entry(product).State = System.Data.Entity.EntityState.Modified; context.SaveChanges(); } }
public void SaveCategory(Category category) { using (var context = new EShopContext()) { context.Categories.Add(category); context.SaveChanges(); } }
public int SaveOrder(Order order) { using (var context = new EShopContext()) { context.Orders.Add(order); return(context.SaveChanges()); } }
public ActionResult ExceptionsInfo(string t) { using (EShopContext db = new EShopContext()) { db.Database.ExecuteSqlCommand("TRUNCATE TABLE [ExceptionDetail]"); db.SaveChanges(); } return(RedirectToAction("ExceptionsInfo")); }
public void SaveProduct(Product product) { using (var context = new EShopContext()) { context.Entry(product.Category).State = System.Data.Entity.EntityState.Unchanged; context.Products.Add(product); context.SaveChanges(); } }
public void DeleteProduct(int ID) { using (var context = new EShopContext()) { var product = context.Products.Find(ID); product.DeletedAtUtc = DateTimeOffset.Now; context.Products.Remove(product); context.SaveChanges(); } }
public ActionResult Create([Bind(Include = "UserId,Firstname,Lastname,EmailAddress,ConfirmEmailAddress,Password,ConfirmPassword")] User user) { if (ModelState.IsValid) { db.Users.Add(user); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(user)); }
public ActionResult Create([Bind(Include = "LoginId,ConfirmEmailAddress,Password")] Login login) { if (ModelState.IsValid) { db.Logins.Add(login); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(login)); }
public void CreateOrder([FromBody] Order product, Client client) { db.Orders.Add(product); db.Clients.Add(client); if (product != null) { db.Carts.RemoveRange(db.Carts); } db.SaveChanges(); }
public async Task <IActionResult> PatchProduct(long id, [FromBody] JsonPatchDocument <ProductToPatchDTO> patchDoc) { if (patchDoc == null) { return(BadRequest()); } if (!ProductExists(id)) { return(NotFound()); } Product product = await _context.Products.FirstOrDefaultAsync(p => p.Id == id); //var patchedProduct = new ProductToPatchDTO //{ // Id = product.Id, // Label = product.Label, // Price = product.Price, // ImageUri = product.ImageUri, // Available = product.Available //}; var patchedProduct = Mapper.Map <ProductToPatchDTO>(product); patchDoc.ApplyTo(patchedProduct, ModelState); TryValidateModel(patchedProduct); if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (patchedProduct.Id != product.Id) { ModelState.AddModelError(nameof(product.Id), "Modification of ID isn't allowed."); return(BadRequest(ModelState)); } //product.Label = patchedProduct.Label; //product.ImageUri = patchedProduct.ImageUri; //product.Available = patchedProduct.Available; //product.Price = patchedProduct.Price; Mapper.Map(patchedProduct, product); if (_context.SaveChanges() == 0) { return(StatusCode(500, "A problem happened while handling your request.")); } return(NoContent()); }
public void DeleteCategory(int ID) { using (var context = new EShopContext()) { var category = context.Categories.Where(x => x.ID == ID).Include(x => x.Products).FirstOrDefault(); context.Products.RemoveRange(category.Products); //first delete products of this category category.DeletedAtUtc = DateTimeOffset.Now; context.Categories.Remove(category); context.SaveChanges(); } }
public bool UpdateOrderStatus(int ID, string status) { using (var context = new EShopContext()) { var order = context.Orders.Find(ID); order.Status = status; context.Entry(order).State = EntityState.Modified; return(context.SaveChanges() > 0); } }
public ActionResult Delete(int id) { using (var db = new EShopContext()) { var product = db.ProductsTable.Find(id); if (product != null) { db.ProductsTable.Remove(product); } db.SaveChanges(); } return(RedirectToAction("Product")); }
public ActionResult Delete(int id) { using (var db = new EShopContext()) { var category = db.CategoriesTable.Find(id); if (category != null) { db.CategoriesTable.Remove(category); } db.SaveChanges(); } return(RedirectToAction("Index")); }
public IActionResult Buy(Dictionary <string, int> ProductNames, int UserId) { using (EShopContext context = new EShopContext()) { var order = new Order(); order.UserId = UserId; context.SaveChanges(); var orders = new OrderProduct(); foreach (var productName in ProductNames) { var product = context.Products.SingleOrDefault(pro => pro.ProductName == productName.Key); orders.ProductId = product.ProductId; orders.OrderId = order.OrderId; orders.Piece = productName.Value; } context.SaveChanges(); } return(Content("Siparişiniz Başarıyla Alındı.")); }
public EmployeeEntity Create(EmployeeEntity EmployeeEntity, EmployeeEntity CreatedEmployeeEntity) { EShopContext EShopContext = new EShopContext(); EmployeeEntity.Id = Guid.NewGuid(); if (EShopContext.Employees.Any(e => e.Username.ToLower() == CreatedEmployeeEntity.Username.ToLower())) { throw new NotFoundException(); } CreatedEmployeeEntity.Password = SecurePasswordHasher.Hash(CreatedEmployeeEntity.Password); Employee Employee = new Employee(CreatedEmployeeEntity); EShopContext.Employees.Add(Employee); EShopContext.SaveChanges(); return(Get(EmployeeEntity, Employee.Id)); }
public ActionResult CreateProduct(Category model) { try { var cateAdd = new Category { Name = model.Name, NameVN = model.NameVN }; dbc.Categories.Add(cateAdd); dbc.SaveChanges(); return(JsonSuccess("Good Job")); } catch (Exception e) { return(JsonError(e.ToString())); } }
public void Complete() { try { context.SaveChanges(); _transaction.Commit(); } catch (Exception ex) { _transaction.Rollback(); throw new InternalServerErrorException(ex.Message); } finally { _transaction.Dispose(); _transaction = null; } }
public ActionResult Edit(EditCategoryViewModel model) { if (!ModelState.IsValid) { return(View(model)); } using (var db = new EShopContext()) { var category = db.CategoriesTable.FirstOrDefault(r => r.CategoryId == model.CategoryId); category.CategoryId = model.CategoryId; category.CategoryName = model.CategoryName; category.CategoryDescription = model.Description; db.SaveChanges(); } return(RedirectToAction("Index")); }
public static void EnsureSeedDataForCustomers(this EShopContext context) { if (context.Customers.Any()) { return; } var customers = new List <Customer> { new Customer { FirstName = "Nickolas", LastName = "Buxy", }, new Customer { FirstName = "Mandel", LastName = "Gudgen" }, new Customer { FirstName = "Lonnie", LastName = "Gilfether", }, new Customer { FirstName = "Boyd", LastName = "Howen", }, new Customer { FirstName = "Tamas", LastName = "Riseam", }, new Customer { FirstName = "Willow", LastName = "Bocken", }, }; context.Customers.AddRange(customers); context.SaveChanges(); }
public ActionResult Edit(EditProductViewModel model) { if (!ModelState.IsValid) { return(View(model)); } using (var db = new EShopContext()) { var product = db.ProductsTable.FirstOrDefault(r => r.ProductId == model.ProductId); product.ProductId = model.ProductId; product.ProductName = model.ProductName; product.ProductDetail = model.ProductDetail; product.ProductPrice = model.ProductPrice; product.CategoryId = model.CategoryId; db.SaveChanges(); return(RedirectToAction("Product", new { id = model.CategoryId })); } }
public ActionResult Create(CreateCategoryViewModel model) { if (!ModelState.IsValid) { return(View(model)); } using (var db = new EShopContext()) { var category = new Category { CategoryName = model.CategoryName, CategoryDescription = model.Description }; db.CategoriesTable.Add(category); db.SaveChanges(); } return(RedirectToAction("Index")); }