コード例 #1
0
        public TaxonomyEntity AddBrand(string brandLabel, bool save = true)
        {
            var brandEntityName = $"{BRAND_NAME_PREFIX}-{brandLabel.ToEntityName()}";
            var newBrand        = new TaxonomyEntity
            {
                Name           = brandEntityName,
                TaxonomyTypeId = Seed.BaseBrandSeed.ProductBrand.Id,
                Details        = new List <TaxonomyDetail>
                {
                    new TaxonomyDetail
                    {
                        Label    = brandLabel,
                        Language = "vi"
                    }
                }
            };

            var entry = _context.TaxonomyEntity.Add(newBrand);

            if (save)
            {
                _context.SaveChanges();
            }

            return(entry.Entity);
        }
コード例 #2
0
ファイル: AccountController.cs プロジェクト: itd2902/WebFix
        public ActionResult GetUser(UserViewModel userViewModel)
        {
            var user = db.Users.Where(x => x.Id == userViewModel.Id).FirstOrDefault();

            try
            {
                if (user != null)
                {
                    if (userViewModel.Gender.Equals("male"))
                    {
                        user.Gender = true;
                    }
                    else
                    {
                        user.Gender = false;
                    }
                    user.FirstName       = userViewModel.FirstName;
                    user.LastName        = userViewModel.LastName;
                    user.PhoneNumber     = userViewModel.PhoneNumber;
                    user.Address         = userViewModel.Address;
                    user.Email           = userViewModel.Email;
                    db.Entry(user).State = EntityState.Modified;
                    db.SaveChanges();
                }
            }
            catch (Exception)
            {
                throw;
            }
            ViewBag.Notify = "Cập nhật thông tin thành công.";
            return(View(userViewModel));
        }
コード例 #3
0
        public async Task <IActionResult> Edit(Product product)
        {
            using (var httpclient = new HttpClient())
            {
                httpclient.BaseAddress = new Uri("http://localhost:54183/");
                string              data     = JsonConvert.SerializeObject(product);
                StringContent       content  = new StringContent(data, Encoding.UTF8, "application/json");
                HttpResponseMessage response = await httpclient.PutAsync(httpclient.BaseAddress + "api/Product/AddProductRating/" + product.ProductId + "/" + product.Rating, content);

                if (response.IsSuccessStatusCode)
                {
                    UpdatedRating rate = new UpdatedRating();
                    rate.userid    = TokenInfo.UserID;
                    rate.ProductId = product.ProductId;
                    rate.Rating    = product.Rating;
                    context.products.Add(rate);
                    context.SaveChanges();
                    return(RedirectToAction("Index", "Customer"));
                }
                else
                {
                    return(View("Invalid"));
                }
            }
        }
コード例 #4
0
        ServiceResponse <string> ICartService.GenerateCart(Models.Cart cart)
        {
            var now = DateTime.UtcNow;

            try
            {
                _db.Carts.Add(cart);
                _db.SaveChanges();
                return(new ServiceResponse <string>
                {
                    Code = 200,
                    Time = now,
                    Message = "Cart was generated.",
                    Data = null
                });
            }
            catch (Exception)
            {
                return(new ServiceResponse <string>
                {
                    Code = 400,
                    Time = now,
                    Message = "Something wrong when generating a cart.",
                    Data = null
                });
            }
        }
コード例 #5
0
        public virtual T Add(T entity, bool isSave = true)
        {
            DbContext.Set <T>().Add(entity);
            if (isSave)
            {
                DbContext.SaveChanges();
            }


            return(entity);
        }
コード例 #6
0
        public ActionResult Create(UserViewModel userViewModel)
        {
            if (ModelState.IsValid)
            {
                var user = Mapper.Map <UserViewModel, User>(userViewModel);
                db.Users.Add(user);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(userViewModel));
        }
コード例 #7
0
        public ActionResult Create(ManufactureViewModel manufactureViewModel)
        {
            if (ModelState.IsValid)
            {
                var manufacturer = Mapper.Map <Manufacturer>(manufactureViewModel);
                manufacturer.Status = Domain.Enum.CommonStatus.Active;
                db.Manufacturers.Add(manufacturer);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View());
        }
コード例 #8
0
 public ActionResult Create(SupplierViewModel supplierViewModel)
 {
     // TODO: Add insert logic here
     if (ModelState.IsValid)
     {
         var supplier = Mapper.Map <Supplier>(supplierViewModel);
         supplier.Status = Domain.Enum.CommonStatus.Active;
         db.Suppliers.Add(supplier);
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View());
 }
コード例 #9
0
        public ActionResult Create(CategoryViewModel categoryViewModel)
        {
            if (ModelState.IsValid)
            {
                var category = Mapper.Map <Category>(categoryViewModel);
                category.Status = Domain.Enum.CommonStatus.Active;
                db.Categories.Add(category);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View());
        }
