Ejemplo n.º 1
0
        public async Task <ActionResult <CityDto> > AddCity([FromBody] CityForCreationDto cityForCreation)
        {
            var validationResults = new CityForCreationDtoValidator().Validate(cityForCreation);

            validationResults.AddToModelState(ModelState, null);

            if (!ModelState.IsValid)
            {
                return(BadRequest(new ValidationProblemDetails(ModelState)));
                //return ValidationProblem();
            }

            var city = _mapper.Map <City>(cityForCreation);
            await _cityRepository.AddCity(city);

            var saveSuccessful = await _cityRepository.SaveAsync();

            if (saveSuccessful)
            {
                var cityFromRepo = await _cityRepository.GetCityAsync(city.CityId);

                var cityDto  = _mapper.Map <CityDto>(cityFromRepo);
                var response = new Response <CityDto>(cityDto);

                return(CreatedAtRoute("GetCity",
                                      new { cityDto.CityId },
                                      response));
            }

            return(StatusCode(500));
        }
Ejemplo n.º 2
0
        public async Task <IActionResult> AddCity([FromBody] CityForCreationDto city)
        {
            if (city == null)
            {
                _logger.LogInformation($"City is null");
                return(BadRequest());
            }

            if (city.Description == city.Name)
            {
                ModelState.AddModelError("Description", "The Provided description should be different from the name");
            }

            var Entity = Mapper.Map <Entities.City>(city);

            var username = User.Identity.Name;

            var user = await _userManager.FindByNameAsync(username);

            Entity.Principal = user;

            _cityInfoRepository.AddCity(Entity);

            if (!_cityInfoRepository.Save())
            {
                return(StatusCode(500, "A problem happened while handling your request"));
            }

            var createdCity = Mapper.Map <CityWithoutPointsOfInterestDto>(Entity);

            return(CreatedAtRoute("GetCity", new { id = createdCity.Id }, createdCity));
        }
Ejemplo n.º 3
0
        public IActionResult CreateCity([FromBody] CityForCreationDto newCity)
        {
            if (newCity.Name == newCity.Description)
            {
                ModelState.AddModelError(
                    "Description",
                    "The provided description should be different than the name"
                    );
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }


            var maxCityId = CitiesDataStore.Current.Cities.Max(c => c.Id);

            var finalCity = new CityDto()
            {
                Id          = ++maxCityId,
                Name        = newCity.Name,
                Description = newCity.Description
            };

            CitiesDataStore.Current.Cities.Add(finalCity);

            return(CreatedAtRoute("GetCity", new { id = finalCity.Id }, finalCity));
        }
Ejemplo n.º 4
0
        public async Task <ActionResult <CityDto> > AddCity(CityForCreationDto cityForCreation)
        {
            var validationResults = new CityForCreationDtoValidator().Validate(cityForCreation);

            validationResults.AddToModelState(ModelState, null);

            if (!ModelState.IsValid)
            {
                return(BadRequest(new ValidationProblemDetails(ModelState)));
                //return ValidationProblem();
            }

            var city = _mapper.Map <City>(cityForCreation);

            _cityRepository.AddCity(city);
            var saveSuccessful = await _cityRepository.SaveAsync();

            if (saveSuccessful)
            {
                var cityDto = await _cityRepository.GetCityAsync(city.CityId); //get from repo for fk object, if needed

                return(CreatedAtRoute("GetCity",
                                      new { cityDto.CityId },
                                      cityDto));
            }

            return(StatusCode(500));
        }
        public ActionResult <City> CreateCity([FromBody] CityForCreationDto cityDto)
        {
            this.citiesInfoService.CreateCity(cityDto);

            return(this.Ok());


            //return this.CreatedAtAction("GetCityById", new { id = city.Id }, city);

            //newly created obj returned in the headers => OK https://localhost:44348/api/citiesInfo/11
        }
Ejemplo n.º 6
0
        public void CreateCity(CityForCreationDto creationDto)
        {
            City city = new City
            {
                Name        = creationDto.Name,
                Description = creationDto.Description
            };

            this.context.Cities.Add(city);
            this.context.SaveChanges();
        }
