Пример #1
0
        public async Task <IHttpActionResult> Post(CreateCityCommand command)
        {
            var response = await
                           Bus.Send <CreateCityCommand, CreateCityCommandResponse>(command);

            return(Ok(response));
        }
Пример #2
0
        public void ShouldRequireMinimumFields()
        {
            var command = new CreateCityCommand();

            FluentActions.Invoking(() =>
                                   SendAsync(command)).Should().Throw <ValidationException>();
        }
Пример #3
0
        public async Task <IActionResult> Create([FromBody] CreateCityCommand command)
        {
            await Mediator.Send(command);


            return(NoContent());
        }
Пример #4
0
        public async Task HandleAsync_Should_Throw_ConflictException_When_Only_PolishName_Is_Already_Used()
        {
            var state = State.Builder()
                        .SetId(Guid.NewGuid())
                        .SetRowVersion(Array.Empty <byte>())
                        .SetName("Name")
                        .SetPolishName("PolishName")
                        .Build();
            var getStateResult = GetResult <State> .Ok(state);

            var command = new CreateCityCommand(Guid.NewGuid(), "Name", "PolishName", Guid.NewGuid());
            var duplicatePolishNameError               = new Error(CityErrorCodeEnumeration.PolishNameAlreadyInUse, CityErrorMessage.PolishNameAlreadyInUse);
            var nameIsNotTakenVerificationResult       = VerificationResult.Ok();
            var polishNameIsNotTakenVerificationResult = VerificationResult.Fail(new Collection <IError> {
                duplicatePolishNameError
            });
            var errors = new Collection <IError> {
                duplicatePolishNameError
            };


            _stateGetterServiceMock.Setup(x => x.GetByIdAsync(It.IsAny <Guid>())).ReturnsAsync(getStateResult);
            _cityVerificationServiceMock.Setup(x => x.VerifyNameIsNotTakenAsync(It.IsAny <string>(), It.IsAny <Guid>()))
            .ReturnsAsync(nameIsNotTakenVerificationResult);
            _cityVerificationServiceMock.Setup(x => x.VerifyPolishNameIsNotTakenAsync(It.IsAny <string>(), It.IsAny <Guid>()))
            .ReturnsAsync(polishNameIsNotTakenVerificationResult);

            Func <Task> result = async() => await _commandHandler.HandleAsync(command);

            var exceptionResult = await result.Should().ThrowExactlyAsync <ConflictException>();

            exceptionResult.And.Errors.Should().BeEquivalentTo(errors);
        }
Пример #5
0
        public async Task HandleAsync_Should_Create_City()
        {
            var state = State.Builder()
                        .SetId(Guid.NewGuid())
                        .SetRowVersion(Array.Empty <byte>())
                        .SetName("Name")
                        .SetPolishName("PolishName")
                        .Build();
            var command = new CreateCityCommand(Guid.NewGuid(), "Name", "PolishName", state.Id);
            var city    = City.Builder()
                          .SetId(command.CityId)
                          .SetRowVersion(Array.Empty <byte>())
                          .SetName(command.Name)
                          .SetPolishName(command.PolishName)
                          .SetStateId(command.StateId)
                          .Build();
            var getStateResult = GetResult <State> .Ok(state);

            var nameIsNotTakenVerificationResult       = VerificationResult.Ok();
            var polishNameIsNotTakenVerificationResult = VerificationResult.Ok();

            _stateGetterServiceMock.Setup(x => x.GetByIdAsync(It.IsAny <Guid>())).ReturnsAsync(getStateResult);
            _cityVerificationServiceMock.Setup(x => x.VerifyNameIsNotTakenAsync(It.IsAny <string>(), It.IsAny <Guid>()))
            .ReturnsAsync(nameIsNotTakenVerificationResult);
            _cityVerificationServiceMock.Setup(x => x.VerifyPolishNameIsNotTakenAsync(It.IsAny <string>(), It.IsAny <Guid>()))
            .ReturnsAsync(polishNameIsNotTakenVerificationResult);
            _mapperMock.Setup(x => x.Map <CreateCityCommand, City>(It.IsAny <CreateCityCommand>())).Returns(city);
            _cityRepositoryMock.Setup(x => x.AddAsync(It.IsAny <City>())).Returns(Task.CompletedTask);

            Func <Task> result = async() => await _commandHandler.HandleAsync(command);

            await result.Should().NotThrowAsync <Exception>();
        }
