public async Task <IActionResult> PostProduct(Product model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    int pid = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);
                    model.ProviderId = pid;

                    var ProdId = await ProductsRepository.Add(model);

                    if (ProdId == true)
                    {
                        return(Ok(ProdId));
                    }
                    else
                    {
                        return(NotFound());
                    }
                }
                catch (Exception)
                {
                    return(BadRequest());
                }
            }

            return(BadRequest());
        }
        public void Handle(AddProductCommand command)
        {
            if (!command.IsValid())
            {
                RaiseValidationErrors(command);
                return;
            }

            var product = Product.Create(
                command.CategoryId,
                command.ProductName,
                command.Description,
                command.Price,
                command.ImageUrl
                );

            if (product.CategoryId.HasValue)
            {
                var categoryProduct = CategoryProduct.Create(
                    product.Id,
                    product.CategoryId.Value,
                    product
                    );
                categoriesRepository.AddCategoryProduct(categoryProduct);
            }

            productsRepository.Add(product);
        }
Beispiel #3
0
        public CreatedProductDTO Create(
            string name,
            string description,
            string accessories,
            string brand,
            string model,
            string voltage,
            string frequency,
            double pricePerDay,
            int rentingPeriodLimit
            )
        {
            var product = new Product(
                name,
                description,
                accessories,
                brand,
                model,
                voltage,
                frequency,
                pricePerDay,
                rentingPeriodLimit
                );
            var ProductValidation = product.Validate();

            if (ProductValidation.isValid)
            {
                _productsRepository.Add(product);
                return(new CreatedProductDTO(product.Id));
            }
            return(new CreatedProductDTO(ProductValidation.errors));
        }
Beispiel #4
0
        public async Task <IActionResult> NewProduct(ProductModel productModel)
        {
            bool saved = false;

            try
            {
                productModel.Tags = productModel.Tags.Distinct().ToArray();
                Product pe = _mapper.Map <Product>(productModel);
                _productsRepo.FillTags(pe);
                _productsRepo.Add(pe);
                saved = await _productsRepo.SaveAllAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
            }

            if (saved)
            {
                this.AddInformationMessage($"Product {productModel.Name} saved successfully");
                return(RedirectToAction("Status"));
            }
            else
            {
                this.AddErrorMessage($"Unable to save product {productModel.Name}");
                LoadExistingTags();
                return(View(productModel));
            }
        }
        public async Task <IActionResult> Create([FromBody] ProductDTO productDTO)
        {
            var systemOfMeasurement = await _productsRepository.AssignMeasurementUnitToMeasurementSystem(productDTO.UnitOfMeasurement);

            var product = Product.Create(
                productDTO.Name,
                productDTO.Brand,
                productDTO.Quantity,
                productDTO.UnitOfMeasurement,
                systemOfMeasurement);
            await _productsRepository.Add(product);

            foreach (var price in productDTO.Prices)
            {
                var store = await _storesRepository.GetByName(price.StoreName);

                var productStore = ProductStore.Create(
                    product.Id,
                    store.FirstOrDefault().Id,
                    price.Price);
                await _productStoresRepository.Add(productStore);
            }

            return(Ok(product));
        }
        public int Add(ProductDTO product)
        {
            this.AddCommonProcess(product);
            var productModel = this._mapper.Map <Product>(product);

            return(_productsRepository.Add(productModel));
        }
 public ActionResult Add(ProductVM model)
 {
     try
     {
         var modelAdd = model.search.GetEntity();
         var msgValid = ValidateModel(modelAdd);
         if (string.IsNullOrEmpty(msgValid))
         {
             var obj = _userRepository.Add(modelAdd);
             if (obj)
             {
                 return(Json(new { status = true }));
             }
             else
             {
                 return(Json(new { status = false, msg = "Thêm thất bại" }));
             }
         }
         else
         {
             return(Json(new { status = false, msg = msgValid }));
         }
     }
     catch (Exception ex)
     {
         // chuyển sang page ERR
         return(RedirectToAction("Index", "Error"));
     }
 }
