Beispiel #1
0
        public async Task <ActionResult <CreateCategoryCommandResponse> > Create(
            [FromBody] CreateCategoryCommand createCategoryCommand)
        {
            var response = await _mediator.Send(createCategoryCommand);

            return(Ok(response));
        }
Beispiel #2
0
        public async Task <ActionResult> Post(CreateCategoryCommand category)
        {
            var currentCategories = await this.db
                                    .Categories
                                    .Where(c => c.IsActive)
                                    .ToListAsync();

            var currentCategory = currentCategories
                                  .FirstOrDefault(c =>
                                                  c.Code == category.Code &&
                                                  c.ExternalId == category.ExternalId
                                                  );

            if (currentCategory != null)
            {
                return(this.Conflict($"Категория {category.Name} уже существует!"));
            }

            var addedCategory = await this.db.AddAsync(this.mapper.Map <Category>(category)).ConfigureAwait(false);

            var result = await this.db.SaveChangesAsync().ConfigureAwait(false);

            return(result > 0
                ? this.CreatedAtAction(nameof(this.Get), new { id = addedCategory.Entity.Id },
                                       new { id = addedCategory.Entity.Id })
                : throw new InvalidOperationException("Не удалось добавить категорию!"));
        }
        public async Task CreateCategoryCommandTestAsync(string identityUserId, string title, string titleImagePath, CreateCategoryResponse result)
        {
            CreateCategoryCommand request = new CreateCategoryCommand
            {
                IdentityUserId = identityUserId,
                Title          = title,
                TitleImagePath = titleImagePath,
            };
            CreateCategoryCommandHandler handler = new CreateCategoryCommandHandler(_createFixture.Context);
            var expectedResult = await handler.Handle(request, new CancellationToken());

            Assert.Equal(expectedResult.IsSuccessful, result.IsSuccessful);
            if (expectedResult.IsSuccessful)
            {
                Category category = await _createFixture.Context.Categories
                                    .Include(c => c.Creator)
                                    .Include(c => c.TitleImage)
                                    .Where(c => c.Id == expectedResult.Id)
                                    .SingleOrDefaultAsync();

                Assert.Equal(category.Title, title);
                Assert.Equal(category.TitleImage.Path, titleImagePath);
                Assert.Equal(category.Creator.IdentityUserId, identityUserId);
            }
            Assert.Equal(expectedResult.Message, result.Message);
        }
Beispiel #4
0
        public async Task <ApiResponse <CategoryDto> > CreateCategory(CategoryViewModel categoryViewModel)
        {
            try
            {
                ApiResponse <CategoryDto> apiResponse           = new ApiResponse <CategoryDto>();
                CreateCategoryCommand     createCategoryCommand = _mapper.Map <CreateCategoryCommand>(categoryViewModel);
                var createCategoryCommandResponse = await _client.AddCategoryAsync(createCategoryCommand);

                if (createCategoryCommandResponse.Success)
                {
                    apiResponse.Data    = _mapper.Map <CategoryDto>(createCategoryCommandResponse.Category);
                    apiResponse.Success = true;
                }
                else
                {
                    apiResponse.Data = null;
                    foreach (var error in createCategoryCommandResponse.ValidationErrors)
                    {
                        apiResponse.ValidationErrors += error + Environment.NewLine;
                    }
                }
                return(apiResponse);
            }
            catch (ApiException ex)
            {
                return(ConvertApiExceptions <CategoryDto>(ex));
            }
        }
Beispiel #5
0
        public async Task <BaseApiResponse> Add(AddCategoryRequest request)
        {
            request.CheckNotNull(nameof(request));
            var newcategoryid = GuidUtil.NewSequentialId();
            var command       = new CreateCategoryCommand(
                newcategoryid,
                request.ParentId,
                request.Name,
                request.Url,
                request.Thumb,
                request.Type,
                request.IsShow,
                request.Sort);

            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(), "添加分类", newcategoryid, request.Name);

            return(new BaseApiResponse());
        }
Beispiel #6
0
        public async Task <ValidationResult> Add(CreateCategoryViewModel createCategoryViewModel)
        {
            CreateCategoryCommand createCategoryCommand =
                _mapper.Map <CreateCategoryCommand>(createCategoryViewModel);

            return(await _mediator.Send(createCategoryCommand));
        }
Beispiel #7
0
        public async Task <IActionResult> CreateCategory([FromBody] Category category)
        {
            var command = new CreateCategoryCommand(category);
            var result  = await _mediator.Send(command);

            return(Ok(result));
        }
