Пример #1
0
        public async Task <ActionResult> Update([FromBody] UpdateCategoryRequest request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState.GetErrorResponse()));
                }

                var response = await _service.UpdateAsync(request);

                if (!response.Success)
                {
                    return(BadRequest(response.Erros));
                }

                return(Ok());
            }
            catch (ArgumentNullException ex)
            {
                return(NotFound("Category does not exist"));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex));
            }
        }
Пример #2
0
        public ApiResponse <UpdateCategoryRequest, bool> Put([FromBody] UpdateCategoryRequest request)
        {
            var validate = _updateCategoryValidations.Validate(request);

            if (!validate.IsValid)
            {
                Log.Error(validate.ToString(""));

                return(new ApiResponse <UpdateCategoryRequest, bool>()
                {
                    status = false,
                    error_code = "validations_error",
                    error_message = validate.ToString("~"),
                    request = request
                });
            }

            var response = _repository.Update(request);

            Log.Information("Category updated...");

            return(new ApiResponse <UpdateCategoryRequest, bool>()
            {
                status = true,
                request = request,
                response = response
            });
        }
Пример #3
0
        public async Task <UpdateCategoryResponse> UpdateAsync(int id, UpdateCategoryRequest request)
        {
            try
            {
                var exist = await _unitOfWork.CategoryRepository.FirstOfDefaultAsync(s => s.Id == id);

                if (exist == null)
                {
                    throw new Exception("Data not found");
                }
                exist.Name = request.CategoryName;
                _unitOfWork.CategoryRepository.Update(exist);
                if (await _unitOfWork.CommitAsync())
                {
                    return(new UpdateCategoryResponse
                    {
                        CategoryId = exist.Id,
                        CategoryName = exist.Name
                    });
                }

                throw new Exception("Data invalid");
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Пример #4
0
        public async Task <ActionResult> Edit(Guid id, EditCategoryViewModel request)
        {
            if (!ModelState.IsValid)
            {
                Alert("Invalid Request", NotificationType.error, Int32.Parse(_appConfig.Value.NotificationDisplayTime));
                return(View());
            }
            if (!id.Equals(request.Id))
            {
                Alert("Invalid Request", NotificationType.error, Int32.Parse(_appConfig.Value.NotificationDisplayTime));
                return(View());
            }
            try
            {
                var categoryUpdateRequest = new UpdateCategoryRequest {
                    Id = request.Id, Name = request.Name, Description = request.Description
                };
                var result = await _categoryService.Update(id, categoryUpdateRequest);

                if (!result.Success)
                {
                    Alert($"Error: {result.Message}", NotificationType.error, Int32.Parse(_appConfig.Value.NotificationDisplayTime));
                    return(View());
                }

                Alert($"Category Updated Successfully", NotificationType.success, Int32.Parse(_appConfig.Value.NotificationDisplayTime));
                return(RedirectToAction(nameof(Index)));
            }
            catch
            {
                Alert($"Error Occurred While processing the request", NotificationType.error, Int32.Parse(_appConfig.Value.NotificationDisplayTime));
                return(View());
            }
        }
Пример #5
0
        public ResponseMessage UpdateCategory(UpdateCategoryRequest request)
        {
            var response = new CreateCategoryRequest();

            try
            {
                var category = _context.Category.FirstOrDefault(x => x.Id == request.Id);

                if (category == null)
                {
                    response.Errors.Add("The category is null");
                }
                else
                {
                    category.Name = request.Name;
                    _context.SaveChanges();
                }
                if (!response.IsOk)
                {
                    return(response);
                }
            }
            catch (Exception msg)
            {
                response.Errors.Add(msg.Message);
            }
            if (!response.IsOk)
            {
                return(response);
            }

            return(response);
        }
Пример #6
0
        public async Task <BaseApiResponse> Update(UpdateCategoryRequest request)
        {
            request.CheckNotNull(nameof(request));
            var command = new UpdateCategoryCommand(
                request.Name,
                request.Url,
                request.Thumb,
                request.Type,
                request.IsShow,
                request.Sort)
            {
                AggregateRootId = request.Id
            };
            var result = await ExecuteCommandAsync(command);

            if (!result.IsSuccess())
            {
                return(new BaseApiResponse {
                    Code = 400, Message = "命令没有执行成功:{0}".FormatWith(result.GetErrorMessage())
                });
            }
            //添加操作记录
            var currentAdmin = _contextService.GetCurrentAdmin(HttpContext.Current);

            RecordOperat(currentAdmin.AdminId.ToGuid(), "编辑分类", request.Id, request.Name);
            return(new BaseApiResponse());
        }
        public async Task <IActionResult> UpdateCategory(long category, [FromForm] UpdateCategoryRequest request)
        {
            var command =
                new UpdateCategoryCommand(request.Name, request.NameEng, category, request.ImageUrl);

            return(await HandleActionResultFor(command));
        }
Пример #8
0
        /// <summary>
        /// 修改媒体资源分类
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public UpdateCategoryResponse UpdateMediaCategory(UpdateCategoryRequest input)
        {
            var client = InitVodClient();
            var model  = client.GetAcsResponse(input);

            return(model);
        }
Пример #9
0
        public async Task <IActionResult> UpdateCategoryAsync(int id, UpdateCategoryRequest request)
        {
            CategoryFullResponce result;

            try
            {
                result = await m_categoriesAPIService.UpdateCategoryAsync(id, request);
            }
            catch (NotFoundException)
            {
                return(NotFound());
            }
            catch (CategoryNameAlreadyExistException)
            {
                ModelState.AddModelError(nameof(request.Name), "A category with the same name already exists");
                return(ValidationProblem());
            }
            catch (ParentNodeNotFoundException)
            {
                ModelState.AddModelError(nameof(request.ParentId), "Сategory node with this id does not exist");
                return(ValidationProblem());
            }

            return(Ok(result));
        }
Пример #10
0
        public void Inventory_Category_UpdateCategory_ShouldGetException_WithDuplicateName()
        {
            try
            {
                string otherName        = "Name" + Guid.NewGuid();
                string otherDescription = "Other description";
                CreateCategoryRequest  createCategoryRequest = new CreateCategoryRequest(otherName, otherDescription);
                ICategoryService       service       = IoC.Container.Resolve <ICategoryService>();
                CreateCategoryResponse otherCategory = service.Create(createCategoryRequest);

                UpdateCategoryRequest updateCategoryRequest = new UpdateCategoryRequest()
                {
                    Id          = otherCategory.Id,
                    Name        = this.category.Name,
                    Description = "Description of category updated"
                };

                this.UpdateCategory(updateCategoryRequest);
                Assert.IsTrue(false);
            }
            catch (ValidationException exception)
            {
                Assert.IsTrue(exception.HasExceptionKey("inventory.addOrUpdateCategory.validation.nameAlreadyExisted"));
            }
        }
Пример #11
0
        public UpdateCategoryResponse UpdateCategory(UpdateCategoryRequest request)
        {
            UpdateCategoryResponse res = new UpdateCategoryResponse();
            string strSP = SqlCommandStore.uspUpdateCategory;

            try
            {
                using (SqlCommand cmd = new SqlCommand(strSP))
                {
                    cmd.Parameters.Add("CategoryID", SqlDbType.BigInt).Value          = request.CategoryID;
                    cmd.Parameters.Add("CategoryName", SqlDbType.NVarChar, 100).Value = request.CategoryName;

                    cmd.Parameters.Add("@Return", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;

                    DataSet ds = DB.ExecuteSPDataSet(cmd);
                    res.Code = (ReturnCode)Convert.ToInt32(cmd.Parameters["@Return"].Value);

                    if (res.Code != ReturnCode.Success)
                    {
                        DB.RollBackTran();
                        return(res);
                    }
                    DB.CommitTran();
                    return(res);
                }
            }
            catch (Exception ex)
            {
                LogWriter.WriteLogException(ex);
                res.Code = ReturnCode.Success;
                return(res);
            }
        }
Пример #12
0
        public async Task <CategoryFullResponce> UpdateCategoryAsync(int id, UpdateCategoryRequest request)
        {
            if (!m_authService.IsAuthUser())
            {
                throw new AuthenticationException();
            }
            if (!m_authService.AuthUserInRole(Roles.AdminRoleName))
            {
                throw new UserNotAdminException();
            }

            var updatedCategoryDb = await m_db.Categories.FirstOrDefaultAsync(x => x.Id == id);

            if (updatedCategoryDb is null)
            {
                throw new NotFoundException();
            }
            if (m_db.Categories.Where(x => x.Id != updatedCategoryDb.Id).Any(x => x.Name == request.Name))
            {
                throw new CategoryNameAlreadyExistException();
            }
            if (request.ParentId != null)
            {
                if (m_db.NodeCategories.All(x => x.Id != request.ParentId))
                {
                    throw new ParentNodeNotFoundException();
                }
            }

            m_mapper.Map(request, updatedCategoryDb);

            await m_db.SaveChangesAsync();

            return(m_mapper.Map <CategoryFullResponce>(updatedCategoryDb));
        }
Пример #13
0
        public async Task <UpdateCategoryResult> UpdateCategoryFromRequestAsync(
            [FromBody] UpdateCategoryRequest request, CancellationToken cancellationToken = default(CancellationToken))
        {
            AutoResetEvent       resetEvent = new AutoResetEvent(false);
            UpdateCategoryResult result     = null;

            _domainEvents.Register("UpdateCategoryFromRequestAsync", (UpdateCategoryEvent e) =>
            {
                result = new UpdateCategoryResult(request.RequestId, e);

                if (result.IsSuccessful)
                {
                    resetEvent.Set();
                }
            });

            var command = request.GetCommand();

            await _categoryCommandHandler.ExecuteAsync(command, cancellationToken);

            resetEvent.WaitOne(10000);

            _domainEvents.Unregister("UpdateCategoryFromRequestAsync");

            return(result);
        }
Пример #14
0
        public async Task <IActionResult> Update([FromRoute] Int32 catgId, [FromBody] UpdateCategoryRequest CategoryRequst)
        {
            var category = new Category
            {
                Id          = catgId,
                ArabicName  = CategoryRequst.ArabicName,
                EnglishName = CategoryRequst.EnglishName,
                ImageUrl    = CategoryRequst.ImageUrl,
                Status      = CategoryRequst.Status
            };

            var status = await _CategoryService.UpdateCategoryAsync(category);

            if (status == -1)
            {
                return(Conflict(new ErrorResponse
                {
                    message = "Dublicate Entry",
                    status = Conflict().StatusCode
                }));
            }

            if (status == 1)
            {
                return(Ok(category));
            }
            return(NotFound(new ErrorResponse
            {
                message = "Not Found",
                status = NotFound().StatusCode
            }));
        }
Пример #15
0
        public IHttpActionResult UpdateCategory(UpdateCategoryRequest request)
        {
            var command = _mapper.Map <UpdateCategoryCommand>(request);

            _commandBus.Send(command);

            return(Ok());
        }
Пример #16
0
        public IActionResult UpdateCategory([FromBody] UpdateCategoryRequest request)
        {
            if (request == null)
            {
                return(BadRequest(new ErrorViewModel
                {
                    ErrorCode = "400",
                    ErrorMessage = "Please provide input information correctly."
                }));
            }

            if (request.CategoryId <= 0)
            {
                return(BadRequest(new ErrorViewModel
                {
                    ErrorCode = "400",
                    ErrorMessage = "Category not found"
                }));
            }

            var category = _categoryRepository.FindById(request.CategoryId);

            if (category == null)
            {
                return(BadRequest(new ErrorViewModel
                {
                    ErrorCode = "400",
                    ErrorMessage = "Category not found"
                }));
            }

            var categoryParent = _categoryRepository.FindById(request.ParentId.GetValueOrDefault());

            if (request.ParentId != null)
            {
                if (categoryParent == null)
                {
                    return(BadRequest(new ErrorViewModel
                    {
                        ErrorCode = "400",
                        ErrorMessage = "Parent Category not found"
                    }));
                }
            }

            category.ParentId = request.ParentId;
            category.Name     = request.CategoryName;
            category.Slug     = request.Slug;

            var response = _categoryServices.UpdateCategory(category);

            if (response != "OK")
            {
                return(BadRequest("Can not execute. Plz contact admin"));
            }
            return(Ok(response));
        }
Пример #17
0
        public static Category ConvertToCategory(this UpdateCategoryRequest updateRequest)
        {
            Category category = new Category();

            category.CategoryId = updateRequest.CategoryId;
            category.Name       = updateRequest.Name;

            return(category);
        }
Пример #18
0
        public async Task <IActionResult> UpdateCategory([FromBody] UpdateCategoryRequest request)
        {
            var success = await _categoryBusiness.UpdateAsync(TinyMapper.Map <CategoryInfo>(request));

            if (success)
            {
                return(Ok());
            }
            return(BadRequest());
        }
Пример #19
0
        public async Task <IActionResult> Update([FromBody] UpdateCategoryRequest request)
        {
            var result = await _categoryService.Update(request);

            if (!result.IsSuccess)
            {
                return(BadRequest(result));
            }
            return(Ok(result));
        }
        public async Task <ActionResult> Update([FromBody] UpdateCategoryRequest request, string id)
        {
            var item = _mapper.Map <Category> (request);

            item.SetId(id);
            _entityRepository.Edit(item);
            await _unitOfWork.CompleteAsync();

            return(NoContent());
        }
Пример #21
0
        public async Task <IActionResult> UpdateProductCategory(string id, [FromBody] UpdateCategoryRequest updateRequest)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            await _service.UpdateCategory(id, updateRequest);

            return(NoContent());
        }
Пример #22
0
        public async Task <IActionResult> UpdateCategoryAsync([FromRoute] Guid id, [FromBody] UpdateCategoryRequest brand)
        {
            var obj = await _categoryService.GetCategoryByIdAsync(id);

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

            return(Accepted(await _categoryService.UpdateCategoryAsync(id, brand)));
        }
Пример #23
0
        public ActionResult Edit(CategoryViewModel categoryVM)
        {
            if (categoryVM.PictureSelector.ImageFile == null && categoryVM.PictureSelector.PictureId == null)
            {
                this.ModelState.AddModelError(nameof(categoryVM.PictureSelector), ValidationMessages.Required);
            }

            if (this.ModelState.IsValid == false)
            {
                return(this.View(categoryVM));
            }

            CreatePictureResponse pictureResponse = null;

            if (categoryVM.PictureSelector.ImageFile != null)
            {
                string categoriesImagesPath = WebConfigurationManager.AppSettings[Constants.CategoriesImagesPath_ConfigKey];
                string serverPath           = this.Server.MapPath(categoriesImagesPath);

                var pictureRequest = new CreatePictureRequest
                {
                    ContentType   = categoryVM.PictureSelector.ImageFile.ContentType,
                    FileExtention = Path.GetExtension(categoryVM.PictureSelector.ImageFile.FileName),
                    InputStream   = categoryVM.PictureSelector.ImageFile.InputStream,
                    ServerPath    = serverPath,
                    UrlPath       = categoriesImagesPath,
                };

                pictureResponse = this.pictureService.Create(pictureRequest);

                if (pictureResponse.Result != CreatePictureResult.Success)
                {
                    this.ModelState.AddModelError(nameof(categoryVM.PictureSelector.ImageFile), pictureResponse.Message);
                    return(this.View(categoryVM));
                }
            }

            var updateRequest = new UpdateCategoryRequest()
            {
                Id           = categoryVM.Id,
                Name         = categoryVM.Name,
                DisplayOrder = categoryVM.Order,
                IsPrimary    = categoryVM.IsPrimary,
                Visible      = categoryVM.Visible,
                PictureId    = pictureResponse?.Picture.Id,
            };

            updateRequest.SelectedCategoriesIds = categoryVM.Subcategories.ListItems
                                                  .Where(x => x.Checked)
                                                  .Select(x => int.Parse(x.Id));

            this.categoryService.Update(updateRequest);
            return(this.RedirectToAction("Index"));
        }
Пример #24
0
        public async Task <IActionResult> Update(Guid id, [FromBody] UpdateCategoryRequest updateCategoryRequest)
        {
            var result = await _categoryService.Update(id, updateCategoryRequest);

            if (!result.Success)
            {
                return(BadRequest(result.Messages));
            }

            return(NoContent());
        }
        public async Task UpdateVodCategory(VodCategoryEditDto input)
        {
            await Task.Yield();

            var updto = new UpdateCategoryRequest {
                CateId = input.CateId, CateName = input.CateName
            };


            var res = _aliyunVodManager.UpdateMediaCategory(updto);
        }
Пример #26
0
        public IHttpActionResult PutCategory(EditCategoryModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var categoryService = new CategoryService();
                    var category        = categoryService.GetCategoryById(new GetCategoryByIdRequest()
                    {
                        Id = model.Id
                    }).Category;

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

                    if (model.IdUpperCategory.HasValue)
                    {
                        // Controla que exista la categoría padre.
                        var upperCategory = categoryService.GetCategoryById(new GetCategoryByIdRequest()
                        {
                            Id = model.IdUpperCategory.Value
                        }).Category;
                        if ((upperCategory == null) || (model.Id == model.IdUpperCategory))
                        {
                            return(BadRequest("Invalid upper category"));
                        }
                    }

                    var request = new UpdateCategoryRequest
                    {
                        Id              = model.Id,
                        Title           = model.Title,
                        Summary         = model.Summary,
                        Description     = model.Description,
                        IdUpperCategory = model.IdUpperCategory
                    };

                    var result = categoryService.UpdateCategory(request);

                    return(Ok());
                }
                catch (Exception)
                {
                    return(BadRequest());
                }
            }
            else
            {
                return(BadRequest(ModelState));
            }
        }