コード例 #10
0
ファイル: ProductController.cs プロジェクト: HungBay/invoice
        public IActionResult Addproduct(Product model)
        {
            var product = new Product()
            {
                Name = model.Name, Description = model.Description, UnitPrice = model.UnitPrice, PromotionPrice = model.PromotionPrice, TypeProductId = model.TypeProductId, Unit = model.Unit, New = model.New
            };

            if (product != null)
            {
                _context.Products.Add(product);
                _context.SaveChanges();
            }
            return(RedirectToAction("Index"));
        }
コード例 #11
0
 public bool Delete(int id)
 {
     try
     {
         var content = db.Contents.Find(id);
         db.Contents.Remove(content);
         db.SaveChanges();
         return(true);
     }
     catch (Exception ex)
     {
         return(false);
     }
 }
コード例 #12
0
 public User addNewUser(User model)
 {
     if (model != null)
     {
         var user = new User()
         {
             FullName = model.FullName, Email = model.Email, Password = model.Password, Phone = model.Phone, Image = model.Image, Address = model.Address
         };
         _context.Users.Add(user);
         _context.SaveChanges();
         return(model);
     }
     return(null);
 }
コード例 #13
0
 public bool Delete(int id)
 {
     try
     {
         var product = db.Products.Find(id);
         db.Products.Remove(product);
         db.SaveChanges();
         return(true);
     }
     catch (Exception ex)
     {
         return(false);
     }
 }
コード例 #14
0
        public IActionResult AddTypeProduct(TypeProduct model)
        {
            var typeProduct = new TypeProduct()
            {
                Name = model.Name, Description = model.Description, Image = model.Image
            };

            if (typeProduct != null)
            {
                _context.TypeProducts.Add(typeProduct);
                _context.SaveChanges();
            }
            return(RedirectToAction("Index"));
        }
コード例 #15
0
        public IHttpActionResult CargarVenta(VentaDTO venta)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            using (var context = new EcommerceDbContext())
            {
                try
                {
                    var ventaDB = new Venta()
                    {
                        VendedorId   = venta.Vendedor.VendedorId,
                        FechaDeVenta = venta.FechaVenta,
                    };

                    context.Ventas.Add(ventaDB);
                    context.SaveChanges();

                    venta.VentaId = ventaDB.VentaId;
                }
                catch (Exception e)
                {
                    return(BadRequest(e.InnerException.InnerException.Message));
                }
            }

            return(Ok(venta));
        }
コード例 #16
0
        public IHttpActionResult ActualizarVenta(VentaDTO venta)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            using (var context = new EcommerceDbContext())
            {
                Venta ventaDB = context.Ventas.Find(venta.VentaId);

                if (ventaDB == null)
                {
                    return(NotFound());
                }

                //Modifico los campos con los datos por parámetro
                ventaDB.VendedorId   = venta.Vendedor.VendedorId;
                ventaDB.FechaDeVenta = venta.FechaVenta;

                context.SaveChanges();
            }

            return(Ok(venta.VentaId));
        }
コード例 #17
0
        public bool RegisterAccount(Account account, out string message)
        {
            message = string.Empty;

            if (FindAccount(account) != null)
            {
                throw new Exception("Email is not valid, choose another email");
            }

            var newAccountRegister = new Account();

            newAccountRegister.AccountId = 0;

            newAccountRegister.EmailLogin = account.EmailLogin;

            newAccountRegister.PassWordSalt = DateTime.UtcNow.ToString().EncriptString();

            newAccountRegister.Password = account.Password.EncriptString() + newAccountRegister.PassWordSalt;

            newAccountRegister.CreatedDate = DateTime.Now;

            newAccountRegister.AccountRoleId = account.AccountRoleId;

            newAccountRegister.AccountStatusID = account.AccountStatusID;

            using (var dbContext = new EcommerceDbContext())
            {
                dbContext.Accounts.Add(newAccountRegister);

                newAccountRegister.AccountId = dbContext.SaveChanges();
            }

            return(true);
        }
コード例 #18
0
        public IHttpActionResult ActualizarProducto(ProductoDTO producto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            using (var context = new EcommerceDbContext())
            {
                Producto prodDB = context.Productos.Find(producto.CodProducto);

                if (prodDB == null)
                {
                    return(NotFound());
                }

                //Modifico los campos con los datos por parámetro
                prodDB.Descripcion = producto.Descripcion;
                prodDB.Stock       = producto.Stock;
                prodDB.Precio      = producto.Precio;
                prodDB.CategoriaId = producto.Categoria.CategoriaId;

                context.SaveChanges();
            }

            return(Ok(producto.CodProducto));
        }