Beispiel #8
0
        public async Task PostShouldReturn201Response()
        {
            var newCategoryToBar = new CreateCategoryCommand
            {
                Code         = "Код в бар",
                Name         = "Наименование в бар",
                ExternalId   = 12345,
                WorkshopType = WorkshopType.Bar,
            };

            var newCategoryToKitchen = new CreateCategoryCommand
            {
                Code         = "Код на кухню",
                Name         = "Наименование на кухню",
                ExternalId   = 123456,
                WorkshopType = WorkshopType.Kitchen,
            };

            var token = await new AccountControllerTest().Authenticate().ConfigureAwait(false);

            this.httpClient.DefaultRequestHeaders.Authorization = AuthenticationHeaderValue.Parse($"{token.Token_type} {token.Access_token}");

            var response = await this.Create(newCategoryToBar);

            Assert.Equal(HttpStatusCode.Created, response.StatusCode);

            var response2 = await this.Create(newCategoryToKitchen);

            Assert.Equal(HttpStatusCode.Created, response2.StatusCode);

            var response3 = await this.Create(newCategoryToKitchen);

            Assert.Equal(HttpStatusCode.Conflict, response3.StatusCode);
        }
Beispiel #9
0
        public void CreateCategory()
        {
            var inputParameter = new Domain.Category("name", 1, "description");
            var command        = new CreateCategoryCommand {
                Name = inputParameter.Name, SortOrder = inputParameter.SortOrder, Description = inputParameter.Description
            };
            var dto = Substitute.For <ICategoryDto>();

            var datastore = Substitute.For <ICategoryDatastore>();

            datastore.Create(inputParameter).Returns <ICategoryDto>(dto);
            var taskDatastore = Substitute.For <ITaskDatastore>();

            CreateCategoryCommandHandler handler = new CreateCategoryCommandHandler(datastore, taskDatastore);
            GenericValidationCommandHandlerDecorator <CreateCategoryCommand> val =
                new GenericValidationCommandHandlerDecorator <CreateCategoryCommand>(
                    handler,
                    new List <IValidator <NForum.CQS.Commands.Categories.CreateCategoryCommand> > {
                new NForum.CQS.Validators.Categories.CreateCategoryValidator()
            }
                    );

            val.Execute(command);

            datastore.ReceivedWithAnyArgs(1).Create(inputParameter);
        }
 public CategoriesViewModel()
 {
     CreateCategoryCommand = new CreateCategoryCommand(this);
     RemoveCategoryCommand = new RemoveCategoryCommand(this);
     CategoriesList        = System.Threading.Tasks.Task.Run(() => GetCategories()).Result;
     ErrorMessage          = "";
 }
        public async Task <ICommandResult> Handle(CreateCategoryCommand request, CancellationToken cancellationToken)
        {
            request.Validate();

            if (!request.IsValid)
            {
                return(new CommandResult(false, "Problemas ao cadastrar a categoria.", request.Notifications));
            }

            var categoriaExiste = await _categoryRepository.VerifyCategoryAsync(request.Name, request.User);

            if (categoriaExiste)
            {
                return(new CommandResult(false, "A categoria ja esta cadastrada.", null));
            }

            var newCategory = new Category(request.Name, request.User);

            var createdCategory = await _categoryRepository.CreateCategoryAsync(newCategory);

            if (createdCategory == null)
            {
                return(new CommandResult(false, "Problemas ao cadastrar a categoria.", null));
            }

            return(new CommandResult(true, "Categoria Cadastrada com sucesso", createdCategory));
        }
Beispiel #12
0
        /// <summary>
        /// ایجاد یک زیر دسته
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        public async Task <IHttpActionResult> Post(CreateCategoryCommand command)
        {
            var response = await
                           Bus.Send <CreateCategoryCommand, CreateCategoryCommandResponse>(command);

            return(Ok(response));
        }
Beispiel #13
0
        public async Task <IActionResult> Create(CreateCategoryCommand command)
        {
            //var validator = new CreateCategoryValidator();
            //var result = await validator.ValidateAsync(command);

            //if (result.IsValid)
            //{
            //    await Mediatr.Send(command);
            //    return RedirectToAction(actionName: nameof(Index));
            //}
            //var errors = result.Errors.Select(x => x.ErrorMessage).ToArray();

            //ModelState.AddModelError("CategoryName", string.Join(",", errors));

            try
            {
                await Mediatr.Send(command);

                return(RedirectToAction(actionName: nameof(Index)));
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("CategoryName", ex.Message);

                return(View());
            }
        }
Beispiel #14
0
        public ActionResult <long> CreateCategory(CreateCategoryCommand cmd)
        {
            if (cmd == null)
            {
                return(BadRequest("Incorrect command sent"));
            }

            var parentCategory = _db.TestCategories.Find(cmd.ParentCategoryId);

            if (parentCategory == null)
            {
                return(BadRequest($"Parent test category with id={cmd.ParentCategoryId} doesn't exist"));
            }

            var category = new TestCategory()
            {
                Name     = cmd.Name,
                ParentId = cmd.ParentCategoryId
            };

            _db.TestCategories.Add(category);
            _db.SaveChanges();

            return(category.Id);
        }
        public async Task <ActionResult <Category> > CreateCategoryAsync(CreateCategoryCommand createCategoryCommand)
        {
            var category = _mapper.Map <Category>(createCategoryCommand);
            await _behavior.CreateCategoryAsync(category);

            return(category);
        }
