public ResultDTO addProduct([FromBody] AddProductDTO model)
        {
            if (!ModelState.IsValid)
            {
                return(new ResultErrorDTO
                {
                    Code = 400,
                    Errors = CustomValidator.getErrorsByModelState(ModelState)
                });
            }

            _context.Products.Add(new Product
            {
                Color     = model.Color,
                Details   = model.Details,
                Name      = model.Name,
                Price     = model.Price,
                Size      = model.Size,
                URL_Image = model.URL_Image
            });

            _context.SaveChanges();

            return(new ResultDTO
            {
                Code = 200,
                Message = "Success!"
            });
        }
Esempio n. 2
0
        public ResultDTO addProduct([FromBody] AddProductDTO model)
        {
            if (!ModelState.IsValid)
            {
                return(new ResultErrorDTO
                {
                    Code = 400,
                    Errors = CustomValidator.getErrorsByModelState(ModelState)
                });
            }

            _context.Products.Add(new DataAccess.Entity.Products
            {
                FullName    = model.FullName,
                Description = model.Description,
                Img_URL     = model.Img_URL,
                Price       = model.Price
            });

            _context.SaveChanges();

            return(new ResultDTO
            {
                Code = 200,
                Message = "Success!"
            });
        }
        public IEnumerable <Product> AddProduct(AddProductDTO productToAdd)
        {
            var repo = new ProductRepository();

            repo.AddNewProduct(productToAdd);
            return(repo.GetAllProducts());
        }
Esempio n. 4
0
        public async Task <ProductInfoDTO> PutUpForAuction([FromForm] AddProductDTO productData)
        {
            if (ModelState.IsValid)
            {
                byte[] productImage;
                using (var memoryStream = new MemoryStream()) {
                    await productData.ProductImage.CopyToAsync(memoryStream);

                    productImage = memoryStream.ToArray();
                }

                var product = await _biddingService.PutUpForAuction(
                    _userManager.GetUserId(User),
                    productData.ProductInfo.Name,
                    productData.ProductInfo.Category,
                    productData.ProductInfo.StartingPrice,
                    DateTime.UtcNow.AddMinutes(productData.ProductInfo.Duration),
                    productData.ProductInfo.Description,
                    productImage
                    );

                return(new ProductInfoDTO(product));
            }
            else
            {
                throw new LemonInvalidException("Bad product data");
            }
        }
        public IActionResult AddProduct([FromBody] AddProductDTO addProductDTO)
        {
            Products product = _mapper.Map <Products>(addProductDTO);

            product.AddedDate = DateTime.Now;
            _servicePro.Add(product);
            return(Ok(product));
        }
Esempio n. 6
0
        public ActionResult Edit(AddProductVM product)
        {
            Mapper.Initialize(c => c.CreateMap <AddProductVM, AddProductDTO>());
            AddProductDTO    productDTO = Mapper.Map <AddProductVM, AddProductDTO>(product);
            OperationDetails op         = _productManagerService.EditProduct(productDTO.Id, productDTO);

            return(Json(new { Succedeed = op.Succedeed, message = op.Message, prop = op.Property }));
        }
        public IActionResult UpdateProduct([FromBody] AddProductDTO addProductDTO)
        {
            //var currentProduct = _servicePro.Find((int)addProductDTO.ProductId);
            Products product = _mapper.Map <Products>(addProductDTO);

            //if (addProductDTO.PictureUrl == null)
            //{
            //    product.PictureUrl = currentProduct.PictureUrl;
            //}
            //product.AddedDate = currentProduct.AddedDate;
            _servicePro.Update(product);
            return(Ok(product));
        }
        public async Task InsertProduct(AddProductDTO productDTO)
        {
            var product = new Product
            {
                Id          = productDTO.ProductId,
                Name        = productDTO.Name,
                ProductType = (ProductType)Enum.Parse(typeof(ProductType), productDTO.ProductType, true),
                Price       = productDTO.Price
            };

            this.dbContext.Products.Add(product);
            await dbContext.SaveChangesAsync();
        }
