예제 #1
0
        public Response<bool> DeleteProductImages(Product_Image product_Image)
        {
            Response<bool> responseMessage = new Response<bool>();

            try
            {
                var databaseResponse = db.DeleteAllProductImages(product_Image);

                if (databaseResponse == false)
                {
                    responseMessage.returnData = false;
                    responseMessage.status = HttpStatusCode.Conflict;
                    responseMessage.ReasonPhrase = "Failed To Delte";
                }
                else if (databaseResponse == true)
                {
                    responseMessage.returnData = true;
                    responseMessage.status = HttpStatusCode.OK;
                    responseMessage.ReasonPhrase = "Product Images Deleted";
                }
            }
            catch (Exception e)
            {
                Errorhead(e);
            }
            return responseMessage;
        }
예제 #2
0
 public ActionResult Create(Product_Image product_Image)
 {
     if (ModelState.IsValid)
     {
         Product_Image pi = new Product_Image();
         pi.Product_ID = product_Image.Product_ID;
         var files = Request.Files;
         for (int i = 0; i < Request.Files.Count; i++)
         {
             HttpPostedFileBase file      = Request.Files[i];
             int              fileSize    = file.ContentLength;
             string           fileName    = file.FileName;
             string           mimeType    = file.ContentType;
             System.IO.Stream fileContent = file.InputStream;
             byte[]           bytes;
             using (BinaryReader br = new BinaryReader(fileContent))
             {
                 bytes = br.ReadBytes(fileSize);
             }
             pi.Image        = Path.GetFileName(fileName);
             pi.ContentType  = mimeType;
             pi.Data         = bytes;
             pi.Date_Created = DateTime.Now;
             db.Product_Image.Add(pi);
             db.SaveChanges();
             return(RedirectToAction("Index"));
         }
     }
     ViewBag.Product_ID = new SelectList(db.Products, "Product_ID", "Product_Name", product_Image.Product_ID);
     return(View(product_Image));
 }
예제 #3
0
        public Response<Product_Image> PutProductImages(Product_Image images)
        {
            Response<Product_Image> responseMessage = new Response<Product_Image>();
            var dbResponse = db.UpdateProductImages(images);
            try
            {

                if (dbResponse == false)
                {
                    responseMessage.returnData = null;
                    responseMessage.status = HttpStatusCode.Conflict;
                    responseMessage.ReasonPhrase = "Update Failed";
                }
                else if (dbResponse == true)
                {
                    responseMessage.returnData = null;
                    responseMessage.status = HttpStatusCode.NoContent;
                    responseMessage.ReasonPhrase = "Update Succeded";
                }

            }
            catch (Exception e)
            {
                Errorhead(e);
            }
            return responseMessage;
        }
예제 #4
0
        public Response<Product_Image> PostProductImages([FromBody] Product_Image product_Images)
        {
            {
                Response<Product_Image> responseMessage = new Response<Product_Image>();
                try
                {
                    var DbResponse = db.CreateProductImageRecord(product_Images);

                    if (DbResponse == null)
                    {
                        responseMessage.returnData = null;
                        responseMessage.ReasonPhrase = "Database Responsed With Null";
                        responseMessage.status = HttpStatusCode.Conflict;
                    }
                    else
                    {
                        responseMessage.returnData = DbResponse;
                        responseMessage.ReasonPhrase = "SuccessFully Inserted";
                        responseMessage.status = HttpStatusCode.Created;
                    }
                }
                catch (Exception e)
                {
                    Errorhead(e);
                }
                return responseMessage;
            }
        }
예제 #5
0
        public ActionResult Save()
        {
            int    id   = RequestInt("id");
            string tag  = RequestString("tag");
            byte   type = RequestByte("type");

            if (id == 0)
            {
                return(LayerAlertErrorAndReturn("请选择一个图片!"));
            }
            Product_Image model = Bll.BllProduct_Image.First(o => o.Id == id);

            if (model == null)
            {
                return(Response404());
            }

            model.Tag  = tag;
            model.Type = type;

            int rows = Bll.BllProduct_Image.Update(model);

            if (rows > 0)
            {
                return(LayerAlertSuccessAndRefresh("编辑成功"));
            }
            else
            {
                return(LayerAlertErrorAndReturn("编辑失败"));
            }
        }
예제 #6
0
        public IActionResult Create([FromBody] JObject data)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            Product model    = data["product"].ToObject <Product>();
            var     _listImg = data["images"].ToList();
            var     _listCat = data["categories"].ToList();

            Product Created = _service.Add(model);

            for (int i = 0; i < _listImg.Count; i++)
            {
                Product_Image toCreate = new Product_Image()
                {
                    ImageID   = (int)_listImg[i],
                    ProductID = Created.Id,
                };
                _service_img.Add(toCreate);
            }
            for (int i = 0; i < _listCat.Count; i++)
            {
                Product_Category toCreate = new Product_Category()
                {
                    ProductID  = Created.Id,
                    CategoryID = (int)_listCat[i],
                };
                _service_cat.Add(toCreate);
                Category toUpdate = _catrepository.GetSingleById(toCreate.Id);
                toUpdate.Quantity++;
                _catrepository.Update(toUpdate);
            }
            return(Ok("Success"));
        }