Пример #6
0
        public async Task CreateCityAsync_Should_Return_CreatedAtRouteResult_With_CityResponse()
        {
            var createCityRequest = new CreateCityRequest {
                Name = "Name", PolishName = "PolishName"
            };
            var createCityCommand = new CreateCityCommand(Guid.NewGuid(), createCityRequest.Name,
                                                          createCityRequest.PolishName, Guid.NewGuid());
            var cityOutputQuery = new CityOutputQuery(createCityCommand.CityId, Array.Empty <byte>(), createCityCommand.Name,
                                                      createCityCommand.PolishName, createCityCommand.StateId);
            var cityResponse = new CityResponse(cityOutputQuery.Id, cityOutputQuery.RowVersion, cityOutputQuery.Name,
                                                cityOutputQuery.PolishName, cityOutputQuery.StateId);

            _mapperMock.Setup(x => x.Map <CreateCityRequest, CreateCityCommand>(It.IsAny <CreateCityRequest>())).Returns(createCityCommand);
            _communicationBusMock.Setup(x => x.SendCommandAsync(It.IsAny <CreateCityCommand>(), It.IsAny <CancellationToken>()))
            .Returns(Task.CompletedTask);
            _getCityQueryHandlerMock
            .Setup(x => x.HandleAsync(It.IsAny <GetCityInputQuery>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(cityOutputQuery);
            _mapperMock.Setup(x => x.Map <CityOutputQuery, CityResponse>(It.IsAny <CityOutputQuery>())).Returns(cityResponse);

            var result = await _controller.CreateCityAsync(createCityRequest);

            var createdAtRouteResult = result.As <CreatedAtRouteResult>();

            createdAtRouteResult.Value.Should().BeEquivalentTo(cityResponse);
            createdAtRouteResult.RouteName.Should().BeEquivalentTo("GetCity");
            createdAtRouteResult.RouteValues.Should().BeEquivalentTo(new RouteValueDictionary(new { id = cityResponse.Id }));
        }
        public async Task CreateCity_ShouldReturnSuccessWithCreatedData()
        {
            var client = _factory.GetClient();

            var token = ApiTokenHelper.GenerateFakeToken();

            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");

            var command = new CreateCityCommand
            {
                Name      = "Venice",
                CountryId = Guid.Parse("{3ae4e108-e2df-4893-958a-2d76ab89b9dc}")
            };

            var content  = Utilities.GetRequestContent(command);
            var response = await client.PostAsync($"/cities", content);

            response.EnsureSuccessStatusCode();

            var result = await Utilities.GetResponseContent <Application.Features.Cities.Commands.CreateCity.CityDto>(response);

            result.Should().BeOfType(typeof(Application.Features.Cities.Commands.CreateCity.CityDto));
            result.Should().NotBeNull();
            response.StatusCode.Should().Be(HttpStatusCode.Created);
            response.Headers.Location.LocalPath.Should().Be($"/Cities/{result.CityId}");
        }
Пример #8
0
        public async Task CreateCity(Guid cityId, CreateCityCommand createCityCommand)
        {
            var document = new Document <CityDocument>
            {
                Id      = cityId.ToString(),
                Content = new CityDocument
                {
                    Name     = createCityCommand.Name,
                    City     = createCityCommand.City,
                    Country  = createCityCommand.Country,
                    Location = new CityLocationDocument
                    {
                        Lat = createCityCommand.Latitude,
                        Lon = createCityCommand.Longitude
                    }
                }
            };

            var documentResult = await _citiesBucket.InsertAsync(document);

            if (!documentResult.Success)
            {
                throw documentResult.Exception;
            }
        }
        public City Create(CreateCityCommand command)
        {
            var city = new City(command.Title, command.IsActved);

            city.Register();
            _repository.Create(city);

            if (Commit())
            {
                return(city);
            }

            return(null);
        }
        public async Task ShouldCreateCity()
        {
            var command = new CreateCityCommand
            {
                Name = "Kastamonu"
            };

            var result = await SendAsync(command);

            var list = await FindAsync <City>(result.Data.Id);

            list.Should().NotBeNull();
            list.Name.Should().Be(command.Name);
            list.CreateDate.Should().BeCloseTo(DateTime.Now, 10000);
        }
        public async Task CreateCity_ShouldReturnUnauthorized()
        {
            var client = _factory.GetClient();

            var command = new CreateCityCommand
            {
                Name      = "Venice",
                CountryId = Guid.Parse("{3ae4e108-e2df-4893-958a-2d76ab89b9dc}")
            };

            var content  = Utilities.GetRequestContent(command);
            var response = await client.PostAsync($"/cities", content);

            response.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
        }
Пример #12
0
        public async Task ShouldRequireUniqueName()
        {
            await SendAsync(new CreateCityCommand
            {
                Name = "Bursa"
            });

            var command = new CreateCityCommand
            {
                Name = "Bursa"
            };

            FluentActions.Invoking(() =>
                                   SendAsync(command)).Should().Throw <ValidationException>();
        }
        public async Task ShouldCreateCity()
        {
            var userId = await RunAsDefaultUserAsync();

            var command = new CreateCityCommand
            {
                Name = "İzmir"
            };

            var result = await SendAsync(command);

            var list = await FindAsync <City>(result.Data.Id);

            list.Should().NotBeNull();
            list.Name.Should().Be(command.Name);
            list.Creator.Should().Be(userId);
            list.CreateDate.Should().BeCloseTo(DateTime.Now, 10000);
        }
Пример #14
0
        public async Task HandleAsync_Should_Throw_ValidationException_When_State_Is_Not_Found()
        {
            var stateId = Guid.NewGuid();
            var command = new CreateCityCommand(Guid.NewGuid(), "Name", "PolishName", stateId);
            var errors  = new Collection <IError>
            {
                new Error(StateErrorCodeEnumeration.NotFound, StateErrorMessage.NotFound)
            };
            var getStateResult = GetResult <State> .Fail(errors);

            _stateGetterServiceMock.Setup(x => x.GetByIdAsync(It.IsAny <Guid>())).ReturnsAsync(getStateResult);

            Func <Task> result = async() => await _commandHandler.HandleAsync(command);

            var exceptionResult = await result.Should().ThrowExactlyAsync <ValidationException>();

            exceptionResult.And.Errors.Should().BeEquivalentTo(errors);
        }
Пример #15
0
        public async Task <CreateResultViewModel <City> > Handle(CreateCityCommand request, CancellationToken cancellationToken)
        {
            var city = _mapper.Map <City>(request.Model);

            #if NET5_0_OR_GREATER
            await using var unitOfWork = _unitOfWorkFactory.Create();
            #else
            using var unitOfWork = _unitOfWorkFactory.Create();
            #endif
            City newCity = await unitOfWork.Add(city, cancellationToken);

            // ConfigureAwait is necessary here because of possible mix of async/await and task.Wait/task.Result
            // without the configure await it would expect to return to this thread and potentially deadlock if
            // another task was using the original thread (and worse yet if that thread was waiting on the this
            // await to complete
            await unitOfWork.Commit(cancellationToken).ConfigureAwait(false);

            return(new CreateResultViewModel <City>(newCity.Id));
        }
        public async Task <CreateCityCommandResponse> Handle(CreateCityCommand command)
        {
            var province = _provinceRepository.AsQuery().SingleOrDefault(p => p.Id == command.ProvinceId);

            if (province == null)
            {
                throw new DomainException("استان یافت نشد");
            }

            var isExist = await _cityRepository.AsQuery().AnyAsync(item => item.Code == command.Code);

            if (isExist)
            {
                throw new DomainException("شهر با این کد قبلا ثبت شده است");
            }
            var city = new City(Guid.NewGuid(), command.Code, command.CityName, province);

            _cityRepository.Add(city);
            return(new CreateCityCommandResponse());
        }
Пример #17
0
 public async Task <ActionResult <CreateCityOutputModel> > CreateCity(
     CreateCityCommand command)
 => await this.Send(command);
Пример #18
0
 public async Task <ActionResult <City> > Post(CreateCityCommand command)
 {
     return(await Mediator.Send(command));
 }
Пример #19
0
 public async Task <City> Post([FromBody] CreateCityCommand cmd)
 {
     return(await _meditor.Send(cmd));
 }
Пример #20
0
 public async Task <Result <int> > Post([FromBody] CreateCityCommand createCityCommand)
 {
     return(await _citiesApplication.Create(createCityCommand));
 }
Пример #21
0
        public async Task <IActionResult> CreateCity([FromBody] CreateCityCommand command)
        {
            var result = await Mediator.Send(command);

            return(Ok(new { result }));
        }
Пример #22
0
 public CreateCityCommandValidatorTests()
 {
     this.createValidator = new CreateCityCommandValidator();
     this.createCommand   = new CreateCityCommand();
 }
Пример #23
0
 public async Task <ActionResult <ServiceResult <CityDto> > > Create(CreateCityCommand command)
 {
     return(Ok(await Mediator.Send(command)));
 }
        public async Task <ActionResult <CityDto> > CreateCity([FromBody] CreateCityCommand createCityCommand)
        {
            var cityDto = await _mediator.Send(createCityCommand);

            return(CreatedAtAction(nameof(GetCityDetails), new { id = cityDto.CityId }, cityDto));
        }