Beispiel #16
0
        public async Task <ActionResult <CategoryDto> > Create([FromBody] CreateCategoryCommand command)
        {
            var res = await Mediator.Send(command);

            return(Ok(await Mediator.Send(new GetCategoryDetailQuery {
                Id = res
            })));
        }
Beispiel #17
0
        public async Task <IActionResult> AddCategoryAsync(
            [FromBody] CreateCategoryCommand addCategoryCommand,
            CancellationToken cancellationToken)
        {
            await _categoryHandler.AddCategoryAsync(addCategoryCommand, cancellationToken);

            return(Ok());
        }
Beispiel #18
0
        public async Task <IActionResult> PostCategory(CreateCategoryCommand category)
        {
            string UserId = getUserId();

            category.UserId = UserId;

            return(Ok(await _mediator.Send(category)));
        }
        public async override Task <string> Handle(CreateCategoryCommand request, CancellationToken cancellationToken)
        {
            Entity = mapper.Map <CategoryDto, Category>(request);

            Result = repo.Add(Entity);

            return(Result);
        }
Beispiel #20
0
        public async Task <ActionResult> AddCategory(CategoryDTO category)
        {
            var command = new CreateCategoryCommand(category.Id, category.Title, category.Description);

            await _commandHandler.HandleAsync(command);

            return(Ok());
        }
Beispiel #21
0
        public async Task <Result <CreateCategoryResponse> > Handle(CreateCategoryCommand request, CancellationToken cancellationToken)
        {
            var newCat       = new Category(request.Name, request.Description, request.Slug, request.ParentCategory);
            var createResult = await _repository.AddAsync(newCat, cancellationToken);

            var result = new Result <CreateCategoryResponse>(new CreateCategoryResponse(_mapper.Map <CategoryDto>(createResult)));

            return(result);
        }
        public Category Create(CreateCategoryCommand command)
        {
            var category = new Category(command.Title);

            category.Register();
            _repository.Create(category);

            return(Commit() ? category : null);
        }
        public Task<HttpResponseMessage> Post([FromBody]dynamic body)
        {
            var command = new CreateCategoryCommand(
                title: (string)body.title
            );

            var category = _service.Create(command);
            return CreateResponse(HttpStatusCode.Created, category);
        }
        // 1 The request comes in and and it's sended to validate
        public async Task <int> Create(CreateCategoryCommand command)
        {
            // 2 CreateCategoryCommandValidator Starts
            // 3 LoggingBehaviour Executes
            // 4 ValidationBehaviour Check if errors
            // 5 CreateCategoryCommand Creates entity

            // if error 4.1 ValidationExeption 4.1.1 ApiExectionFilter
            return(await Mediator.Send(command));
        }
Beispiel #25
0
        public async Task <ActionResult <long> > PostCategory(CreateCategoryCommand command)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }
            var response = await mediator.Send(command);

            return(NoContent());
        }
        public Task <HttpResponseMessage> Post([FromBody] dynamic body)
        {
            var command = new CreateCategoryCommand(
                title: (string)body.title
                );

            var category = _service.Create(command);

            return(CreateResponse(HttpStatusCode.Created, category));
        }
        public async Task <IActionResult> Add([FromBody] CreateCategoryCommand createCategory)
        {
            var result = await _mediator.Send(createCategory);

            if (result.Success)
            {
                return(Ok(result.Message));
            }
            return(BadRequest(result.Message));
        }
 public CategoryManager(CommerceCommander commander, GetCategoryCommand getCategoryCommand, CreateCategoryCommand createCategoryCommand, AssociateCategoryToParentCommand associateCategoryToParentCommand, FindEntityCommand findEntityCommand, CreateRelationshipPipeline createRelationshipPipeline, AddEntityVersionCommand addEntityVersionCommand)
 {
     this._commander                        = commander;
     this._getCategoryCommand               = getCategoryCommand;
     this._createCategoryCommand            = createCategoryCommand;
     this._associateCategoryToParentCommand = associateCategoryToParentCommand;
     this._findEntityCommand                = findEntityCommand;
     this._createRelationshipPipeline       = createRelationshipPipeline;
     this._addEntityVersionCommand          = addEntityVersionCommand;
 }
Beispiel #29
0
        private async Task <CategoryViewModel> CreateCategory()
        {
            var name        = Guid.NewGuid().ToString();
            var description = Guid.NewGuid().ToString();
            var command     = new CreateCategoryCommand(name, description);

            var response = await Mediator.Send(command);

            return(response);
        }
        public async Task <IActionResult> Create(CreateCategoryCommand category)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }
            var categoryId = await _mediator.Send(category);

            return(Ok(categoryId));
        }
        public async Task <Guid> Handle(CreateCategoryCommand request, CancellationToken cancellationToken)
        {
            var category = new Category(request.Name, request.Color, request.CreatedBy);

            await _categoriesRepository.Add(category);

            await _categoriesRepository.UnitOfWork.SaveEntitiesAsync();

            return(category.Id);
        }
        public Category Create(CreateCategoryCommand command)
        {
            var category = new Category(command.Title);
            category.Register();

            _repository.Create(category);

            if (Commit())
            {
                return category;
            }

            return null;
        }