예제 #7
0
        public async Task <IActionResult> CreateProductImagesAsync(int id, [FromForm] Product_ImageDto product_ImageDto)
        {
            if (product_ImageDto.Image1 != null && product_ImageDto.Image2 != null)
            {
                var images = await _context.Product_Images.Where(m => m.ProductId == id).ToListAsync();

                _context.Product_Images.RemoveRange(images.ToArray());
                await _context.SaveChangesAsync();
            }
            var count = await _context.Product_Images.Where(m => m.ProductId == id).CountAsync();

            if (count > 1)
            {
                var images = await _context.Product_Images.Where(m => m.ProductId == id).OrderBy(m => m.Id).ToListAsync();

                _context.Product_Images.RemoveRange(images.ToArray().FirstOrDefault());
                await _context.SaveChangesAsync();
            }
            Product_Image product_Image = new Product_Image();

            if (product_ImageDto.Image1 != null)
            {
                var    extensionPath = Path.GetExtension(product_ImageDto.Image1.FileName);
                string fileName      = id + "_" + id + "_" + product_ImageDto.Image1.FileName.Substring(0, 4) + extensionPath;
                string path          = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/ProductImg", fileName);
                using (var stream = System.IO.File.Create(path))
                {
                    await product_ImageDto.Image1.CopyToAsync(stream);
                }
                string imgurl = Request.Scheme + "://" + Request.Host;
                product_Image.Image     = imgurl + "/ProductImg/" + fileName;
                product_Image.ProductId = id;
                await _context.Product_Images.AddAsync(product_Image);

                await _context.SaveChangesAsync();
            }



            Product_Image product_Image2 = new Product_Image();

            if (product_ImageDto.Image2 != null)
            {
                var    extensionPath2 = Path.GetExtension(product_ImageDto.Image2.FileName);
                string fileName2      = id + "_" + id + "_" + product_ImageDto.Image2.FileName.Substring(0, 4) + extensionPath2;
                string path2          = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/ProductImg", fileName2);
                using (var stream = System.IO.File.Create(path2))
                {
                    await product_ImageDto.Image2.CopyToAsync(stream);
                }
                string imgur2 = Request.Scheme + "://" + Request.Host;
                product_Image2.Image     = imgur2 + "/ProductImg/" + fileName2;
                product_Image2.ProductId = id;

                await _context.Product_Images.AddAsync(product_Image2);

                await _context.SaveChangesAsync();
            }
            return(Ok());
        }
