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));
        }
Beispiel #4
0
        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"));
        }
Beispiel #5
0
        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"));
            }
        }
Beispiel #6
0
        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);
        }
Beispiel #7
0
        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));
        }
Beispiel #8
0
 public void UpdateCategory(Category category)
 {
     using (var context = new EShopContext())
     {
         context.Entry(category).State = System.Data.Entity.EntityState.Modified;
         context.SaveChanges();
     }
 }
Beispiel #9
0
 public void UpdateProduct(Product product)
 {
     using (var context = new EShopContext())
     {
         context.Entry(product).State = System.Data.Entity.EntityState.Modified;
         context.SaveChanges();
     }
 }
Beispiel #10
0
 public void SaveCategory(Category category)
 {
     using (var context = new EShopContext())
     {
         context.Categories.Add(category);
         context.SaveChanges();
     }
 }
Beispiel #11
0
 public int SaveOrder(Order order)
 {
     using (var context = new EShopContext())
     {
         context.Orders.Add(order);
         return(context.SaveChanges());
     }
 }
Beispiel #12
0
 public ActionResult ExceptionsInfo(string t)
 {
     using (EShopContext db = new EShopContext())
     {
         db.Database.ExecuteSqlCommand("TRUNCATE TABLE [ExceptionDetail]");
         db.SaveChanges();
     }
     return(RedirectToAction("ExceptionsInfo"));
 }
Beispiel #13
0
        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();
            }
        }
Beispiel #14
0
 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();
     }
 }
Beispiel #15
0
        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));
        }
Beispiel #16
0
        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();
        }
Beispiel #18
0
        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());
        }
Beispiel #19
0
        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();
            }
        }
Beispiel #20
0
        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"));
        }
Beispiel #22
0
        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"));
        }
Beispiel #23
0
        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ı."));
        }
Beispiel #24
0
        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));
        }
Beispiel #25
0
 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()));
     }
 }
Beispiel #26
0
 public void Complete()
 {
     try
     {
         context.SaveChanges();
         _transaction.Commit();
     }
     catch (Exception ex)
     {
         _transaction.Rollback();
         throw new InternalServerErrorException(ex.Message);
     }
     finally
     {
         _transaction.Dispose();
         _transaction = null;
     }
 }
Beispiel #27
0
        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"));
        }
Beispiel #28
0
        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 }));
            }
        }
Beispiel #30
0
        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"));
        }