Esempio n. 9
0
        public async Task <ActionResult> Post([FromForm] AddProductDTO productdto)
        {
            try
            {
                await _products.AddAsync(productdto);

                return(StatusCode(201));
            }
            catch (Exception ex)
            {
                return(StatusCode((int)HttpStatusCode.InternalServerError, ex.Message));
            }
        }
Esempio n. 10
0
        public ActionResult Add(AddProductDTO productDTO)
        {
            if (!ModelState.IsValid)
            {
                var model = new ProductViewModel
                {
                    Product = new ProductDTO(),
                    ProductSpecification = new ProductSpecificationDTO(),
                    Categories           = _categoryRepo.Categories.AsEnumerable(),
                    Statuses             = _statusRepo.Statuses.AsEnumerable(),
                    IsFeatured           = productDTO.IsFeatured,
                    IsActive             = productDTO.IsActive
                };
                return(View(model));
            }

            if (_productRepo.FindBySku(productDTO.Sku) != null)
            {
                var model = new ProductViewModel
                {
                    Product = _mapper.Map <AddProductDTO, ProductDTO>(productDTO),
                    ProductSpecification = productDTO.ProductSpecification,
                    Categories           = _categoryRepo.Categories.AsEnumerable(),
                    Statuses             = _statusRepo.Statuses.AsEnumerable(),
                    IsFeatured           = productDTO.IsFeatured,
                    IsActive             = productDTO.IsActive
                };
                ModelState.AddModelError("", "SKU is used by another product.");
                return(View(model));
            }

            var images = new List <string>();

            if (!string.IsNullOrWhiteSpace(productDTO.Images))
            {
                foreach (var imgUrl in productDTO.Images.Split('@'))
                {
                    images.Add(imgUrl);
                }
            }

            var product = _mapper.Map <AddProductDTO, ProductDTO>(productDTO);

            product.Images = images;

            _productRepo.Save(product, productDTO.ProductSpecification);

            TempData["SaveSuccess"] = "Success";
            return(RedirectToAction("add"));
        }
Esempio n. 11
0
        public ActionResult Add(AddProductVM product)
        {
            // To exclude the size or color from validation when the product has only color or only size
            if (product.HasSize || product.HasColor)
            {
                if (!product.HasColor)
                {
                    for (int i = 0; i < product.ProductOptionValues.Count; i++)
                    {
                        this.ModelState.Remove("ProductOptionValues[" + i + "].ColorValueId");
                    }
                }
                if (!product.HasSize)
                {
                    for (int i = 0; i < product.ProductOptionValues.Count; i++)
                    {
                        this.ModelState.Remove("ProductOptionValues[" + i + "].SizeValueId");
                    }
                }
            }
            //////////////

            if (ModelState.IsValid)
            {
                Mapper.Initialize(c => c.CreateMap <AddProductVM, AddProductDTO>());
                AddProductDTO    productdto = Mapper.Map <AddProductVM, AddProductDTO>(product);
                OperationDetails op         = _productManagerService.AddProduct(productdto);


                return(Json(new { Succedeed = op.Succedeed, message = op.Message, prop = op.Property }));
            }
            else
            {
                var errors = ModelState.Select(x => x.Value.Errors)
                             .Where(y => y.Count > 0)
                             .ToList();
                product.Colors    = _productManagerService.GetAllColors();
                product.Sizes     = _productManagerService.GetSizesOfCat(product.SizeCategoryId);
                product.Designers = _DesignerService.GetAllDesigners(CurrentLanguage);
                //product.BaseCategories = _productManagerService.GetSubCategories((long)CurrentWebsite, CurrentLanguage);
                product.BaseCategories = _categoryService.GetAllPathsByWebsite(CurrentWebsite, CurrentLanguage);
                List <AttributeGroupDTO> attribueGroups = _attributeGroupService.GetAllAttributeGroups(CurrentLanguage);
                product.AttributesGroups = attribueGroups;
                if (product.HasSize)
                {
                    product.AllSizeAttributes = _manageSizeAttributesService.GetSizeAttributesBySizeCaategoryId(product.SizeCategoryId.Value, CurrentLanguage);
                }
                return(View(product));
            }
        }
        public IActionResult AddProduct([FromBody] AddProductDTO productDTO, [FromServices] AddProductCommand addProductCommand)
        {
            AddTrace(addProductCommand);
            addProductCommand.ProductDTO = productDTO;
            addProductCommand.Execute();

            if (!addProductCommand.IsSuccesful)
            {
                Logger.Warn("Product addition failed, productDTO: {@productDTO} ", productDTO);
                return(BadRequest(addProductCommand.Errors));
            }


            return(NoContent());
        }
