示例#1
0
        public async Task <ProductEntity> PutProductAsync(PutProductRequest request)
        {
            var product = await _db.Products.Where(p => p.Id == request.Id).FirstOrDefaultAsync();

            product = _mapper.Map <ProductEntity>(request);
            await _db.SaveChangesAsync();

            return(product);
        }
示例#2
0
        public async Task <IActionResult> Put([FromBody] PutProductRequest product)
        {
            var response = await _putProduct.PutProductDb(product);

            if (!response.Success)
            {
                return(BadRequest());
            }
            return(Ok(response));
        }
示例#3
0
        public async Task <PutProductResponse> PutProductDb(PutProductRequest request)
        {
            var product = await _repository.PutProductAsync(request);

            if (product != null)
            {
                return(new PutProductResponse(true, product.Id));
            }
            return(new PutProductResponse(false, 0));
        }
 public Product ToEntity(int id, PutProductRequest request)
 {
     return(new Product()
     {
         ProductID = id,
         Code = request.Code,
         Name = request.Name,
         StockCount = request.StockCount,
         TaxRate = request.TaxRate,
         UnitPrice = request.UnitPrice
     });
 }
示例#5
0
        public ActionResult <ProductResponse> PutProduct(Guid id, PutProductRequest entity)
        {
            if (id != entity.Id)
            {
                return(BadRequest());
            }

            try
            {
                Product res = new ProductAdapter(_loggerFactory, _context).update(id, ProductConverter.getObjectEntity(entity));
                return(new OkObjectResult(ProductConverter.getObjectEntity(res)));
            }
            catch (DomainException)
            {
                return(NoContent());
            }
        }
示例#6
0
        public static Product getObjectEntity(PutProductRequest entity)
        {
            if (entity == null)
            {
                return(new Product());
            }

            return(new Product
            {
                Id = entity.Id,
                Code = entity.Code,
                Name = entity.Name,
                Price = entity.Price,
                Status = entity.Status,
                LastModified = DateTime.Now
            });
        }
        public async Task <IActionResult> PutProductAsync(int id, [FromBody] PutProductRequest request)
        {
            ProductMapper mapper = new ProductMapper();

            this._logger?.LogDebug("'{0}' has been invoked", nameof(PutProductAsync));
            var existingResource = this._productService.RetrieveProductById(id).Result;

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

            var resourceToBeUpdated = mapper.ToEntity(id, request);

            var updatedResource = this._productService.Update(id, resourceToBeUpdated).Result;

            return(this.Ok(updatedResource));
        }
        public void CreateInstanceAndAssignDataExpectSuccess()
        {
            var putProductRequest = new PutProductRequest();

            Assert.NotNull(putProductRequest);

            putProductRequest.Name           = "Name";
            putProductRequest.Description    = "Description";
            putProductRequest.Company        = "Company";
            putProductRequest.Price          = 1;
            putProductRequest.AgeRestriction = 1;

            Assert.Equal("Name", putProductRequest.Name);
            Assert.Equal("Description", putProductRequest.Description);
            Assert.Equal("Company", putProductRequest.Company);
            Assert.Equal(1, putProductRequest.Price);
            Assert.Equal(1, putProductRequest.AgeRestriction);
        }
        public void ValidatePostProductRequestIncorrectNameExpectFailure()
        {
            var putProductRequest = new PutProductRequest();

            Assert.NotNull(putProductRequest);

            putProductRequest.Name           = "This is a product with a very long name which will make the model to break.";
            putProductRequest.Description    = "Description";
            putProductRequest.Company        = "Company";
            putProductRequest.Price          = 1;
            putProductRequest.AgeRestriction = 1;

            var  validationResults = new List <ValidationResult>();
            bool isValid           =
                Validator.TryValidateObject(putProductRequest, new ValidationContext(putProductRequest),
                                            validationResults, true);

            Assert.False(isValid, "The PutProductRequest instance passed the validations.");
            Assert.True(validationResults.Count == 1, "The validation results are not equal to one.");
            Assert.Equal("The product name must be of 50 characters at maximum.",
                         validationResults[0].ErrorMessage);
        }
        public void ValidatePostProductRequestIncorrectPriceRangeExpectFailure()
        {
            var putProductRequest = new PutProductRequest();

            Assert.NotNull(putProductRequest);

            putProductRequest.Name           = "Barby";
            putProductRequest.Description    = "Description";
            putProductRequest.Company        = "Mattel";
            putProductRequest.Price          = 1001;
            putProductRequest.AgeRestriction = 1;

            var  validationResults = new List <ValidationResult>();
            bool isValid           =
                Validator.TryValidateObject(putProductRequest, new ValidationContext(putProductRequest),
                                            validationResults, true);

            Assert.False(isValid, "The PutProductRequest instance passed the validations.");
            Assert.True(validationResults.Count == 1, "The validation results are not equal to one.");
            Assert.Equal("Price must be between $1 and $1000",
                         validationResults[0].ErrorMessage);
        }