Ejemplo n.º 7
0
        public async Task <CityForReturnDto> Update(CityForCreationDto updateDto)
        {
            var checkById = await cityDal.GetAsync(x => x.Id == updateDto.Id);

            if (checkById == null)
            {
                throw new RestException(HttpStatusCode.BadRequest, new { NotFound = Messages.NotFound });
            }

            var mapForUpdate = mapper.Map(updateDto, checkById);
            await cityDal.Update(mapForUpdate);

            return(mapper.Map <City, CityForReturnDto>(mapForUpdate));
        }
Ejemplo n.º 8
0
        public async Task AddCity_ShouldBeDoneSuccessfully()
        {
            // Arrange
            var responseMessage    = "City added successfully.";
            var cityForCreationDto = new CityForCreationDto()
            {
                CountryId = 1,
                Name      = "Belgrade"
            };

            var country = new Country()
            {
                Id        = 1,
                Name      = "Serbia",
                Users     = new List <User>(),
                Cities    = new List <City>(),
                Flag      = "Flag",
                Locations = new List <Location>()
            };

            var cityToAdd = new City()
            {
                Country   = country,
                CountryId = country.Id,
                Id        = 1,
                Locations = new List <Location>(),
                Name      = cityForCreationDto.Name,
                Users     = new List <User>(),
            };

            _unitOfWorkMock.Setup(x => x.Countries.GetById(It.IsAny <int>()))
            .ReturnsAsync(country);

            _mapperMock.Setup(x => x.Map <City>(cityForCreationDto))
            .Returns(cityToAdd);

            _unitOfWorkMock.Setup(x => x.Cities.Add(cityToAdd))
            .Verifiable();

            _unitOfWorkMock.Setup(x => x.Complete())
            .ReturnsAsync(true);

            // Act
            var result = await _sut.AddCity(cityForCreationDto);

            // Assert
            Assert.Equal(responseMessage, result.Value);
        }
Ejemplo n.º 9
0
        public async Task <CityForReturnDto> Create(CityForCreationDto createDto)
        {
            var checkByName = await cityDal.GetAsync(x => x.Name.ToLower() == createDto.Name.ToLower());

            if (checkByName != null)
            {
                throw new RestException(HttpStatusCode.BadRequest, new { AlreadyExist = Messages.AlreadyExist });
            }

            var mapForCreate = mapper.Map <City>(createDto);
            var saveToDb     = await cityDal.Add(mapForCreate);

            var mapForReturn = mapper.Map <City, CityForReturnDto>(saveToDb);

            return(mapForReturn);
        }
Ejemplo n.º 10
0
        public IActionResult PostCity([FromBody] CityForCreationDto cityDto)
        {
            if (cityDto == null)
            {
                return(BadRequest());
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            // TODO: saving logic

            return(CreatedAtRoute("GetCity", new { id = 1 }, cityDto));
        }
Ejemplo n.º 11
0
        public IActionResult CreateCity([FromBody] CityForCreationDto city)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var cityToAdd = new CityForCreationDto()
            {
                Description = city.Description,
                Name        = city.Name
            };



            return(NoContent());
        }
Ejemplo n.º 12
0
        public async Task <ActionResult <CityForReturnDto> > Update(CityForCreationDto updateDto)
        {
            var city = await cityService.Update(updateDto);

            var onlineScreens = await onlineScreenService.GetAllOnlineScreenConnectionId();

            if (onlineScreens != null && onlineScreens.Length != 0)
            {
                var foreCastsForKiosks = await wheatherForeCastService.WheatherForeCastsAsync();

                if (foreCastsForKiosks != null)
                {
                    await kiosksHub.Clients.Clients(onlineScreens).SendAsync("ReceiveWheatherForeCast", foreCastsForKiosks);
                }
            }
            return(city);
        }