Пример #27
0
        public async Task <UpdateCategoryResponse> UpdateAsync(UpdateCategoryRequest request)
        {
            var command  = request.ProjectedAs <UpdateCategoryCommand>();
            var response = await _mediator.Send(command);

            if (response.IsSuccess)
            {
                _uow.Commit();
            }

            return(response.ProjectedAs <UpdateCategoryResponse>());
        }
        /// <summary>
        /// Update a category, changing the description, portals it's visible on or the name
        /// </summary>
        ///
        /// <param name="categoryId">
        /// The unique identifier of the category to update.
        /// </param>
        ///
        /// <param name="request">
        /// The object defining what updates we want to make.
        /// </param>
        ///
        /// <param name="cancellationToken"></param>
        ///
        /// <returns>The contents of the category after the update</returns>
        public async Task <Category> UpdateCategoryAsync(
            long categoryId,
            UpdateCategoryRequest request,
            CancellationToken cancellationToken = default)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request), "The request must not be null");
            }

            return(await _freshdeskClient.ApiOperationAsync <Category>(HttpMethod.Put, $"/api/v2/solutions/categories/{categoryId}", request, cancellationToken : cancellationToken));
        }
Пример #29
0
        public async Task UpdateCategory(UpdateCategoryRequest request)
        {
            var category = await DbContext.Categories.FirstOrDefaultAsync(c => c.Id == request.Id);

            if (category == null)
            {
                throw new EntityNotFoundException <Category>();
            }

            category.Name = request.Name;

            await DbContext.SaveChangesAsync();
        }
 public void Update(UpdateCategoryRequest updateCategoryRequest)
 {
     this.ValiateUpdateCategoryRequest(updateCategoryRequest);
     using (IUnitOfWork uow = new UnitOfWork(RepositoryType.MSSQL))
     {
         ICategoryRepository categoryRepository = IoC.Container.Resolve <ICategoryRepository>(uow);
         Category            category           = categoryRepository.GetById(updateCategoryRequest.Id.ToString());
         category.Name        = updateCategoryRequest.Name;
         category.Description = updateCategoryRequest.Description;
         categoryRepository.Update(category);
         uow.Commit();
     }
 }