示例#11
0
        public async Task <IActionResult> PutProductAsync(int id, [FromBody] PutProductRequest request)
        {
            Logger?.LogDebug("'{0}' has been invoked", nameof(PutProductAsync));

            var response = new Response();

            try
            {
                // Get stock item by id
                var entity = await DbContext.GetProductAsync(new Product(id));

                // Validate if entity exists
                if (entity == null)
                {
                    return(NotFound());
                }

                // Set changes to entity
                entity.productName = request.productName;
                entity.categoryId  = request.categoryId;
                entity.image       = request.image;
                entity.price       = request.price;

                // Update entity in repository
                DbContext.Update(entity);

                // Save entity in database
                await DbContext.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                response.DidError     = true;
                response.ErrorMessage = "There was an internal error, please contact to technical support.";

                Logger?.LogCritical("There was an error on '{0}' invocation: {1}", nameof(PutProductAsync), ex);
            }

            return(response.ToHttpResponse());
        }
        public void ValidatePostProductRequestIncorrectDescriptionLengthExpectFailure()
        {
            var putProductRequest = new PutProductRequest();

            Assert.NotNull(putProductRequest);

            putProductRequest.Name        = "Barby";
            putProductRequest.Description =
                "He my polite be object oh change. Consider no mr am overcame yourself throwing sociable children. Hastily her totally conduct may. My solid by stuff first smile fanny. Humoured how advanced mrs elegance sir who. Home sons when them dine do want to";
            putProductRequest.Company        = "Company";
            putProductRequest.Price          = 1;
            putProductRequest.AgeRestriction = 1;

            var  validationResults = new List <ValidationResult>();
            bool isValid           =
                Validator.TryValidateObject(putProductRequest, new ValidationContext(putProductRequest),
                                            validationResults, true);

            Assert.False(isValid, "The PutProductRequest instance passed the validations.");
            Assert.True(validationResults.Count == 1, "The validation results are not equal to one.");
            Assert.Equal("The product description must be of 100 characters at maximum.",
                         validationResults[0].ErrorMessage);
        }
        public void ValidatePostProductRequestIncorrectCompanyLengthExpectFailure()
        {
            var putProductRequest = new PutProductRequest();

            Assert.NotNull(putProductRequest);

            putProductRequest.Name        = "Barby";
            putProductRequest.Description = "Description";
            putProductRequest.Company     =
                "Prevailed sincerity behaviour to so do principle mr. As departure at no propriety zealously my. On dear rent if girl view. ";
            putProductRequest.Price          = 1;
            putProductRequest.AgeRestriction = 1;

            var  validationResults = new List <ValidationResult>();
            bool isValid           =
                Validator.TryValidateObject(putProductRequest, new ValidationContext(putProductRequest),
                                            validationResults, true);

            Assert.False(isValid, "The PutProductRequest instance passed the validations.");
            Assert.True(validationResults.Count == 1, "The validation results are not equal to one.");
            Assert.Equal("The product company must be of 50 characters at maximum.",
                         validationResults[0].ErrorMessage);
        }
        async void PutProductExpectSuccess()
        {
            var request = new PutProductRequest()
            {
                Name           = "A test product",
                Description    = "Description",
                Company        = "Company",
                Price          = 10,
                AgeRestriction = 1
            };

            var buffer      = System.Text.Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(request));
            var byteContent = new ByteArrayContent(buffer);

            byteContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

            var response = await _client
                           .PutAsync("/products/b06494b7-01b6-49b9-a6db-e32d64e4420c", byteContent);

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            string responseContent = await response.Content.ReadAsStringAsync();

            Assert.NotEmpty(responseContent);

            BaseResponse <Product> createdProductResponse =
                JsonConvert.DeserializeObject <BaseResponse <Product> >(responseContent);

            Assert.NotNull(createdProductResponse);
            Assert.Equal(1, createdProductResponse.Count);

            var updateProduct = createdProductResponse.Data.SingleOrDefault();

            Assert.NotNull(updateProduct);
            Assert.Equal("A test product", updateProduct.Name);
            Assert.NotEmpty(updateProduct.ProductId.ToString());
        }
        public void CreateNewInstanceExpectSuccess()
        {
            var putProductRequest = new PutProductRequest();

            Assert.NotNull(putProductRequest);
        }
        public IActionResult Put([FromBody] PutProductRequest newProductData, string productId)
        {
            try
            {
                bool commitRequired = false;

                if (!Guid.TryParse(productId, out var parsedProductId))
                {
                    throw new BadRequestException($"The product id {productId} cannot be parsed correctly.");
                }

                Product existingProduct = _unitOfWork.Products
                                          .Get(product => product.ProductId == parsedProductId)
                                          .SingleOrDefault();

                if (existingProduct == null)
                {
                    throw new EntityNotFoundException($"The productId {productId} does not exist in the database.");
                }

                if (!string.IsNullOrEmpty(newProductData.Name) && newProductData.Name != existingProduct.Name)
                {
                    existingProduct.Name = newProductData.Name;
                    commitRequired       = true;
                }

                if (!string.IsNullOrEmpty(newProductData.Description) &&
                    newProductData.Description != existingProduct.Description)
                {
                    existingProduct.Description = newProductData.Description;
                    commitRequired = true;
                }

                if (newProductData.AgeRestriction != null &&
                    newProductData.AgeRestriction != existingProduct.AgeRestriction)
                {
                    existingProduct.AgeRestriction = newProductData.AgeRestriction;
                    commitRequired = true;
                }

                if (!string.IsNullOrEmpty(newProductData.Company) && newProductData.Company != existingProduct.Company)
                {
                    existingProduct.Company = newProductData.Company;
                    commitRequired          = true;
                }

                if (newProductData.Price != null && !newProductData.Price.Equals(existingProduct.Price))
                {
                    existingProduct.Price = newProductData.Price;
                    commitRequired        = true;
                }

                if (commitRequired)
                {
                    _unitOfWork.Products.Update(existingProduct);
                    _unitOfWork.Commit();
                }

                return(new OkObjectResult(new BaseResponse <Product>
                {
                    Data = new List <Product> {
                        existingProduct
                    }
                }));
            }
            catch (Exception e)
            {
                _logger.LogCritical("Exception while processing request to add new product.");
                _logger.LogCritical($"Exception message: {e.Message}");

                throw;
            }
            finally
            {
                _logger.LogDebug("The request for the products resource has been finished.");
            }
        }