Exemple #1
0
        public ActionResult UpdateCategory([FromForm] CategoryUpdateDTO categoryUpdateDTO, int id)
        {
            var categoryRepo = _repo.GetCategoryById(id);

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

            // SUBE UNA SOLA IMAGEN A UN CAMPO DE TIPO Byte[] en una tabla
            if (categoryUpdateDTO.Files.FileName != null)
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    categoryUpdateDTO.Files.OpenReadStream().CopyTo(ms);
                    // return arreglo de bytes
                    categoryUpdateDTO.Picture = ms.ToArray();
                }
            }

            _mapper.Map(categoryUpdateDTO, categoryRepo);

            _repo.UpdateCategory(categoryRepo);

            _repo.SaveChanges();

            return(NoContent());
        }
Exemple #2
0
        public async Task <IActionResult> Update(int id, CategoryUpdateDTO categoryUpdateDTO)
        {
            if (id != categoryUpdateDTO.Id)
            {
                return(BadRequest("Invalid ID"));
            }
            await _categoryService.UpdateAsync(_mapper.Map <Category>(categoryUpdateDTO));

            return(NoContent());
        }
        public async Task <ActionResult <CategoryDTO> > Put(int id, [FromBody] CategoryUpdateDTO categoryUpdateDTO)
        {
            var categoryDTO = await _categoryService.UpdateAsync(id, categoryUpdateDTO);

            if (categoryDTO is null)
            {
                return(NotFound());
            }

            return(categoryDTO);
        }
Exemple #4
0
        public async Task <IActionResult> UpdateCategory(int id, CategoryUpdateDTO categoryUpdate)
        {
            var categoryFromReop = await _repo.GetCategory(id);

            _mapper.Map(categoryUpdate, categoryFromReop);
            if (await _repo.SaveAll())
            {
                var categoryToReturn = _mapper.Map <CategoryReturnDTO>(categoryFromReop);
                return(CreatedAtRoute("GetCategory", new { id = categoryFromReop.CategoryId }, categoryToReturn));
            }
            throw new Exception($"حدثت مشكلة في تعديل بيانات القسم  {id}");
        }
Exemple #5
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            CategoryUpdateDTO categoryDTO = new CategoryUpdateDTO();

            categoryDTO.id          = Convert.ToInt32(no);
            categoryDTO.name        = NazivKategorije.Text;
            categoryDTO.description = OpisKategorije.Text;
            var convertedModel = JsonConvert.SerializeObject(categoryDTO);

            //CreateProductAsync(userAccessModel);
            new HttpClient().PostAsync("http://localhost:9388/updatecategory", new StringContent(convertedModel, Encoding.UTF8, "application/json"));
        }
        public async Task <ActionResult> updateCategory(int categoryId, [FromBody] CategoryUpdateDTO updateObject)
        {
            var result = await _repository.UpdateCategory(categoryId, updateObject);

            if (result == ReqResult.NotFound)
            {
                return(NotFound());
            }
            else
            {
                return(Ok("Category updated"));
            }
        }
        public IActionResult Update(CategoryUpdateDTO category)
        {
            var cat = _repository.GetById(category.Id);

            cat.Name         = category.Name;
            cat.ModifiedDate = DateTime.Now;
            cat.UserId       = _userContext.UserId;
            int result = _repository.Update(cat);

            if (result > 0)
            {
                return(Ok());
            }
            else
            {
                throw new Exception();
            }
        }
Exemple #8
0
        public async Task <ReqResult> UpdateCategory(int ID, CategoryUpdateDTO updateDto)
        {
            var target = await _context.Categories
                         .FirstOrDefaultAsync(category => category.category_id == ID);

            if (target == null)
            {
                return(ReqResult.NotFound);
            }

            // TODO: This code is horrendous. Is there a better way?
            if (updateDto.name != null)
            {
                target.name = updateDto.name;
            }
            if (updateDto.parent_id != null)
            {
                target.parent_id = updateDto.parent_id;
            }
            if (updateDto.is_active != null)
            {
                if (target.parent_id == null && updateDto.is_active == false)
                {
                    var childrenToDeactivate = await _context.Categories
                                               .Where(category => category.parent_id == target.category_id)
                                               .ToListAsync <Category>();

                    foreach (var child in childrenToDeactivate)
                    {
                        child.is_active = false;
                    }
                    target.is_active = false;
                    await _context.SaveChangesAsync();
                }
                else
                {
                    target.is_active = (bool)updateDto.is_active;
                }
            }

            await _context.SaveChangesAsync();

            return(ReqResult.Success);
        }