예제 #8
0
        public async Task <IActionResult> Edit(int id, [Bind("Id,Title,ImageName,ProductId")] Product_Image product_Image)
        {
            if (id != product_Image.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(product_Image);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!Product_ImageExists(product_Image.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["ProductId"] = new SelectList(_context.Products, "Id", "Description_Long", product_Image.ProductId);
            return(View(product_Image));
        }
예제 #9
0
        public ActionResult DeleteConfirmed(int id)
        {
            Product_Image product_Image = db.Product_Image.Find(id);

            db.Product_Image.Remove(product_Image);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
예제 #10
0
 public ActionResult Edit([Bind(Include = "PrdImg_ID,Product_ID,Image,ContentType,Data,Date_Created")] Product_Image product_Image)
 {
     if (ModelState.IsValid)
     {
         db.Entry(product_Image).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     ViewBag.Product_ID = new SelectList(db.Products, "Product_ID", "Product_Name", product_Image.Product_ID);
     return(View(product_Image));
 }
예제 #11
0
        public HttpResponseMessage AddProductImage([FromBody] ProductImageDomain productImageDomain)
        {
            Product_Image product_Image = new Product_Image();

            mapper.Map(productImageDomain, product_Image);

            InventorySalesUnitOfWork.ProductImageRepository.Add(product_Image);

            InventorySalesUnitOfWork.Commit();
            return(Request.CreateResponse(HttpStatusCode.OK, "Success"));
        }
예제 #12
0
 private Product_Image EmptyIfNull(Product_Image p1)
 {
     p1.ma_san_pham      = (p1.ma_san_pham == null) ? "" : p1.ma_san_pham;
     p1.ma_thong_tin_anh = (p1.ma_thong_tin_anh == null) ? "" : p1.ma_thong_tin_anh;
     p1.ten_anh          = (p1.ten_anh == null) ? "" : p1.ten_anh;
     //p1.mo_ta = (p1.mo_ta == null) ? "" : p1.mo_ta;
     //p1.nguoi_duyet = (p1.nguoi_duyet == null) ? "" : p1.nguoi_duyet;
     //p1.nguoi_xuat_ban = (p1.nguoi_xuat_ban == null) ? "" : p1.nguoi_xuat_ban;
     //p1.trang_thai_duyet = (p1.trang_thai_duyet == null) ? "" : p1.trang_thai_duyet;
     //p1.trang_thai_xuat_ban = (p1.trang_thai_xuat_ban == null) ? "" : p1.trang_thai_xuat_ban;
     p1.trang_thai = (p1.trang_thai == null) ? "" : p1.trang_thai;
     return(p1);
 }
        public void ProductImageRepositoryTests_Delete()
        {
            ProductImageRepository repository = new ProductImageRepository();
            var model = new Product_Image
            {
                Product_Image_ID = 17
            };

            repository.Delete(17);
            var result = repository.GetByProduct_ID(1);

            Assert.IsTrue(result.Count() == 4);
        }
예제 #14
0
        public ActionResult Details(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Product_Image product_Image = db.Product_Image.Find(id);

            if (product_Image == null)
            {
                return(HttpNotFound());
            }
            return(View(product_Image));
        }
예제 #15
0
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Product_Image product_Image = db.Product_Image.Find(id);

            if (product_Image == null)
            {
                return(HttpNotFound());
            }
            ViewBag.Product_ID = new SelectList(db.Products, "Product_ID", "Product_Name", product_Image.Product_ID);
            return(View(product_Image));
        }
        public void ProductImageRepositoryTests_Create()
        {
            ProductImageRepository repository = new ProductImageRepository();
            var model = new Product_Image
            {
                Product_ID = 1,
                Image_Only = "OFF",
                Image      = $"product_img/001.jpg"
            };

            repository.Create(model);
            var result = repository.GetByProduct_ID(1);

            Assert.IsTrue(result.Count() == 5);
        }
예제 #17
0
        public bool DeleteAllProductImages(Product_Image product_Images)
        {
            bool status = false;

            try
            {
                db.Product_Images.DeleteOnSubmit(product_Images);
                db.SubmitChanges();
                status = true;
            }
            catch (Exception e)
            {
                Errorhead(e);
            }
            return(status);
        }
예제 #18
0
        /// <summary>
        /// 编辑图片
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Edit(int id)
        {
            if (id == 0)
            {
                return(LayerAlertErrorAndReturn("请选择一个图片!"));
            }
            Product_Image model = Bll.BllProduct_Image.First(o => o.Id == id);

            if (model == null)
            {
                return(Response404());
            }

            ViewBag.typeHtml = Tools.Enums.Tools.GetOptionHtml(typeof(Tools.Enums.ESite.ImageType), (byte)(model.Type ?? 0));
            ViewBag.taglist  = Bll.BllProduct_ImageTag.GetAll();
            return(View(model));
        }
예제 #19
0
 public ActionResult Upsert(Product_Image item, HttpPostedFileBase file)
 {
     if (asset.Create || asset.Update)
     {
         string result = "";
         try
         {
             if (file != null && file.ContentLength > 0)
             {
                 var fileName = Path.GetFileName(file.FileName);
                 var refix    = "Product_Image_" + currentUser.UserName + "_" + DateTime.Now.ToString("yyyyMMddHHmmss");
                 Helpers.UploadFile.CreateFolder(Server.MapPath("~/Images/Product_Image/"));
                 var path = Path.Combine(Server.MapPath("~/Images/Product_Image/"), refix + Path.GetExtension(fileName));
                 file.SaveAs(path);
                 item.ten_anh = refix + Path.GetExtension(fileName);
             }
             List <Product_Image> lstProdInfo = new List <Product_Image>();
             lstProdInfo.Add(item);
             result = new Product_Image_DAO().UpSert(lstProdInfo, currentUser.UserName, "Insert");
             if (result == "true")
             {
                 if (item.id == 0)// 0 insert, 1 update
                 {
                     return(Json(new { success = true, type = 0 }));
                 }
                 else
                 {
                     return(Json(new { success = true, type = 1 }));
                 }
             }
             else
             {
                 return(Json(new { success = false, message = result }));
             }
         }
         catch (Exception e)
         {
             return(Json(new { success = false, message = "Có lỗi file upload" + e.Message }));
         }
     }
     else
     {
         return(Json(new { success = false, message = "Bạn không có quyền." }));
     }
 }
예제 #20
0
        public Product_Image CreateProductImageRecord(Product_Image product_Images)
        {
            Product_Image product_Image2Response = null;

            if (product_Images == null)
            {
                return(product_Image2Response);
            }
            try
            {
                db.Product_Images.InsertOnSubmit(product_Images);
                db.SubmitChanges();
                product_Image2Response = product_Images;
            }
            catch (Exception e)
            {
                Errorhead(e);
            }
            return(product_Image2Response);
        }
예제 #21
0
        public bool UpdateProductImages(Product_Image product_Images)
        {
            bool status = false;

            try
            {
                Product_Image currentImageRecord = db.Product_Images.Where(p => p.Id == product_Images.Id).FirstOrDefault();
                currentImageRecord.Product_Id      = product_Images.Product_Id;
                currentImageRecord.Product_Image_1 = product_Images.Product_Image_1;
                currentImageRecord.Product_Image_2 = product_Images.Product_Image_2;
                currentImageRecord.Product_Image_3 = product_Images.Product_Image_3;
                db.SubmitChanges();
                status = true;
            }
            catch (Exception e)
            {
                Errorhead(e);
            }
            return(status);
        }
예제 #22
0
        public async Task <IActionResult> Create([Bind("Id,Title,ImageFile,ProductId")] Product_Image product_Image)
        {
            if (ModelState.IsValid)
            {
                //save image to wwwroot/images
                string publicPath = _hostEnvironment.WebRootPath;
                string fileName   = Path.GetFileNameWithoutExtension(product_Image.ImageFile.FileName);
                string extension  = Path.GetExtension(product_Image.ImageFile.FileName);
                //definir le nom de l'image
                product_Image.ImageName = fileName = product_Image.ProductId + fileName + DateTime.Now.ToString("fffssddmmyy") + extension;
                string path = Path.Combine(publicPath + "/Images/", fileName);
                using (var fileStream = new FileStream(path, FileMode.Create))
                {
                    await product_Image.ImageFile.CopyToAsync(fileStream);
                }
                //insert record
                _context.Add(product_Image);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["ProductId"] = new SelectList(_context.Products, "Id", "Description_Long", product_Image.ProductId);
            return(View(product_Image));
        }
예제 #23
0
        public IActionResult Update(int id, [FromBody] JObject data)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var Product = _service.GetSingleById(id);

            if (Product == null)
            {
                return(NotFound());
            }
            Product model    = data["product"].ToObject <Product>();
            var     _listImg = data["images"].ToList();
            var     _listCat = data["categories"].ToList();

            for (int i = 0; i < _listImg.Count; i++)
            {
                Product_Image toCreate = new Product_Image()
                {
                    ImageID   = (int)_listImg[i],
                    ProductID = id,
                };
                _service_img.Add(toCreate);
            }
            //Check lai danh muc xem co cai nao bi xoa k - co thi delete no ra.
            foreach (var item in _service_img.GetMulti(c => c.ProductID == id))
            {
                bool flag = true;
                for (int i = 0; i < _listImg.Count; i++)
                {
                    if (item.ImageID == (int)_listImg[i])
                    {
                        flag = false;
                        break;
                    }
                }
                if (flag)
                {
                    _service_img.Delete(item);
                }
            }
            //Add lai tat ca cac danh muc
            for (int i = 0; i < _listCat.Count; i++)
            {
                Product_Category toCreate = new Product_Category()
                {
                    CategoryID = (int)_listCat[i],
                    ProductID  = id,
                };
                _service_cat.Add(toCreate);
                Category toUpdate = _catrepository.GetSingleById(toCreate.CategoryID);
                toUpdate.Quantity++;
                _catrepository.Update(toUpdate);
            }
            //Check lai danh muc xem co cai nao bi xoa k - co thi delete no ra.
            foreach (var item in _service_cat.GetMulti(c => c.ProductID == id))
            {
                bool flag = true;
                for (int i = 0; i < _listCat.Count; i++)
                {
                    if (item.CategoryID == (int)_listCat[i])
                    {
                        flag = false;
                        break;
                    }
                }
                if (flag)
                {
                    _service_cat.Delete(item);
                    Category toUpdate = _catrepository.GetSingleById(item.CategoryID);
                    toUpdate.Quantity--;
                    _catrepository.Update(toUpdate);
                }
            }
            _service.Update(model);
            return(Ok(model));
        }
예제 #24
0
        public JsonResult CreateNewProduct(string name, int category_id, decimal original_price,
                                           int quantity, int quota_min, int quota_max,
                                           string[] barcode, string[] unit_name, int[] quantitiesPerUnit, decimal[] sell_price, string[] img)
        {
            using (IPosEntities ctx = new IPosEntities())
            {
                try
                {
                    int    default_bar_code  = GetMaxProductCodeNumber();
                    string base_product_code = barcode[0].Length > 0 ? barcode[0] : string.Format("P{0}", (++default_bar_code).ToString("D" + _product_code_number_length));
                    // Khởi tạo sản phẩm
                    Products _new_product = new Products();
                    _new_product.ID   = ctx.Products.Any() ? ctx.Products.Max(b => b.ID) + 1 : 1;
                    _new_product.Name = name;
                    _new_product.Product_Category_ID = category_id;
                    _new_product.Min_Quota           = quota_min;
                    _new_product.Max_Quota           = quota_max;
                    _new_product.Base_Product_Code   = base_product_code;
                    ctx.Products.Add(_new_product);

                    // Khởi tạo unit
                    for (int i = 0; i < barcode.Length; i++)
                    {
                        Product_Unit _new_product_unit = new Product_Unit();
                        _new_product_unit.Product_Code      = i == 0 ? base_product_code : barcode[i].Length > 0 ? barcode[i] : string.Format("P{0}", (++default_bar_code).ToString("D" + _product_code_number_length));
                        _new_product_unit.Product_ID        = _new_product.ID;
                        _new_product_unit.Base_Product_Code = base_product_code;
                        _new_product_unit.Name            = unit_name[i];
                        _new_product_unit.Original_Price  = original_price * quantitiesPerUnit[i];
                        _new_product_unit.QuantityPerUnit = quantitiesPerUnit[i];
                        _new_product_unit.Sell_Price      = sell_price[i];
                        ctx.Product_Unit.Add(_new_product_unit);
                    }

                    // Khởi tạo image
                    long _last_image_id = ctx.Product_Image.Any() ? ctx.Product_Image.Max(b => b.ID) + 1 : 1;
                    for (int i = 0; i < img.Length; i++)
                    {
                        Product_Image _new_image = new Product_Image();
                        _new_image.ID         = _last_image_id++;
                        _new_image.Number     = i + 1;
                        _new_image.Product_ID = _new_product.ID;
                        _new_image.Contents   = img[i];
                        ctx.Product_Image.Add(_new_image);
                    }

                    // Khởi tạo giao dịch "Initiation"
                    Transaction _new_transaction = new Transaction();
                    _new_transaction.code         = Utilities.Utilities.CreateNewTransactionCode(Utilities.Utilities.TransactionType.Initiation());
                    _new_transaction.Type         = Utilities.Utilities.TransactionType.Initiation();
                    _new_transaction.Created_Time = DateTime.Now;
                    _new_transaction.Created_User = ""; // MANHDC - TODO
                    _new_transaction.Shop_ID      = 0;  // MANHDC - TODO
                    _new_transaction.Discount     = 0;
                    _new_transaction.Note         = "Khởi tạo sản phẩm";
                    ctx.Transaction.Add(_new_transaction);

                    // Khởi tạo chi tiết giao dịch (số lượng, giá tiền)
                    Transaction_Detail _new_transaction_detail = new Transaction_Detail();
                    _new_transaction_detail.Transaction_Code = _new_transaction.code;
                    _new_transaction_detail.Product_Code     = _new_product.Base_Product_Code;
                    _new_transaction_detail.Quantity         = quantity;
                    _new_transaction_detail.Price            = original_price;
                    _new_transaction_detail.Total            = quantity * original_price;
                    ctx.Transaction_Detail.Add(_new_transaction_detail);

                    ctx.SaveChanges();
                }
                catch (Exception ex)
                {
                    string msg = ex.Message;
                    while (ex.InnerException != null)
                    {
                        ex  = ex.InnerException;
                        msg = ex.Message;
                    }
                    return(Json("ERR:" + msg, JsonRequestBehavior.AllowGet));
                }
            }

            return(Json("OK", JsonRequestBehavior.AllowGet));
        }
예제 #25
0
        protected override void Seed(DatabaseContext context)
        {
            List <Brand>   brandList   = new List <Brand>();
            List <MyUser>  brandUsers  = new List <MyUser>();
            List <Product> productList = new List <Product>();


            //Only one super user is creating
            MyUser SuperUser = new MyUser()
            {
                Name         = "Emre",
                Surname      = "Serbest",
                ActivateGuid = Guid.NewGuid(),
                Email        = "*****@*****.**",
                IsActive     = true,
                IsSuperUser  = true,
                HasBrand     = false,
                Username     = "******",
                Password     = "******",
                UserImage    = FakeData.NetworkData.GetDomain(),
            };

            context.MyUsers.Add(SuperUser);
            context.SaveChanges();


            //Creating 7 Admins (Brand Users)
            for (int i = 0; i < 7; i++)
            {
                MyUser BrandUser = new MyUser()
                {
                    Name         = FakeData.NameData.GetFirstName(),
                    Surname      = FakeData.NameData.GetSurname(),
                    Email        = FakeData.NetworkData.GetEmail(),
                    UserImage    = FakeData.NetworkData.GetDomain(),
                    ActivateGuid = Guid.NewGuid(),
                    IsActive     = true,
                    IsSuperUser  = false,
                    HasBrand     = true,
                    Username     = $"brandUser{i}",
                    Password     = "******"
                };
                brandUsers.Add(BrandUser);
                context.MyUsers.Add(BrandUser);
            }
            context.SaveChanges();


            //List<MyUser> users = context.MyUsers.ToList();
            //Creating a Brand for the current BrandUser
            foreach (MyUser item in brandUsers)
            {
                Brand newBrand = new Brand()
                {
                    BrandName  = FakeData.NameData.GetCompanyName(),
                    BrandImage = "BrandImage.jpg",
                    Tag        = FakeData.TextData.GetSentence(),
                    MyUser     = item,
                };
                brandList.Add(newBrand);
                context.Brands.Add(newBrand);
            }
            context.SaveChanges();

            // Creating categories(3,6) for the current Brand

            foreach (var itemBrand in brandList)
            {
                for (int a = 0; a < FakeData.NumberData.GetNumber(3, 6); a++)
                {
                    Category category = new Category()
                    {
                        Title       = FakeData.NameData.GetSurname(),
                        Description = FakeData.TextData.GetSentence(),
                        Brand       = itemBrand,
                    };

                    context.Categories.Add(category);
                }
            }
            context.SaveChanges();

            List <string> sizeList = new List <string>();

            sizeList.Add("XS");
            sizeList.Add("S");
            sizeList.Add("M");
            sizeList.Add("L");
            sizeList.Add("XL");
            sizeList.Add("XXL");

            List <string> colorList = new List <string>();

            colorList.Add("black");
            colorList.Add("white");
            colorList.Add("pink");
            colorList.Add("green");
            colorList.Add("red");


            //Creating 50 products
            for (int j = 0; j < 50; j++)
            {
                Product newProduct = new Product()
                {
                    ProductName        = FakeData.NameData.GetCompanyName(),
                    ProductDescription = FakeData.TextData.GetSentence(),
                    Brand = brandList[(FakeData.NumberData.GetNumber(0, brandList.Count - 1))],
                    Size  = sizeList[(FakeData.NumberData.GetNumber(0, sizeList.Count - 1))],
                    Color = colorList[(FakeData.NumberData.GetNumber(0, colorList.Count - 1))],
                    Stock = FakeData.NumberData.GetNumber(10, 100),
                    Price = FakeData.NumberData.GetDouble(),
                    DiscountPercentage = FakeData.NumberData.GetNumber(0, 10),
                };

                productList.Add(newProduct);
                context.Product.Add(newProduct);
            }
            context.SaveChanges();


            List <MyUser> standartUserList = new List <MyUser>();

            for (int s = 0; s < 10; s++)
            {
                MyUser standartUser = new MyUser()
                {
                    Name         = FakeData.NameData.GetFirstName(),
                    Surname      = FakeData.NameData.GetSurname(),
                    Email        = FakeData.NetworkData.GetEmail(),
                    UserImage    = FakeData.NetworkData.GetDomain(),
                    ActivateGuid = Guid.NewGuid(),
                    IsActive     = true,
                    IsSuperUser  = false,
                    HasBrand     = false,
                    Username     = $"standartUser{s}",
                    Password     = "******"
                };
                standartUserList.Add(standartUser);
                context.MyUsers.Add(standartUser);
                context.SaveChanges();

                //Creating Wishlist for standartusers randomly.
                if (FakeData.BooleanData.GetBoolean())
                {
                    Wishlist wishlist = new Wishlist()
                    {
                        IsPublic = FakeData.BooleanData.GetBoolean(),
                        Title    = FakeData.BooleanData.GetBoolean() ? "Specialized-WishList-Title" : "WishList",
                        MyUser   = standartUser,
                    };
                    context.Wishlists.Add(wishlist);

                    //Adding products to the wishlist randomly
                    for (int i = 0; i < FakeData.NumberData.GetNumber(3, 10); i++)
                    {
                        Wishlist_Products wishlist_products = new Wishlist_Products()
                        {
                            Product  = productList[FakeData.NumberData.GetNumber(0, 45)],
                            Wishlist = wishlist
                        };
                        context.WishlistProduct.Add(wishlist_products);
                    }
                }

                //Creating Sale for standart users randomly
                if (FakeData.BooleanData.GetBoolean())
                {
                    for (int salecounter = 0; salecounter < FakeData.NumberData.GetNumber(3, 20); salecounter++)
                    {
                        double totalPrice = 0;

                        Sale_Details saleDetail = new Sale_Details()
                        {
                        };

                        Sale sale = new Sale()
                        {
                        };
                        for (int saleDetailCounter = 0; saleDetailCounter < FakeData.NumberData.GetNumber(2, 8); saleDetailCounter++)
                        {
                            Product soldProduct  = productList[FakeData.NumberData.GetNumber(0, 49)];
                            int     tempQuantity = FakeData.NumberData.GetNumber(1, 4);
                            double  tempSubTotal = soldProduct.Price * tempQuantity;
                            totalPrice += tempSubTotal;


                            saleDetail.Quantity     = tempQuantity;
                            saleDetail.Product      = soldProduct;
                            saleDetail.InstantPrice = soldProduct.Price;
                            saleDetail.SubTotal     = tempSubTotal;
                            saleDetail.Sale         = sale;


                            context.Sale_Details.Add(saleDetail);
                        }


                        sale.Customer   = standartUser;
                        sale.Date       = FakeData.DateTimeData.GetDatetime();
                        sale.Time       = FakeData.DateTimeData.GetDatetime();
                        sale.TotalPrice = totalPrice;
                        sale.TotalVat   = 18;



                        context.Sales.Add(sale);
                    }
                }
            }

            context.SaveChanges();



            //Adding product images
            foreach (Product itemProduct in productList)
            {
                for (int i = 0; i < FakeData.NumberData.GetNumber(3, 7); i++)
                {
                    Product_Image productImage = new Product_Image()
                    {
                        Url     = $"picture{i}.jpg",
                        Product = itemProduct,
                    };
                    context.ProductImages.Add(productImage);


                    //Adding comments
                    Comment newComment = new Comment()
                    {
                        Text    = FakeData.TextData.GetSentences(FakeData.NumberData.GetNumber(1, 3)),
                        Owner   = standartUserList[FakeData.NumberData.GetNumber(0, standartUserList.Count - 1)],
                        Product = itemProduct,
                    };
                    context.Comments.Add(newComment);


                    //Creating likes
                    Like like = new Like()
                    {
                        LikeOwner = standartUserList[FakeData.NumberData.GetNumber(0, standartUserList.Count - 1)],
                        Product   = itemProduct,
                    };
                    context.Likes.Add(like);
                }
            }
            context.SaveChanges();
        }
예제 #26
0
        public async Task <Product> Save(Guid productTypeId, Guid storeId, IEnumerable <IFormFile> images, string name, int stock, int size, string barcode, string productNo, int color, decimal price)
        {
            var dbUser = await _userManager.FindByNameAsync(_httpContextAccessor.HttpContext.User?.Identity?.Name);

            Product product = new Product()
            {
                UserId        = dbUser.Id,
                ProductTypeId = productTypeId,
                Name          = name,
                Stock         = stock,
                Size          = size,
                Price         = price,
                Color         = color,
                Barcode       = barcode,
                ProductNo     = productNo
            };
            await _unitOfWork.Products.AddAsync(product);

            Product_Store product_Store = new Product_Store()
            {
                ProductId = product.Id,
                StoreId   = storeId
            };
            await _unitOfWork.Product_Stores.AddAsync(product_Store);


            if (images != null)
            {
                int sort = 1;
                foreach (var item in images)
                {
                    //Orjinal dosyamızın extensionunu alıyoruz
                    string extension = Path.GetExtension(item.FileName);
                    Guid   imageId   = Guid.NewGuid();
                    string p         = $"{imageId}{extension}";
                    string path      = Path.Combine("C:\\inetpub\\wwwroot\\AlisverisAsistani\\ProductImages\\" + p);
                    Image  image     = new Image()
                    {
                        Path = $"ProductImages\\{p}",
                        Sort = sort
                    };
                    await _unitOfWork.Images.AddAsync(image);

                    using (var stream = new FileStream(path, FileMode.Create))
                    {
                        await item.CopyToAsync(stream);
                    }
                    sort++;

                    Product_Image product_Image = new Product_Image()
                    {
                        ProductId = product.Id,
                        ImageId   = image.Id
                    };
                    await _unitOfWork.Product_Images.AddAsync(product_Image);
                }
            }

            await _unitOfWork.CommitAsync();

            return(product);
        }
예제 #27
0
        protected override void Seed(DatabaseContext context)
        {
            List <Brand>   brandList   = new List <Brand>();
            List <MyUser>  brandUsers  = new List <MyUser>();
            List <Product> productList = new List <Product>();


            //Only one super user is creating
            MyUser SuperUser = new MyUser()
            {
                Name             = "Emre",
                Surname          = "Serbest",
                ActivateGuid     = Guid.NewGuid(),
                Email            = "*****@*****.**",
                Address          = FakeData.PlaceData.GetAddress(),
                Gender           = "Male",
                IsActive         = true,
                IsSuperUser      = true,
                HasBrand         = false,
                Username         = "******",
                Password         = "******",
                UserImage        = "super_user_avatar.png",
                CreatedOn        = DateTime.Now,
                ModifiedOn       = DateTime.Now,
                ModifiedUsername = "******",
            };

            context.MyUsers.Add(SuperUser);
            context.SaveChanges();


            //Creating 7 Admins (Brand Users)
            for (int i = 0; i < 7; i++)
            {
                var gender     = FakeData.BooleanData.GetBoolean() ? "Male" : "Female";
                var avatar_url = "default_user_avatar";
                if (gender == "Male")
                {
                    avatar_url = "male_user_avatar.png";
                }
                else
                {
                    avatar_url = "female_user_avatar.png";
                }

                MyUser BrandUser = new MyUser()
                {
                    Name             = FakeData.NameData.GetFirstName(),
                    Surname          = FakeData.NameData.GetSurname(),
                    Email            = FakeData.NetworkData.GetEmail(),
                    Address          = FakeData.PlaceData.GetAddress(),
                    Gender           = gender,
                    UserImage        = avatar_url,
                    ActivateGuid     = Guid.NewGuid(),
                    IsActive         = true,
                    IsSuperUser      = false,
                    HasBrand         = true,
                    Username         = $"brandUser{i}",
                    Password         = "******",
                    CreatedOn        = DateTime.Now,
                    ModifiedOn       = DateTime.Now,
                    ModifiedUsername = "******",
                };
                brandUsers.Add(BrandUser);
                context.MyUsers.Add(BrandUser);
            }
            context.SaveChanges();


            //List<MyUser> users = context.MyUsers.ToList();
            //Creating a Brand for the current BrandUser
            foreach (MyUser item in brandUsers)
            {
                Brand newBrand = new Brand()
                {
                    BrandName        = FakeData.NameData.GetCompanyName(),
                    BrandImage       = "logo_placeholder.png",
                    Tag              = FakeData.TextData.GetSentence(),
                    MyUser           = item,
                    CreatedOn        = DateTime.Now,
                    ModifiedOn       = DateTime.Now,
                    ModifiedUsername = "******",
                };
                brandList.Add(newBrand);
                context.Brands.Add(newBrand);
            }
            context.SaveChanges();



            List <string> sizeList = new List <string>();

            sizeList.Add("XS");
            sizeList.Add("S");
            sizeList.Add("M");
            sizeList.Add("L");
            sizeList.Add("XL");
            sizeList.Add("XXL");

            List <string> colorList = new List <string>();

            colorList.Add("black");
            colorList.Add("white");
            colorList.Add("pink");
            colorList.Add("green");
            colorList.Add("red");

            // Creating Categories MEN, WOMEN, KidsAndBabies

            Category Men = new Category()
            {
                Title            = "Men",
                Description      = "Only for men shopping items",
                CreatedOn        = DateTime.Now,
                ModifiedOn       = DateTime.Now,
                ModifiedUsername = "******",
            };

            context.Categories.Add(Men);

            Category Women = new Category()
            {
                Title            = "Women",
                Description      = "Only for women shopping items",
                CreatedOn        = DateTime.Now,
                ModifiedOn       = DateTime.Now,
                ModifiedUsername = "******",
            };

            context.Categories.Add(Women);

            Category KidsAndBabies = new Category()
            {
                Title            = "Kids & Babies",
                Description      = "Kids and Babies shopping items",
                CreatedOn        = DateTime.Now,
                ModifiedOn       = DateTime.Now,
                ModifiedUsername = "******",
            };

            context.Categories.Add(KidsAndBabies);
            context.SaveChanges();
            List <Category>    mainCategories             = new List <Category>();
            List <SubCategory> MenSubCategories           = new List <SubCategory>();
            List <SubCategory> WomenSubCategories         = new List <SubCategory>();
            List <SubCategory> KidsAndBabiesSubCategories = new List <SubCategory>();

            List <string> MenCatNames = new List <string>()
            {
                "Hoodies",
                "Jackets",
                "T-shirts",
                "Shirts",
                "Socks",
                "Jeans",
                "Casual Pants",
                "Cargo Pants",
                "Suits",
                "Boxers",
                "Men's Sleep Lounge",
                "Accessories",
            };

            List <string> WomenCatNames = new List <string>()
            {
                "Dress",
                "Blouses",
                "T-shirts",
                "Beach Style",
                "Skirts",
                "Shorts",
                "Jean",
                "Blazers",
                "Bra",
                "Sleep Lounge",
                "Accessories",
            };

            List <string> KidsCatNames = new List <string>()
            {
                "Dresses",
                "Clothing Sets",
                "Family Matching Clothes",
                "Shoes",
                "Swim Suits",
                "Shorts",
                "Baby Mother",
                "Toys",
            };

            foreach (string subCat in MenCatNames)
            {
                SubCategory subCatMen = new SubCategory()
                {
                    Title            = subCat,
                    Description      = "Men Shopping",
                    Category         = Men,
                    CreatedOn        = DateTime.Now,
                    ModifiedOn       = DateTime.Now,
                    ModifiedUsername = "******",
                };

                MenSubCategories.Add(subCatMen);
                context.SubCategories.Add(subCatMen);
            }

            foreach (string subCat in WomenCatNames)
            {
                SubCategory subCatWomen = new SubCategory()
                {
                    Title            = subCat,
                    Description      = "Women Shopping",
                    Category         = Women,
                    CreatedOn        = DateTime.Now,
                    ModifiedOn       = DateTime.Now,
                    ModifiedUsername = "******",
                };

                WomenSubCategories.Add(subCatWomen);
                context.SubCategories.Add(subCatWomen);
            }

            foreach (string subCat in KidsCatNames)
            {
                SubCategory subCatKidsAndBabies = new SubCategory()
                {
                    Title            = subCat,
                    Description      = "Kids & Babies Shopping",
                    Category         = KidsAndBabies,
                    CreatedOn        = DateTime.Now,
                    ModifiedOn       = DateTime.Now,
                    ModifiedUsername = "******",
                };

                KidsAndBabiesSubCategories.Add(subCatKidsAndBabies);
                context.SubCategories.Add(subCatKidsAndBabies);
            }

            context.SaveChanges();

            mainCategories.Add(Men);
            mainCategories.Add(Women);
            mainCategories.Add(KidsAndBabies);


            //Creating 50 products
            for (int j = 0; j < 50; j++)
            {
                Category    randomCat = mainCategories[FakeData.NumberData.GetNumber(0, mainCategories.Count - 1)];
                SubCategory randomSubCat;
                if (randomCat == Men)
                {
                    randomSubCat = MenSubCategories[FakeData.NumberData.GetNumber(0, MenSubCategories.Count - 1)];
                }
                else if (randomCat == Women)
                {
                    randomSubCat = WomenSubCategories[FakeData.NumberData.GetNumber(0, WomenSubCategories.Count - 1)];
                }
                else
                {
                    randomSubCat = KidsAndBabiesSubCategories[FakeData.NumberData.GetNumber(0, KidsAndBabiesSubCategories.Count - 1)];
                }

                Product newProduct = new Product()
                {
                    ProductName        = FakeData.NameData.GetCompanyName(),
                    ProductDescription = FakeData.TextData.GetSentence(),
                    Brand = brandList[(FakeData.NumberData.GetNumber(0, brandList.Count - 1))],
                    Size  = sizeList[(FakeData.NumberData.GetNumber(0, sizeList.Count - 1))],
                    Color = colorList[(FakeData.NumberData.GetNumber(0, colorList.Count - 1))],
                    Stock = FakeData.NumberData.GetNumber(10, 100),
                    Price = FakeData.NumberData.GetNumber(15, 150),
                    DiscountPercentage = FakeData.NumberData.GetNumber(0, 10),
                    Category           = randomCat,
                    SubCategory        = randomSubCat,
                    CreatedOn          = DateTime.Now,
                    ModifiedOn         = DateTime.Now,
                    ModifiedUsername   = "******",
                };

                productList.Add(newProduct);
                context.Product.Add(newProduct);
            }
            context.SaveChanges();


            List <MyUser> standartUserList = new List <MyUser>();

            for (int s = 0; s < 10; s++)
            {
                MyUser standartUser = new MyUser()
                {
                    Name             = FakeData.NameData.GetFirstName(),
                    Surname          = FakeData.NameData.GetSurname(),
                    Email            = FakeData.NetworkData.GetEmail(),
                    Address          = FakeData.PlaceData.GetAddress(),
                    Gender           = FakeData.BooleanData.GetBoolean() ? "Male" : "Female",
                    UserImage        = FakeData.NetworkData.GetDomain(),
                    ActivateGuid     = Guid.NewGuid(),
                    IsActive         = true,
                    IsSuperUser      = false,
                    HasBrand         = false,
                    Username         = $"standartUser{s}",
                    Password         = "******",
                    CreatedOn        = DateTime.Now,
                    ModifiedOn       = DateTime.Now,
                    ModifiedUsername = "******",
                };
                standartUserList.Add(standartUser);
                context.MyUsers.Add(standartUser);
                context.SaveChanges();

                //Creating Wishlist for standartusers randomly.
                if (FakeData.BooleanData.GetBoolean())
                {
                    Wishlist wishlist = new Wishlist()
                    {
                        IsPublic = FakeData.BooleanData.GetBoolean(),
                        Title    = FakeData.BooleanData.GetBoolean() ? "Specialized-WishList-Title" : "WishList",
                        MyUser   = standartUser,
                    };
                    context.Wishlists.Add(wishlist);

                    //Adding products to the wishlist randomly
                    for (int i = 0; i < FakeData.NumberData.GetNumber(3, 10); i++)
                    {
                        Wishlist_Products wishlist_products = new Wishlist_Products()
                        {
                            Product  = productList[FakeData.NumberData.GetNumber(0, 45)],
                            Wishlist = wishlist
                        };
                        context.WishlistProduct.Add(wishlist_products);
                    }
                }

                //Creating Sale for standart users randomly
                if (FakeData.BooleanData.GetBoolean())
                {
                    for (int salecounter = 0; salecounter < FakeData.NumberData.GetNumber(3, 20); salecounter++)
                    {
                        double totalPrice = 0;

                        Sale_Details saleDetail = new Sale_Details()
                        {
                        };

                        Sale sale = new Sale()
                        {
                        };
                        for (int saleDetailCounter = 0; saleDetailCounter < FakeData.NumberData.GetNumber(2, 8); saleDetailCounter++)
                        {
                            Product soldProduct  = productList[FakeData.NumberData.GetNumber(0, 49)];
                            int     tempQuantity = FakeData.NumberData.GetNumber(1, 4);
                            double  tempSubTotal = soldProduct.Price * tempQuantity;
                            totalPrice += tempSubTotal;


                            saleDetail.Quantity     = tempQuantity;
                            saleDetail.Product      = soldProduct;
                            saleDetail.InstantPrice = soldProduct.Price;
                            saleDetail.SubTotal     = tempSubTotal;
                            saleDetail.Sale         = sale;


                            context.Sale_Details.Add(saleDetail);
                        }


                        sale.Customer   = standartUser;
                        sale.Date       = FakeData.DateTimeData.GetDatetime();
                        sale.Time       = FakeData.DateTimeData.GetDatetime();
                        sale.TotalPrice = totalPrice;
                        sale.TotalVat   = 18;



                        context.Sales.Add(sale);
                    }
                }
            }

            context.SaveChanges();



            //Adding product images
            foreach (Product itemProduct in productList)
            {
                for (int i = 0; i < FakeData.NumberData.GetNumber(3, 7); i++)
                {
                    Product_Image productImage = new Product_Image()
                    {
                        Url     = $"picture{i}.jpg",
                        Product = itemProduct,
                    };
                    context.ProductImages.Add(productImage);


                    MyUser owner = standartUserList[FakeData.NumberData.GetNumber(0, standartUserList.Count - 1)];
                    //Adding comments
                    Comment newComment = new Comment()
                    {
                        Text             = FakeData.TextData.GetSentences(FakeData.NumberData.GetNumber(1, 3)),
                        Owner            = owner,
                        Product          = itemProduct,
                        CreatedOn        = DateTime.Now,
                        ModifiedOn       = DateTime.Now,
                        ModifiedUsername = owner.Username,
                    };
                    context.Comments.Add(newComment);


                    //Creating likes
                    Rate Rate = new Rate()
                    {
                        RateOwner = standartUserList[FakeData.NumberData.GetNumber(0, standartUserList.Count - 1)],
                        Product   = itemProduct,
                    };
                    context.Rates.Add(Rate);
                }
            }
            context.SaveChanges();
        }