コード例 #19
0
 private void CreateContactDetail(EcommerceDbContext context)
 {
     if (context.ContactDetails.Count() == 0)
     {
         try
         {
             var contactDetail = new Ecommerce.Model.Models.ContactDetail()
             {
                 Name    = "Shop thời trang TEDU",
                 Address = "Ngõ 77 Xuân La",
                 Email   = "*****@*****.**",
                 Lat     = 21.0633645,
                 Lng     = 105.8053274,
                 Phone   = "095423233",
                 Website = "http://tedu.com.vn",
                 Other   = "",
                 Status  = true
             };
             context.ContactDetails.Add(contactDetail);
             context.SaveChanges();
         }
         catch (DbEntityValidationException ex)
         {
             foreach (var eve in ex.EntityValidationErrors)
             {
                 Trace.WriteLine($"Entity of type \"{eve.Entry.Entity.GetType().Name}\" in state \"{eve.Entry.State}\" has the following validation error.");
                 foreach (var ve in eve.ValidationErrors)
                 {
                     Trace.WriteLine($"- Property: \"{ve.PropertyName}\", Error: \"{ve.ErrorMessage}\"");
                 }
             }
         }
     }
 }
コード例 #20
0
 private void CreatePage(EcommerceDbContext context)
 {
     if (context.Pages.Count() == 0)
     {
         try
         {
             var page = new Page()
             {
                 Name    = "Giới thiệu",
                 Alias   = "gioi-thieu",
                 Content = @"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium ",
                 Status  = true
             };
             context.Pages.Add(page);
             context.SaveChanges();
         }
         catch (DbEntityValidationException ex)
         {
             foreach (var eve in ex.EntityValidationErrors)
             {
                 Trace.WriteLine($"Entity of type \"{eve.Entry.Entity.GetType().Name}\" in state \"{eve.Entry.State}\" has the following validation error.");
                 foreach (var ve in eve.ValidationErrors)
                 {
                     Trace.WriteLine($"- Property: \"{ve.PropertyName}\", Error: \"{ve.ErrorMessage}\"");
                 }
             }
         }
     }
 }
コード例 #21
0
        public ServiceResponse <string> CreateOrder(Models.Order order)
        {
            var now = DateTime.UtcNow;

            try
            {
                _db.Orders.Add(order);
                _db.SaveChanges();
                return(new ServiceResponse <string>
                {
                    Code = 200,
                    Time = now,
                    Message = "Order was generated.",
                    Data = null
                });
            }
            catch (Exception)
            {
                return(new ServiceResponse <string>
                {
                    Code = 400,
                    Time = now,
                    Message = "Something wrong when generating an order.",
                    Data = null
                });
            }
        }
コード例 #22
0
        public IHttpActionResult ActualizarVendedor(VendedorDTO vendedor)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            using (var context = new EcommerceDbContext())
            {
                Vendedor vendedorDB = context.Vendedores.Find(vendedor.VendedorId);

                if (vendedorDB == null)
                {
                    return(NotFound());
                }

                //Modifico los campos con los datos por parámetro
                vendedorDB.Nombre            = vendedor.Nombre;
                vendedorDB.Apellido          = vendedor.Apellido;
                vendedorDB.DNI               = vendedor.NroDocumento;
                vendedorDB.FechaDeNacimiento = vendedor.FechaDeNacimiento;

                context.SaveChanges();
            }

            return(Ok(vendedor.VendedorId));
        }
コード例 #23
0
        public IHttpActionResult CargarCategoria(CategoriaDTO categoria)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            using (var context = new EcommerceDbContext())
            {
                //Instanciando un objeto de la clase categoria
                try
                {
                    var catDB = new Categoria()
                    {
                        Descripcion = categoria.Nombre
                    };

                    context.Categorias.Add(catDB);
                    context.SaveChanges();

                    //Guardar el id de la categoria registrada
                    categoria.CategoriaId = catDB.CategoriaId;
                }
                catch (Exception e)
                {
                    return(BadRequest(e.InnerException.InnerException.Message));
                }
            }

            return(Ok(categoria));
        }
コード例 #24
0
        public IHttpActionResult CargarVendedor(VendedorDTO vendedor)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            using (var context = new EcommerceDbContext())
            {
                try
                {
                    var vendedorDB = new Vendedor()
                    {
                        Nombre            = vendedor.Nombre,
                        Apellido          = vendedor.Apellido,
                        DNI               = vendedor.NroDocumento,
                        FechaDeNacimiento = vendedor.FechaDeNacimiento
                    };
                    context.Vendedores.Add(vendedorDB);
                    context.SaveChanges();
                    vendedor.VendedorId = vendedorDB.VendedorId;
                }
                catch (Exception e)
                {
                    return(BadRequest(e.InnerException.InnerException.Message));
                }
            }

            return(Ok(vendedor));
        }