Exemple #9
0
        public async Task <IDataResult <CategoryDTO> > UpdateAsync(CategoryUpdateDTO categoryUpdateDTO, string modifiedByName)
        {
            var oldCategory = await _unitOfWork.Categories.GetAsync(c => c.Id == categoryUpdateDTO.Id);

            var category = _mapper.Map <CategoryUpdateDTO, Category>(categoryUpdateDTO, oldCategory);

            category.ModifiedByName = modifiedByName;

            var updatedCategory = await _unitOfWork.Categories.UpdateAsync(category);

            await _unitOfWork.SaveAsync();

            return(new DataResult <CategoryDTO>(ResultStatus.Success, Messages.Category.Update(categoryUpdateDTO.Name), new CategoryDTO
            {
                Category = updatedCategory,
                ResultStatus = ResultStatus.Success,
                Message = Messages.Category.Update(categoryUpdateDTO.Name)
            }));
        }
        public async Task <IActionResult> Update(int id, [FromBody] CategoryUpdateDTO categoryDTO)
        {
            try
            {
                _logger.LogInfo($"Category Update attempted - id: {id}");
                if (string.IsNullOrWhiteSpace(id.ToString()) || categoryDTO == null ||
                    id != categoryDTO.Id)
                {
                    _logger.LogWarn($"Empty Request was submitted.");
                    return(BadRequest());
                }

                var isExists = await _categoryRepository.IsExists(id);

                if (!isExists)
                {
                    _logger.LogWarn($"Category Update failed: no Category with id: {id} was found.");
                    return(NotFound());
                }

                if (!ModelState.IsValid)
                {
                    _logger.LogWarn($"Category Data was Invalid.");
                    return(BadRequest(ModelState));
                }
                var category  = _mapper.Map <Category>(categoryDTO);
                var isSuccess = await _categoryRepository.Update(category);

                if (!isSuccess)
                {
                    return(InternalError($"Update Operation failed."));
                }

                return(NoContent());
            }
            catch (Exception e)
            {
                return(InternalError($"{e.Message} - {e.InnerException}"));
            }
        }
Exemple #11
0
        public async Task <IActionResult> Update(int id, [FromBody] CategoryUpdateDTO categoryDTO)
        {
            var location = GetControllerActionName();

            try
            {
                logger.LogInfo($"{location}: Update Category with id {id}");
                if (id < 1 || categoryDTO == null || id != categoryDTO.Id)
                {
                    logger.LogWarn($"{location}: Update Category with id {id} failed with bad data");
                    return(BadRequest());
                }
                var isExists = await categoryRepository.IsExists(id);

                if (!isExists)
                {
                    logger.LogWarn($"{location}: Category with id {id} not found");
                    return(NotFound());
                }
                if (!ModelState.IsValid)
                {
                    logger.LogWarn($"{location}: Category object is incomplete");
                    return(BadRequest(ModelState));
                }
                var category  = mapper.Map <Category>(categoryDTO);
                var isSuccess = await categoryRepository.Update(category);

                if (!isSuccess)
                {
                    return(InternalError($"{location}: Update Category with id {id} failed"));
                }
                logger.LogInfo($"{location}: Update Category with id {id} successful");
                return(NoContent());
            }
            catch (Exception e)
            {
                return(InternalError($"{location}: {e.Message} - {e.InnerException}"));
            }
        }
Exemple #12
0
        public ActionResult UpdateCategory([FromBody] CategoryUpdateDTO category)
        {
            string[]    lines       = System.IO.File.ReadAllLines(@"auth.txt");
            var         accessToken = lines[0]; //Settings.Default["accessToken"].ToString();//HttpContext.Session.GetString("accessToken");
            var         serverUrl   = lines[1];
            CategoryDTO categoryDTO = new CategoryDTO();

            categoryDTO.name        = category.name;
            categoryDTO.description = category.description;
            CategoryPostDTO categoryPostDTO = new CategoryPostDTO();

            categoryPostDTO.category = categoryDTO;
            var nopApiClient   = new ApiClient(accessToken, serverUrl);
            var convertedModel = JsonConvert.SerializeObject(categoryPostDTO,
                                                             Formatting.None,
                                                             new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore
            });
            string jsonUrl      = String.Format("/api/categories/{0}", category.id);
            object productsData = nopApiClient.Put(jsonUrl, convertedModel);

            return(Ok());
        }
Exemple #13
0
        public IActionResult Put(int id, [FromBody] CategoryUpdateDTO category)
        {
            if (category == null)
            {
                return(BadRequest(new ErrorViewModel
                {
                    ErrorCode = "400",
                    ErrorMessage = "Thông tin cung cấp không chính xác."
                }));
            }

            if (!ModelState.IsValid)
            {
                var errorViewModel = new ErrorViewModel
                {
                    ErrorCode    = "400",
                    ErrorMessage = ModelState.ToErrorMessages()
                };

                return(BadRequest(errorViewModel));
            }

            var categoryToUpdate = this._categoryRepository.GetById(id);

            if (categoryToUpdate == null)
            {
                return(NotFound(new ErrorViewModel
                {
                    ErrorCode = "404",
                    ErrorMessage = "Loại sản phẩm cần cập nhật không tìm thấy"
                }));
            }

            bool isExisting = this._categoryRepository.CheckExistingCategory(id, category.Name);

            if (isExisting)
            {
                return(BadRequest(new ErrorViewModel
                {
                    ErrorCode = "400",
                    ErrorMessage = "Tên loại sản phẩm này đã tồn tại."
                }));
            }

            categoryToUpdate.Name        = category.Name;
            categoryToUpdate.UpdatedBy   = "admin";
            categoryToUpdate.UpdatedDate = DateTime.Now;

            bool isSuccess = this._categoryRepository.Update(categoryToUpdate);

            if (isSuccess == false)
            {
                return(StatusCode(500, new ErrorViewModel
                {
                    ErrorCode = "500",
                    ErrorMessage = "Có lỗi trong quá trình cập nhật dữ liệu."
                }));
            }

            return(Ok(categoryToUpdate));
        }
 public async Task <CategoryDTO> UpdateAsync(int id, CategoryUpdateDTO categoryUpdateDTO)
 {
     return(await _httpService.PutHelperAsync <CategoryUpdateDTO, CategoryDTO>($"{CategoryClientEndpoints.Base}/{id}", categoryUpdateDTO));
 }