Beispiel #8
0
        public Result Handle(AddProductCommand command)
        {
            if (command.ExpirationDate < SystemTime.Now)
            {
                return(Result.Failure("Expiration date should be greater than current date."));
            }

            if (string.IsNullOrWhiteSpace(command.Name))
            {
                return(Result.Failure("Product name can not be empty."));
            }

            if (command.MaxDaysAfterOpening < 0)
            {
                return(Result.Failure("Max days after opening should be greater than zero."));
            }

            var product = new Product
            {
                Id                  = Guid.NewGuid(),
                Name                = command.Name,
                ExpirationDate      = command.ExpirationDate,
                MaxDaysAfterOpening = command.MaxDaysAfterOpening
            };

            _productsRepository.Add(product);

            return(Result.Success());
        }
        public async Task <IActionResult> AddProduct(Product newProduct)
        {
            newProduct.Price = Math.Round(newProduct.Price, 2);

            await _cosmeticProductsRepository.Add(newProduct);

            return(RedirectToAction("ViewProducts", "Products"));
        }
        private void PopularInMemoryProductsMocked()
        {
            var productsTxt = File.ReadAllText("products.json");
            var products    = JsonConvert.DeserializeObject <List <Product> >(productsTxt);

            _productsMocked.AddRange(products);

            foreach (var product in _productsMocked)
            {
                if (_productRepository.GetProductById(product.ProductId) == null)
                {
                    _productRepository.Add(product);
                }
            }

            _logService.SendMessagesAsync($"InitializeIngredients PopularInMemoryProductsMocked");
        }
Beispiel #11
0
 public async Task <int> Add(Product request)
 {
     if (request == null)
     {
         throw new ArgumentNullException(nameof(request));
     }
     _repository.Add(request);
     return(await _uow.SaveAsync());
 }
Beispiel #12
0
        public async Task <Product> Add(Product product)
        {
            if (string.IsNullOrEmpty(product.Name))
            {
                return(null);
            }

            return(await _repository.Add(product));
        }
Beispiel #13
0
        public IActionResult Create(Products products)
        {
            if (ModelState.IsValid)
            {
                Products newProduct = _productsRepository.Add(products);
                return(RedirectToAction("details", new { id = newProduct.Id }));
            }

            return(View());
        }
        public async Task <IActionResult> Post([FromBody] NewProductRequest request)
        {
            var product = Product.Create(request.SKU, request.DisplayName, request.UnitPrice, request.Description);

            _repository.Add(product);

            await _repository.UnitOfWork.SaveChangesAsync();

            return(Ok(product));
        }
Beispiel #15
0
        public ApiResponse <int> Put([FromBody] ApiProduct product)
        {
            if (!ModelState.IsValid)
            {
                return(ModelState.ToApiResponse <int>());
            }

            var id = _repo.Add(product);

            return(new ApiResponse <int>(id));
        }
Beispiel #16
0
        public IActionResult Create([FromBody] Product product)
        {
            if (product == null || product.UserName != User.Identity.Name)
            {
                return(BadRequest());
            }

            _ProductsRepository.Add(product);

            return(CreatedAtRoute("GetProduct", new { id = product.Id }, product));
        }
        public async Task <IActionResult> Create([Bind("name,price,Id,AddedDate,ModifiedDate,IPAddress")] Product product)
        {
            if (ModelState.IsValid)
            {
                _repoProduct.Add(product);
                await _repoProduct.SaveAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(product));
        }
Beispiel #18
0
        public async Task <IActionResult> Create([Bind("ID,Name,Brand,Price,Thumbnail")] Product product)
        {
            setCartItemCount();
            if (ModelState.IsValid)
            {
                _productsRepository.Add(product);
                await _productsRepository.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(product));
        }
Beispiel #19
0
        public ProductModel Add(ProductEntity entity)
        {
            var product = _repository.Add(entity);

            return(new ProductModel
            {
                Id = product.Id,
                Name = product.Name,
                Price = product.Price,
                TypeEntityId = product.TypeEntityId,
                Volume = product.Volume
            });
        }
Beispiel #20
0
        public async Task <IActionResult> Post([FromBody] NewProductDto newProduct)
        {
            var productToAdd = _mapper.Map <Product>(newProduct);

            _productsRepo.Add(productToAdd);

            if (await _productsRepo.SaveAll())
            {
                return(CreatedAtRoute("GetProduct", new { id = productToAdd.Id }, productToAdd));
            }

            throw new Exception("Creating the product failed on save.");
        }
Beispiel #21
0
        public void AddProduct(ProductDTO productDTO)
        {
            if (_categoryRepository.GetCategoryByName(productDTO.Category.Name) == null ||
                _categoryRepository.GetCategoryById(productDTO.Category.Id) == null)
            {
                throw new ValidationException("Product's category doesn't exist.");
            }


            Product product = _mapper.Map <Product>(productDTO);

            _productRepository.Add(product);
        }
        public void AddProduct(Products New_data)
        {
            List <Products> data = new List <Products>();

            data = _productsRepository.GetProducts(); // fetch the entire database
            int Total = data.Where(x => x.AvailableDate == New_data.AvailableDate).Count();
            int flag  = 0;
            int count = 0;

            if (Total < 15)
            {
                foreach (var Element in data)
                {
                    if (Element.Name == New_data.Name && Element.AvailableDate == New_data.AvailableDate)
                    {
                        break;
                        // " with same name already exist for the date";
                    }

                    else
                    {
                        flag = 1;
                    }
                }
            }
            if (flag == 1)
            {
                if (New_data.IsSpecial == true)
                {
                    foreach (var Element in data)
                    {
                        if (Element.AvailableDate == New_data.AvailableDate)
                        {
                            if (Element.IsSpecial == true)
                            {
                                count++;
                            }
                        }
                    }
                    if (count < 4)
                    {
                    }
                }
                else
                {
                    _productsRepository.Add(New_data);
                }
            }
        }