コード例 #25
0
        public IHttpActionResult CargarProducto(ProductoDTO producto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            using (var context = new EcommerceDbContext())
            {
                //Instanciando un objeto de la clase Producto
                try
                {
                    var prodDB = new Producto()
                    {
                        Descripcion = producto.Descripcion,
                        Stock       = producto.Stock,
                        CategoriaId = producto.Categoria.CategoriaId,
                    };


                    context.Productos.Add(prodDB);
                    context.SaveChanges();
                    producto.CodProducto = prodDB.CodProducto;
                }
                catch (Exception e)
                {
                    return(BadRequest(e.InnerException.InnerException.Message));
                }
            }

            //Retornar un objeto de la clase ProductoDTO con el id generado
            return(Ok(producto));
        }
コード例 #26
0
ファイル: ProductController.cs プロジェクト: itd2902/WebFix
        public ActionResult SaveData(HttpPostedFileBase file, ProductViewModel productViewModel)
        {
            if (file != null)
            {
                var    product   = Mapper.Map <Product>(productViewModel);
                string fileName  = Path.GetFileNameWithoutExtension(file.FileName);
                string extension = Path.GetExtension(file.FileName);
                fileName = fileName + extension;

                file.SaveAs(Path.Combine(Server.MapPath("~/AppFile/Images/"), fileName));
                product.UrlImage        = "http://localhost:55666/AppFile/Images/" + fileName;
                db.Entry(product).State = EntityState.Added;
                db.SaveChanges();

                return(RedirectToAction("GetProductPagsing"));
            }
            return(View());
        }
コード例 #27
0
 public bool Update(Brand entity)
 {
     try
     {
         var brand = db.Brands.Find(entity.ID);
         brand.Name       = entity.Name;
         brand.MetaTitle  = entity.MetaTitle;
         brand.Link       = entity.Link;
         brand.Image      = entity.Image;
         brand.CreateDate = DateTime.Now;
         db.SaveChanges();
         return(true);
     }
     catch (Exception ex)
     {
         //logging
         return(false);
     }
 }
コード例 #28
0
        public ActionResult DatHang(Customer cus)
        {
            //Tạo đơn đặt hàng
            if (Session["GioHang"] == null)
            {
                return(RedirectToAction("Index", "Home"));
            }
            //thêm user vào db
            Customer customer = new Customer();

            if (Session["username"] == null)
            {
                //Thêm khách hàng vào bảng khách hàng đối vs khách hàng chưa có tài khoản
                customer = cus;
                db.Customers.Add(customer);
            }
            else
            {
                User user = Session["username"] as User;
                cus.FistName    = user.FirstName;
                cus.LastName    = user.LastName;
                cus.Address     = user.Address;
                cus.Email       = user.Email;
                cus.PhoneNumber = user.PhoneNumber;
                db.Customers.Add(cus);
            }

            //thêm đơn hàng
            Order orders = new Order();

            orders.OrderDate     = DateTime.Now;
            orders.StatusPayment = CommonStatus.InActive;
            orders.Cancelled     = CommonStatus.InActive;
            orders.Deleted       = CommonStatus.InActive;
            orders.CustomerId    = cus.Id;
            db.Orders.Add(orders);//lưu lại để trong db phát sinh mã đơn đặt hàng
            //thêm chi tiết đơn đặt hàng
            List <ItemGioHang> lstGioHang = LayGioHang();

            foreach (var item in lstGioHang)
            {
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.OrderId         = orders.Id;
                orderDetail.ProductId       = item.ProductCode;
                orderDetail.QuantityProduct = item.QuantityProduct;
                orderDetail.BuyPrice        = item.ProductPrice;
                int countQuantityProduct = orderDetail.QuantityProduct;
                (db.Products.Where(w => w.Id == orderDetail.ProductId).FirstOrDefault()).ProductInStock -= countQuantityProduct;//cập nhật lại số lượng tồn trong kho
                db.OrderDetails.Add(orderDetail);
            }
            db.SaveChanges();
            Session["GioHang"] = null;
            TempData["Notify"] = "Đặt hàng thành công";
            return(RedirectToAction("XemGioHang"));
        }
コード例 #29
0
 public bool Insert(OrderDetail detail)
 {
     try
     {
         db.OrderDetails.Add(detail);
         db.SaveChanges();
         return(true);
     }
     catch
     {
         return(false);
     }
 }
コード例 #30
0
 public TypeProduct addNewTypeProduct(TypeProduct model)
 {
     if (model == null)
     {
         return(null);
     }
     else
     {
         var typeProduct = new TypeProduct()
         {
             Name        = model.Name,
             Description = model.Description,
             Image       = model.Image
         };
         if (typeProduct != null)
         {
             _context.TypeProducts.Add(typeProduct);
             _context.SaveChanges();
         }
     }
     return(model);
 }