Esempio n. 13
0
        public async Task UpdateAsync(int id, AddProductDTO productDTO)
        {
            Product product = _mapper.Map <AddProductDTO, Product>(productDTO);

            if (productDTO.Photo != null)
            {
                using (var memoryStream = new MemoryStream())
                {
                    await productDTO.Photo.CopyToAsync(memoryStream);

                    product.Image = memoryStream.ToArray();
                }
            }

            await _repo.UpdateAsync(product);
        }
Esempio n. 14
0
        public async Task <IActionResult> Put(int id, [FromBody] AddProductDTO product)
        {
            if (id != product.Id)
            {
                return(BadRequest("Id doesn't match"));
            }

            try
            {
                await _products.UpdateAsync(id, product);

                return(Ok(id));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
Esempio n. 15
0
        public IActionResult AddProduct(AddProductVM addProductVM)
        {
            if (!ModelState.IsValid)
            {
                ShowToaster("Please fill required fields", ToasterLevel.Danger);
                return(RedirectToAction("Products", "Company", new { companyId = addProductVM.CompanyId }));
            }
            var           config = new MapperConfiguration(cfg => cfg.CreateMap <AddProductVM, AddProductDTO>());
            var           mapper = new Mapper(config);
            AddProductDTO dto    = mapper.DefaultContext.Mapper.Map <AddProductDTO>(addProductVM);

            dto.ImagePath = UploadedFile(addProductVM);
            _userService.CreateAndUpdateProduct(dto);
            var status = addProductVM.ProductId == 0 ? "Created" : "Updated";

            ShowToaster("Product " + status + " successfully", ToasterLevel.Success);

            return(RedirectToAction("Products", "Company", new { companyId = dto.CompanyId }));
        }
Esempio n. 16
0
        public bool AddNewProduct(AddProductDTO productToAdd)
        {
            using (var db = new SqlConnection(_connectionString))
            {
                var sql = @"INSERT INTO [dbo].[Product]
                            ([CategoryId]
                            ,[Name]
                            ,[Brand]
                            ,[Description]
                            ,[ProductImageUrl])
                            output inserted.*
                             VALUES
                            (@CategoryId
                            ,@Name
                            ,@Brand
                            ,@Description
                            ,@ProductImageUrl)";

                return(db.Execute(sql, productToAdd) == 1);
            }
        }
Esempio n. 17
0
        public ActionResult Edit(long Id)
        {
            AddProductDTO product = _productManagerService.GetEditProduct(Id, CurrentLanguage);

            product.Colors    = _productManagerService.GetAllColors();
            product.Sizes     = _productManagerService.GetSizesOfCat(product.SizeCategoryId);
            product.Designers = _DesignerService.GetAllDesigners(CurrentLanguage);

            List <AttributeGroupDTO> attribueGroups = _attributeGroupService.GetAllAttributeGroups(CurrentLanguage);

            product.AttributesGroups = attribueGroups;

            if (product.HasSize)
            {
                product.AllSizeAttributes = _manageSizeAttributesService.GetSizeAttributesBySizeCaategoryId(product.SizeCategoryId.Value, CurrentLanguage);
            }
            Mapper.Initialize(c => c.CreateMap <AddProductDTO, AddProductVM>());
            AddProductVM productVM = Mapper.Map <AddProductDTO, AddProductVM>(product);

            productVM.BaseCategories = _categoryService.GetAllPathsByWebsite(CurrentWebsite, CurrentLanguage);
            return(View(productVM));
        }
Esempio n. 18
0
        public async Task <ServiceResponse <GetProductDTO> > AddProduct(AddProductDTO newProduct, User user)
        {
            var serviceResponse = new ServiceResponse <GetProductDTO>();

            try
            {
                newProduct.UserId = user.Id;
                Product product = _mapper.Map <Product>(newProduct);
                product.Price = product.OriginalPrice;

                await _repository.AddAsync(product);

                serviceResponse.Data = _mapper.Map <GetProductDTO>(await _repository.SingleOrDefaultAsync(x => x.Id == product.Id));
            }
            catch (Exception ex)
            {
                serviceResponse.Success = false;
                serviceResponse.Message = ex.Message;
            }

            return(serviceResponse);
        }
        public ResultDTO AddProduct([FromBody] AddProductDTO model)
        {
            if (!ModelState.IsValid)
            {
                return(new ResultDTO
                {
                    Status = 500,
                    Message = "Error",
                    Errors = CustomValidator.GetErrorsByModel(ModelState)
                });
            }
            else
            {
                var product = new Product()
                {
                    Name                  = model.Name,
                    Price                 = model.Price,
                    Brand                 = model.Brand,
                    Category              = model.Category,
                    Description           = model.Description,
                    MainImage             = model.MainImage,
                    Warranty              = model.Warranty,
                    Payment               = model.Payment,
                    FirstAdditionalImage  = model.FirstAdditionalImage,
                    SecondAdditionalImage = model.SecondAdditionalImage,
                    ThirdAdditionalImage  = model.ThirdAdditionalImage
                };

                _context.products.Add(product);

                _context.SaveChanges();

                return(new ResultDTO
                {
                    Status = 200,
                    Message = "OK"
                });
            }
        }
Esempio n. 20
0
        private static List <AddProductDTO> GenerateTestProducts(int amount)
        {
            Random random = new Random();
            List <AddProductDTO> products = new List <AddProductDTO>();

            for (int i = 0; i < amount; i++)
            {
                string descriptor = Descriptors[random.Next(0, Descriptors.Length)];
                string ability    = Ability[random.Next(0, Ability.Length)];
                string color      = Color[random.Next(0, Color.Length)];
                string items      = Items[random.Next(0, Items.Length)];

                var product = new AddProductDTO()
                {
                    Title       = descriptor + " " + ability + " " + color + " " + items + ".",
                    Description = descriptor + " " + ability + " " + color + " " + items + "."
                };

                products.Add(product);
            }
            return(products);
        }
Esempio n. 21
0
 public void CreateAndUpdateProduct(AddProductDTO dto)
 {
     if (dto.ProductId != 0)
     {
         var product = dBContext.Products.FirstOrDefault(x => x.Id == dto.ProductId);
         if (product != null)
         {
             product.CompanyId     = dto.CompanyId;
             product.SubCategoryId = dto.SubCategoryId;
             product.Description   = dto.Description;
             product.Discount      = dto.Discount;
             product.Price         = dto.Price;
             product.ProductCode   = dto.ProductCode;
             product.ProductName   = dto.ProductName;
             product.ImagePath     = dto.ImagePath;
             product.IsActive      = true;
             dBContext.SaveChanges();
         }
     }
     else
     {
         var product = new Product()
         {
             CompanyId     = dto.CompanyId,
             SubCategoryId = dto.SubCategoryId,
             Description   = dto.Description,
             Discount      = dto.Discount,
             Price         = dto.Price,
             ProductCode   = dto.ProductCode,
             ProductName   = dto.ProductName,
             ImagePath     = dto.ImagePath,
             IsActive      = true
         };
         dBContext.Products.Add(product);
         dBContext.SaveChanges();
     }
 }
        public async Task <ActionResult <AddProductDTO> > Post(AddProductDTO productDTO)
        {
            await service.InsertProduct(productDTO);

            return(Ok(productDTO));
        }
Esempio n. 23
0
 public async Task <IActionResult> AddProduct(AddProductDTO product)
 {
     return(Ok(await _service.AddProduct(product, this.CurrentUser)));
 }
        public JsonResult SaveFiles(string[] description, HttpPostedFileBase files, AddProductDTO addProductDTO)
        {
            #region comment
            string           Message, fileName, actualFileName;
            string           Manufacturer = string.Empty, Model = string.Empty, PartNo = string.Empty, ProductType = string.Empty, Spec = string.Empty, ProductID = string.Empty;
            ProductMasterDTO productMasterDTO = new ProductMasterDTO();
            Message = fileName = actualFileName = string.Empty;
            bool   flag    = false;
            string strpath = System.Configuration.ConfigurationManager.AppSettings["UploadImagePath"];
            int    size    = 0;
            if (Request.Files != null)
            {
                var list = new List <KeyValuePair <string, string> >();

                foreach (string key in System.Web.HttpContext.Current.Request.Form.AllKeys)
                {
                    string value = System.Web.HttpContext.Current.Request.Form[key];

                    list.Add(new KeyValuePair <string, string>(key, value));
                }
                if (Request.Files.Count != 0)
                {
                    var file = Request.Files[0];
                    actualFileName = file.FileName;
                    fileName       = Guid.NewGuid() + Path.GetExtension(file.FileName);
                    size           = file.ContentLength;
                    file.SaveAs(Path.Combine(Server.MapPath(strpath), fileName));
                    MyProject.Controllers.ViewRequestController.UploadedFile f = new MyProject.Controllers.ViewRequestController.UploadedFile
                    {
                        FileName = actualFileName,
                        FilePath = fileName,
                    };
                }

                var custData = new List <CustomerInfo>();
                try
                {
                    if (list.Count > 0 && list != null)
                    {
                        Manufacturer = list.Find(x => x.Key == "Manufacturer").Value.ToString();
                        Model        = list.Find(x => x.Key == "Model").Value.ToString();
                        PartNo       = list.Find(x => x.Key == "PartNo").Value.ToString();
                        ProductType  = list.Find(x => x.Key == "ProductType").Value.ToString();
                        Spec         = list.Find(x => x.Key == "Spec").Value.ToString();
                        ProductID    = list.Find(x => x.Key == "ProductID").Value.ToString();
                        custData     = JsonConvert.DeserializeObject <List <CustomerInfo> >(list.Find(x => x.Key == "custlist").Value.ToString());
                        // var custData1 = list.Find(x => x.Key == "custlist").Value.ToString();
                    }
                    flag = true;

                    if (!string.IsNullOrEmpty(Manufacturer) && Manufacturer != "undefined")
                    {
                        productMasterDTO.ManufacturerId = Convert.ToInt64(Manufacturer);
                    }
                    if (!string.IsNullOrEmpty(ProductType) && ProductType != "undefined")
                    {
                        productMasterDTO.ProductTypeId = Convert.ToInt64(ProductType);
                    }
                    productMasterDTO.IsActive     = true;
                    productMasterDTO.Model        = Model;
                    productMasterDTO.PartNo       = PartNo;
                    productMasterDTO.Spec         = Spec;
                    productMasterDTO.ImageID      = actualFileName;
                    productMasterDTO.ImagePath    = fileName;
                    productMasterDTO.ImageType    = fileName;// Change name
                    productMasterDTO.ImageLength  = size.ToString();
                    productMasterDTO.strProductId = ProductID;
                    var Data = objData.AddUpdateProducts(custData, productMasterDTO);
                    return(new JsonResult {
                        Data = Data
                    });
                }
                catch (Exception ex)
                {
                    Message = "File Upload Failed!";
                    return(new JsonResult {
                        Data = null
                    });
                }
            }

            #endregion

            return(new JsonResult {
                Data = null
            });
        }
Esempio n. 25
0
        public async Task <IActionResult> PostProduct([FromBody] AddProductDTO model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var product = new Product
            {
                Name              = model.Name,
                IsHide            = false,
                AddDate           = model.AddDate,
                CategoryId        = model.CategoryId,
                BrandId           = model.BrandId,
                ProductStatusId   = model.ProductStatusId,
                DisplayPrice      = model.DisplayPrice,
                MaximumQuantity   = model.MaximumQuantity,
                ProductThumbImage = model.ThumbImageId,
                CurrentQuantity   = model.Quantity,
                RealPrice         = model.RealPrice,
                ProductLongDesc   = model.ProductLongDesc,
                ProductShortDesc  = model.ProductShortDesc,
                Weight            = model.Weight,
                Slug              = model.Slug
            };

            _context.Product.Add(product);

            if (await _context.SaveChangesAsync() > 0)
            {
//                product.Slug = "/product" + "/p" + product.ProductId + "/" + product.Slug;
                product.Slug = "/product/" + product.Slug + "-p" + product.ProductId;
                _context.Entry(product).State = EntityState.Modified;

                var productImages = new List <ProductImage>();

                foreach (var imageId in model.ProductImageIds)
                {
                    productImages.Add(new ProductImage
                    {
                        GeneralImageId = imageId,
                        ProductId      = product.ProductId
                    });
                }

                _context.ProductImage.AddRange(productImages);

                var brand = await _context.Brand.FindAsync(product.BrandId);

                brand.TotalProduct++;

                _context.Update(brand);

                var category = await _context.Category.FindAsync(product.CategoryId);

                category.TotalProduct++;

                _context.Update(category);

                if (await _context.SaveChangesAsync() > 0)
                {
                    return(StatusCode(201));
                }
            }


            return(StatusCode(424));
        }
Esempio n. 26
0
        public async Task <IActionResult> AddProduct(AddProductViewModel model)
        {
            if (ModelState.IsValid)
            {
                var sizeThumbnail = model.ThumbImage.Length;
                var sizeImages    = model.ProductImages.Sum(x => x.Length);

                if (sizeThumbnail > 2097152)
                {
                    ModelState.AddModelError("ThumbnailOverLength", "Thumbnail image size is not greater than 2MB");
                    return(View(model));
                }

                if (sizeImages > 5242880)
                {
                    ModelState.AddModelError("ImagesOverLength", "Product images size is not greater than 5MB");
                    return(View(model));
                }

                var thumbImage = await UploadImages(new List <IFormFile>
                {
                    model.ThumbImage
                });

                var productImages = await UploadImages(model.ProductImages);

                var productDto = new AddProductDTO
                {
                    Name             = model.Name,
                    CategoryId       = model.CategoryId,
                    BrandId          = model.BrandId,
                    ProductStatusId  = model.ProductStatusId,
                    DisplayPrice     = model.DisplayPrice,
                    MaximumQuantity  = model.MaximumQuantity,
                    ProductImageIds  = productImages,
                    Quantity         = model.Quantity,
                    RealPrice        = model.RealPrice,
                    ProductLongDesc  = model.ProductLongDesc,
                    ProductShortDesc = model.ProductShortDesc,
                    ThumbImageId     = thumbImage[0],
                    Weight           = model.Weight,
                    Slug             = model.Name.URLFriendly()
                };

                using (var client = _restClient.CreateClient(User))
                {
                    using (
                        var response = await client.PostAsync("/api/product",
                                                              new StringContent(JsonConvert.SerializeObject(productDto), Encoding.UTF8,
                                                                                "application/json")))
                    {
                        if (response.StatusCode == HttpStatusCode.Created)
                        {
                            return(RedirectToAction("Products"));
                        }
                    }
                }
            }

            return(View(model));
        }
Esempio n. 27
0
        public void Add(AddProductDTO productDTO)
        {
            var product = _mapper.Map <Product>(productDTO);

            _productRepository.Add(product);
        }