Beispiel #23
0
        // POST api/Products
        public IHttpActionResult Post([FromBody] Product value)
        {
            try
            {
                _db.Add(value);
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(nameof(Product), ex.Message);

                return(BadRequest(ModelState));
            }

            return(Ok());
        }
Beispiel #24
0
        private async Task AddOrUpdateProduct(CatalogDto.ProductDto dto)
        {
            var product = await _repository.FindBySkuAsync(dto.SKU);

            if (product != null)
            {
                product.Update(dto.DisplayName, dto.UnitPrice);
            }
            else
            {
                _repository.Add(Product.Create(dto.SKU, dto.DisplayName, dto.UnitPrice));
            }

            await _repository.UnitOfWork.SaveChangesAsync();
        }
Beispiel #25
0
        public async Task <ProductDto> CreateAsync(ProductCreateForm form)
        {
            var productForCreation = new Products
            {
                Title = form.Title
            };

            var result = await _productsRepository.Add(productForCreation);

            //await _productsRepository.Save();

            var mapperdProduct = _mapper.Map <ProductDto>(result);

            return(mapperdProduct);
        }
Beispiel #26
0
        public void HandleProductUpdate(UpdateProductCommand command, IProductsRepository productsRepository)
        {
            Console.WriteLine($"CommandsHandlers: Update product command is executed!");
            var product = productsRepository.Get(command.ProductId);

            if (product == null)
            {
                productsRepository.Add(new Product(command.ProductId, command.Name, command.BestBefore));
            }
            else
            {
                product.Name       = command.Name;
                product.BestBefore = command.BestBefore;
            }
        }
Beispiel #27
0
        public bool AddProduct(ProductBusiness productBusiness)
        {
            var product = new Product()
            {
                Name        = productBusiness.Name,
                Description = productBusiness.Description,
                Brand       = productBusiness.Brand,
                ImageName   = productBusiness.ImageName,
                Category    = productBusiness.Category,
                Price       = productBusiness.Price,
                Stock       = productBusiness.Stock
            };

            return(_productRepository.Add(product));
        }
Beispiel #28
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            //загрузка нового фото на сервер
            if (Photo != null)
            {
                if (!_fileRepository.CheckMIMEType(Photo)) //проверка типа файла
                {
                    TempData["MIMETypeError"] = "Разрешены только файлы с типом .jpg .jpeg .png .gif";
                    return(Page());
                }
                Products.Profile.ImagesName = await _fileRepository.UploadFile(Photo, "Products"); //загрузка файл на сервер и запись имени файла
            }

            //загрузка галереи
            if (Gallery_img.Count != 0)
            {
                foreach (var item in Gallery_img) //проверка типа файла
                {
                    if (!_fileRepository.CheckMIMEType(item))
                    {
                        TempData["MIMETypeErrorGal"] = "Разрешены только файлы с типом .jpg .jpeg .png .gif";
                        return(Page());
                    }
                }
                Products.Images = new List <ProductImages>();
                foreach (var item in Gallery_img) //Добавление записей в модель
                {
                    string imageName = await _fileRepository.UploadFile(item, "Products", "Gallery");

                    ProductImages productImages = new ProductImages()
                    {
                        ProductsId = Products.Id,
                        ImageName  = imageName
                    };
                    Products.Images.Add(productImages);
                }
            }

            Products = await _db.Add(Products); //создаем запись

            TempData["SuccessMessage"] = $"Запись \"{Products.Name}\" успешно создана";
            return(RedirectToPage("./Index"));
        }
        public IActionResult Create([FromBody] CreateProductInputModel input)
        {
            var product = new Product
            {
                Name          = input.Name,
                Price         = input.Price,
                Type          = (ProductType)Enum.Parse(typeof(ProductType), input.Type),
                ProductOffers = new List <ProductOffer>(),
                Duration      = input.Duration
            };

            _repository.Add(product);
            _repository.SaveChanges();

            return(Ok(product.Id));
        }
        public void AddProduct(ProductDto product)
        {
            var productEntity = new Products
            {
                AvailableDate = product.AvailableDate,
                IsSpecial     = product.IsSpecial,
                IsVeg         = product.IsVeg,
                Kcal          = product.Kcal,
                Name          = product.Name,
                Price         = product.Price,
                Quantity      = product.Quantity,
                WeightInGrams = product.WeightInGrams
            };

            _productsRepository.Add(productEntity);
        }