Ejemplo n.º 13
0
        public async Task AddCity_ShouldNotAdd_WhenCountryIsInvalid()
        {
            // Arrange
            var responseMessage    = "Invalid country selected.";
            var cityForCreationDto = new CityForCreationDto()
            {
                CountryId = 1,
                Name      = "Belgrade"
            };

            _unitOfWorkMock.Setup(x => x.Countries.GetById(It.IsAny <int>()))
            .ReturnsAsync(() => null);

            // Act
            var result = await _sut.AddCity(cityForCreationDto);

            // Assert
            Assert.Equal(responseMessage, result.Value);
        }
Ejemplo n.º 14
0
        public async Task <IActionResult> AddCity([FromBody] CityForCreationDto city, int id)
        {
            if (city == null)
            {
                return(BadRequest());
            }
            var cityToAdd = Mapper.Map <City>(city);
            var country   = await _repository.GetCountry(id);

            if (country == null)
            {
                return(NotFound());
            }
            cityToAdd.CountryId = country.Id;
            _repository.AddCityForCountry(cityToAdd);
            if (!await _repository.Save())
            {
                throw new Exception("Failed");
            }
            return(NoContent());
        }
Ejemplo n.º 15
0
        public async Task <KeyValuePair <bool, string> > AddCity(CityForCreationDto city)
        {
            var country = await _unitOfWork.Countries.GetById(city.CountryId);

            if (country == null)
            {
                return(new KeyValuePair <bool, string>(false, "Invalid country selected."));
            }

            var cityToAdd = _mapper.Map <City>(city);

            cityToAdd.Country = country;
            _unitOfWork.Cities.Add(cityToAdd);

            if (await _unitOfWork.Complete())
            {
                return(new KeyValuePair <bool, string>(true, "City added successfully."));
            }

            return(new KeyValuePair <bool, string>(false, "Problem creating city"));
        }
Ejemplo n.º 16
0
        public IActionResult CreateCity([FromBody] CityForCreationDto city)
        {
            if (city == null)
            {
                return(BadRequest());
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var entity = Mapper.Map <City>(city);

            _dataStorage.Cities.Create(entity);
            _dataStorage.SaveChanges();

            var createdCity = Mapper.Map <CityWithoutPointsOfInterestDto>(entity);

            return(CreatedAtRoute("GetCity", new { id = createdCity.Id }, city));;
        }
Ejemplo n.º 17
0
 public async Task <ActionResult <CityForReturnDto> > Create(CityForCreationDto createDto)
 {
     return(await cityService.Create(createDto));
 }
Ejemplo n.º 18
0
 public async Task <IActionResult> AddCity(CityForCreationDto city)
 {
     return(Ok(await _locationsService.AddCity(city)));
 }
Ejemplo n.º 19
0
        public IActionResult CreateCity([FromBody] CityForCreationDto city)
        {
            //the new city is in the POST body with no id (which is generated by SQL)

            if (city == null)
            {
                return(BadRequest());
            }

            //add custom validation before checking data annotation rules
            if (city.Name == city.Description)
            {
                ModelState.AddModelError("Description", "The provided description must be different than the name.");
            }

            //validate data annotations on the model, returning error messages in the response
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            //begin hardcoded data
            ////create a new city and add it to the collection
            //var maxCityId = CitiesDataStore.Current.Cities.Max(c => c.Id);

            //var cityDto = new CityDto
            //{
            //    Id = ++maxCityId, //make a fake new id
            //    Name = city.Name,
            //    Description = city.Description
            //};

            //CitiesDataStore.Current.Cities.Add(cityDto);
            //end hardcoded data

            //create a new entity
            var cityEntity = new City
            {
                Name        = city.Name,
                Description = city.Description
            };

            //add entity and save to db
            _cityInfoRepository.AddCity(cityEntity);
            if (!_cityInfoRepository.Save())
            {
                return(StatusCode(500, "A problem happened while handling your request."));
            }

            //map entity to dto (method must return a dto, not an entity)
            var cityDto = new CityDto
            {
                Id          = cityEntity.Id, //save populated Id identity property
                Name        = cityEntity.Name,
                Description = cityEntity.Description
            };

            //return a 201
            //named route and parameters to get new City are used to build a url in the Location response header
            //the City just created will be in response body
            return(CreatedAtRoute("GetCity", new { id = cityDto.Id }, cityDto));
        }