コード例 #1
0
        public IActionResult CreatePointOfInterest(int cityId, [FromBody] PointOfInterestForCreationDTO pointOfInterest)
        {
            if (pointOfInterest.Name == pointOfInterest.Description)
            {
                ModelState.AddModelError(
                    "Description",
                    "The provided description should be different than the name"
                    );
            }

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

            var city = CitiesDataStore.Current.Cities.FirstOrDefault(c => c.Id == cityId);

            if (city == null)
            {
                return(NotFound());
            }
            var maxPoiId = CitiesDataStore.Current.Cities.SelectMany(c => c.PointsOfInterest).Max(p => p.Id);

            var finalPoi = new PointOfInterestDto()
            {
                Id          = ++maxPoiId,
                Name        = pointOfInterest.Name,
                Description = pointOfInterest.Description
            };

            city.PointsOfInterest.Add(finalPoi);

            return(CreatedAtRoute("GetPointOfInterest", new { cityId, id = finalPoi.Id }, finalPoi));
        }
コード例 #2
0
        // an important note, the parameter placeholder in the HttpGet route defined above needs to match exactly with the parameter name defined in
        // actual method signature.
        public IActionResult GetPointOfInterest(int cityId, int id)
        {
            if (!_cityInfoRepository.CityExists(cityId))
            {
                _logger.LogInformation($"City with id {cityId} wasnt found when accessing points of interest.");
                return(NotFound());
            }

            PointOfInterestDto poi = _cityInfoRepository.GetPointOfInterestForCity(cityId, id);

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

            //PointOfInterestDto result = new PointOfInterestDto()
            //{
            //    Id = poi.Id,
            //    Name = poi.Name,
            //    Description = poi.Description
            //};

            var result = Mapper.Map <PointOfInterestDto>(poi);

            return(Ok(result));
        }
コード例 #3
0
        public IActionResult UpdatePointOfInterest(int cityId, int id, [FromBody] PointOfInterestDto pointOfInterest)
        {
            if (pointOfInterest == null)
            {
                return(BadRequest());
            }

            var city = CitiesDataStore.Current.Cities.FirstOrDefault(c => c.Id == cityId);

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

            var updatePointOfInterest = city.PointsOfInterest.FirstOrDefault(p => p.Id == id);

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

            updatePointOfInterest.Name        = pointOfInterest.Name;
            updatePointOfInterest.Description = pointOfInterest.Description;

            return(NoContent());
        }
コード例 #4
0
        public IActionResult DeletePointOfInterest([FromBody] PointOfInterestDto pointOfInterestDto)
        {
            PointOfInterest pointOfInterest = _mapper.Map <PointOfInterest>(pointOfInterestDto);

            _pointOfInterest.Delete(pointOfInterest.Id);
            return(Ok());
        }
コード例 #5
0
        public void TestMultiplePoints()
        {
            PointOfInterestDto poi1 = new PointOfInterestDto
            {
                Id          = 1,
                Name        = "Downtown",
                Description = "Lots of food"
            };

            PointOfInterestDto poi2 = new PointOfInterestDto
            {
                Id          = 2,
                Name        = "Stanley Park",
                Description = "Lots to do"
            };

            PointOfInterestDto poi3 = new PointOfInterestDto
            {
                Id          = 3,
                Name        = "Science World",
                Description = "Lots of science"
            };

            CityDto city2 = new CityDto
            {
                Id               = 2,
                Name             = "Van",
                Description      = "City of Vancouver",
                PointsOfInterest = { poi1, poi2, poi3 }
            };

            Assert.Equal(3, city2.PointsOfInterest.Count);
        }
コード例 #6
0
        public IActionResult CreatePointOfInterest(int cityId, [FromBody] PointOfInterestModel pointOfInterest)
        {
            if (pointOfInterest == null)
            {
                return(BadRequest());
            }
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var city = CityDataStore.Current.Cities.FirstOrDefault(x => x.Id == cityId);

            if (city == null)
            {
                return(NotFound());
            }
            int id     = GetCurrentPointOfInterestId();
            var result = new PointOfInterestDto
            {
                Id          = ++id,
                Name        = pointOfInterest.Name,
                Description = pointOfInterest.Description
            };

            city.PointofInterest.Add(result);
            return(CreatedAtAction("GetPointOfInterest", new { cityId = cityId, id = result.Id }, result));
        }
コード例 #7
0
        public IActionResult createPointOfInteres(int cityId,
                                                  [FromBody] PointOfInterestForCreationDto pointOfInterest)
        {
            if (pointOfInterest == null)
            {
                return(BadRequest());
            }
            var city = CitiesDataStore.Current.Cities.FirstOrDefault(c => c.Id == cityId);

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            if (city == null)
            {
                return(NotFound());
            }
            var maxPointOfInterestId = CitiesDataStore.Current.Cities.SelectMany(
                c => c.PointOfInterest).Max(p => p.Id);
            var finalPointOfInterest = new PointOfInterestDto()
            {
                Id          = ++maxPointOfInterestId,
                Name        = pointOfInterest.Name,
                Description = pointOfInterest.Description
            };

            city.PointOfInterest.Add(finalPointOfInterest);
            return(CreatedAtRoute("GetPointOfInterest", new
                                  { cityId = cityId, id = finalPointOfInterest.Id }, finalPointOfInterest));
        }
コード例 #8
0
        public IActionResult CreatePointOfInterest1(int cityId, [FromBody] CreatePointOfInterestDto pointOfInterest)
        {
            if (pointOfInterest == null)
            {
                return(BadRequest());
            }

            var city = CitiesDataStore.Current.Cities.SingleOrDefault(c => c.Id == cityId);

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

            int newPointIfInterestId = CitiesDataStore.Current.Cities.SelectMany(c => c.PointsOfInterest).Max(i => i.Id);

            var newPointOfInterest = new PointOfInterestDto()
            {
                Id          = ++newPointIfInterestId,
                Name        = pointOfInterest.Name,
                Description = pointOfInterest.Description
            };


            city.PointsOfInterest.Add(newPointOfInterest);



            //return the 201 with the location header set to any string, it can be jibberish as well
            return(Created("blabla", newPointOfInterest));
        }
コード例 #9
0
        public async Task <IActionResult> PostAsync(int cityId, [FromBody] PointOfInterestDto pointOfInterest)
        {
            if (!_cityService.CityExists(cityId).Result)
            {
                return(NotFound());
            }

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

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

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            try
            {
                pointOfInterest.CityId = cityId;
                await _pointOfInterestService.Create(pointOfInterest);

                return(CreatedAtRoute("Get", new { id = pointOfInterest.Id }, pointOfInterest));
            }
            catch (Exception exception)
            {
                return(StatusCode((int)HttpStatusCode.InternalServerError, exception.Message));
            }
        }
コード例 #10
0
        public IActionResult poster(int cityId, [FromBody] PointOfInterestCreationDto newPointOfInterest)
        {
            var city = CitiesStore.Current.Cities.FirstOrDefault(c => c.Id == cityId);

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

            if (newPointOfInterest.Comment == newPointOfInterest.Name)
            {
                ModelState.AddModelError("comment", "comment should not be same as name");
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }                                                          //for data anotation.
            //can be automatically handle by apiConroller, but its required if custom Modelerror are added.

            var maxId = CitiesStore.Current.Cities.SelectMany(c => c.PointOfInterest).Max(p => p.Id);

            var finalPointOfInterest = new PointOfInterestDto()
            {
                Id      = ++maxId,
                Name    = newPointOfInterest.Name,
                Comment = newPointOfInterest.Comment
            };

            city.PointOfInterest.Add(finalPointOfInterest);

            return(CreatedAtRoute("GetPointOfInterest",
                                  new { cityId = cityId, id = finalPointOfInterest.Id },
                                  finalPointOfInterest));
        }
コード例 #11
0
        public IActionResult CreatePointOfInterest([FromRoute] int cityId, [FromBody] PointOfInterestDto pointOfInterest)
        {
            bool hasRedFlags = HasRedFlags();

            if (hasRedFlags)
            {
                return(BadRequest(ModelState));
            }

            var cityExists = _cityInfoRepository.CityExists(cityId);

            if (!cityExists)
            {
                return(NotFound());
            }

            var finalPointsOfInterest = _mapper.Map <PointOfInterest>(pointOfInterest);

            _cityInfoRepository.AddPointOfInterestForCity(cityId, finalPointsOfInterest);
            _cityInfoRepository.Save();

            var createdPointOfInterest = _mapper.Map <PointOfInterestDto>(finalPointsOfInterest);

            return(CreatedAtRoute("GetPointOfInterest", new { cityId, Id = createdPointOfInterest.Id, createdPointOfInterest }, createdPointOfInterest));
        }
コード例 #12
0
        public IActionResult UpdatePointOfInterest([FromRoute] int cityId, PointOfInterestDto pointOfInterest)
        {
            bool hasRedFlags = HasRedFlags();

            if (hasRedFlags)
            {
                return(BadRequest(ModelState));
            }

            var cityExists = _cityInfoRepository.CityExists(cityId);

            if (!cityExists)
            {
                return(NotFound());
            }

            var pointOfInterestEntity = _cityInfoRepository.GetOnePointOfInterestForCity(cityId, pointOfInterest.Id);

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

            _mapper.Map(pointOfInterest, pointOfInterestEntity);
            _cityInfoRepository.Save();

            return(NoContent());
        }
コード例 #13
0
        public IActionResult CreatePointOfInterest(int cityId,
                                                   [FromBody] PointOfInterestForCreationDto pointOfInterest)
        {
            if (pointOfInterest.Name == pointOfInterest.Description)
            {
                ModelState.AddModelError("Description", "Name and Description can't be same.");
            }

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

            var city = CitiesDataStore.Current.Cities.FirstOrDefault(c => c.Id == cityId);

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

            var maxPointOfINterest = city.PointOfInterest.Max(p => p.Id);

            var finalPointOfInterest = new PointOfInterestDto()
            {
                Id          = ++maxPointOfINterest,
                Name        = pointOfInterest.Name,
                Description = pointOfInterest.Description
            };

            city.PointOfInterest.Add(finalPointOfInterest);

            return(CreatedAtRoute("GetPointOfInterest", new { cityId, id = finalPointOfInterest.Id }, finalPointOfInterest));
        }
コード例 #14
0
        public IActionResult CreatePointOfInterest2(int cityId, [FromBody] CreatePointOfInterestDto pointOfInterest)
        {
            if (pointOfInterest == null)
            {
                return(BadRequest());
            }



            var city = CitiesDataStore.Current.Cities.SingleOrDefault(c => c.Id == cityId);

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

            int newPointIfInterestId = CitiesDataStore.Current.Cities.SelectMany(c => c.PointsOfInterest).Max(i => i.Id);

            var newPointOfInterest = new PointOfInterestDto()
            {
                Id          = ++newPointIfInterestId,
                Name        = pointOfInterest.Name,
                Description = pointOfInterest.Description
            };


            city.PointsOfInterest.Add(newPointOfInterest);



            //return the 201 with the location header to the route associated with the controller action
            //NOTE: this is not the best choice since the acton name may change in a refactoring and the reference here will be still pointing to the old controller action
            //      for that reason, the best usage would be CreatedAtRoute that will reference the Name associated with the route which will not change with the refactoring
            return(CreatedAtAction("GetPointOfInterest", new { cityId = cityId, id = newPointOfInterest.Id }, newPointOfInterest));
        }
コード例 #15
0
        public IActionResult Add(int cityId, PointOfInterestForCreationDto pointOfInterest)
        {
            if (pointOfInterest == null)
            {
                return(BadRequest());
            }


            var city = _cityDataStore.Cities.Where(a => a.Id == cityId).FirstOrDefault();

            if (city == null)
            {
                return(BadRequest());
            }
            var maxPointOfInterestId = city.PointsOfInterest.Max(a => a.Id);
            var newPointOfInterest   = new PointOfInterestDto()
            {
                Name        = pointOfInterest.Name,
                Description = pointOfInterest.Description,
                Id          = ++maxPointOfInterestId
            };

            city.PointsOfInterest.Add(newPointOfInterest);
            return(CreatedAtRoute("GetPointOfInterest", new { cityId, id = newPointOfInterest.Id }, newPointOfInterest));
        }
コード例 #16
0
        public IActionResult CreatePointOfInterestForCity(int cityId,
                                                          [FromBody] CreatePointOfInterestRequestModel requestModel)
        {
            if (requestModel == null || !ModelState.IsValid)
            {
                return(BadRequest());
            }

            var city = CitiesDataStore.Current.Cities.SingleOrDefault(c => c.Id == cityId);

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

            var maxPointOfInterestId = CitiesDataStore.Current.Cities.SelectMany(c => c.PointsOfInterest).Max(p => p.Id);

            var finalPointOfInterest = new PointOfInterestDto()
            {
                Id          = ++maxPointOfInterestId,
                Name        = requestModel.Name,
                Description = requestModel.Description
            };

            city.PointsOfInterest.Add(finalPointOfInterest);

            return(CreatedAtRoute("GetPointOfInterestForCity", new { cityId, pId = finalPointOfInterest.Id }, finalPointOfInterest));
        }
コード例 #17
0
        public IActionResult PartiallyUpdatePointOfInterest(int cityId, int id, [FromBody] JsonPatchDocument <PointOfInterestForUpdateDto> patchDocument)
        {
            // first lets check to make sure the patch document is ok
            if (patchDocument == null)
            {
                return(BadRequest());
            }

            // now we run our normal validation checks
            CityDto city = CitiesDataStore.Current.Cities.FirstOrDefault(c => c.Id == cityId);

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

            PointOfInterestDto pointOfInterestFromStore = city.PointsOfInterest.FirstOrDefault(p => p.Id == id);

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

            PointOfInterestForUpdateDto pointOfInterestToPatch =
                new PointOfInterestForUpdateDto()
            {
                Name        = pointOfInterestFromStore.Name,
                Description = pointOfInterestFromStore.Description
            };

            // here we are applying the incoming patch document to our update dto object to see if it passes the requirements
            patchDocument.ApplyTo(pointOfInterestToPatch, ModelState);

            // check the model state after the patch document has been applied to see if it passes.
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            // check our custom validation rule
            if (pointOfInterestToPatch.Description == pointOfInterestToPatch.Name)
            {
                ModelState.AddModelError("Description", "The provided description should be different than the name.");
            }

            // now we are going to use a built in validation helper to check the model itself for its validation.
            TryValidateModel(pointOfInterestToPatch);

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

            pointOfInterestFromStore.Name        = pointOfInterestToPatch.Name;
            pointOfInterestFromStore.Description = pointOfInterestToPatch.Description;

            return(NoContent());
        }
コード例 #18
0
        public IActionResult CreatePointOfInterest(int cityId, [FromBody] PointOfInterestForCreationDto pointOfInterest)
        {
            // [FromBody]  - allows us to get the content of the request. The request body will contain the information needed
            // to create a new point of interest. We want to serialize this point of interest dto.


            // because we are expecting a well formed PointOfInterestForCreationDto json object to be passed in we need to do some validation first
            if (pointOfInterest == null)
            {
                return(BadRequest());
            }

            //validate the incoming PointOfInterestForCreationDto has valid properties


            // we can of course create our own validation on the object like so:

            if (pointOfInterest.Description == pointOfInterest.Name)
            {
                ModelState.AddModelError("Description", "The provided description should be different than the name.");
            }

            if (!ModelState.IsValid)
            {
                //return BadRequest(); // if we just want to return a bad request then we can just use this

                return(BadRequest(ModelState)); // if we want to include the property error messages (in the response body) that are defined on the
                                                // PointOfInterestForCreationDto model then we need to include the model state.
            }


            // make sure the city exists
            CityDto city = CitiesDataStore.Current.Cities.FirstOrDefault(c => c.Id == cityId);

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

            // get the last POI ID so we can create the new one
            int lastPointOfInterestID = CitiesDataStore.Current.Cities.SelectMany(c => city.PointsOfInterest).Max(p => p.Id);

            // map the POI for creation object to a DTO that we will use
            PointOfInterestDto newPointOfInterestDto = new PointOfInterestDto()
            {
                Id          = ++lastPointOfInterestID,
                Name        = pointOfInterest.Name,
                Description = pointOfInterest.Description
            };

            city.PointsOfInterest.Add(newPointOfInterestDto);

            // for posts, its recommended to return a 201 Created response, we can return this using a the built in helper methods.
            // This helper response method will allow us to add a location header to the response, this will contain the new location URI where
            // the newly created information can be found.
            return(CreatedAtRoute("GetPointOfInterestReferenceName", new { cityId = cityId, id = newPointOfInterestDto.Id }, newPointOfInterestDto));
        }
コード例 #19
0
 public IActionResult Delete(int cityId, int id)
 {
     using (HttpClient client = ApiClient.GetClient())
     {
         HttpResponseMessage response  = client.GetAsync("/api/cities/" + cityId + "/pointsofinterest/" + id).Result;
         string             stringData = response.Content.ReadAsStringAsync().Result;
         PointOfInterestDto data       = JsonConvert.DeserializeObject <PointOfInterestDto>(stringData);
         return(View(data));
     };
 }
コード例 #20
0
        public IActionResult createPointOfInterest(
            int cityid,
            [FromBody] PointOfInterestForCreate pointofinterest
            )
        {
            //string result = $@"[name = { data.name }, description = { data.description } ]";

            //null exception
            if (pointofinterest == null)
            {
                return(BadRequest());
            }

            List <CityDto> cities = CitiesStore.Instance.cities;
            CityDto        city   = null;

            foreach (var c in cities)
            {
                if (c.id == cityid)
                {
                    city = c;
                }
            }
            //no city exception
            if (city == null)
            {
                return(NotFound());
            }

            //search maxid
            var points = city.PointsOfInterest;
            int maxid  = 0;

            foreach (var p in points)
            {
                if (p.id > maxid)
                {
                    maxid = p.id;
                }
            }
            //new point of interest
            var createdPointOfInterest = new PointOfInterestDto()
            {
                id          = maxid + 1,
                name        = pointofinterest.name,
                description = pointofinterest.description
            };

            //add point of interest
            points.Add(createdPointOfInterest);


            return(Ok());
        }
コード例 #21
0
 public IActionResult Create(int cityId, PointOfInterestDto pointOfInterest)
 {
     using (HttpClient client = ApiClient.GetClient())
     {
         string stringData            = JsonConvert.SerializeObject(pointOfInterest);
         var    contentData           = new StringContent(stringData, System.Text.Encoding.UTF8, "application/json");
         HttpResponseMessage response = client.PostAsync("/api/cities/" + cityId + "/pointsofinterest", contentData).Result;
         ViewBag.Message = response.Content.ReadAsStringAsync().Result;
         return(RedirectToAction("Details", "Cities", new { Id = cityId }));
     };
 }
コード例 #22
0
        private List <CityDto> MapHere(List <City> Cities)
        {
            List <CityDto> CityDtos = new List <CityDto>();

            //ICollection<CityDto> CityDtosI = new List<CityDto>();

            for (int Counter = 0; Counter < Cities.Count(); Counter++)
            {
                CityDto CityDto_Object = new CityDto();

                CityDto_Object.Id               = Cities[Counter].Id;
                CityDto_Object.Name             = Cities[Counter].Name;
                CityDto_Object.Description      = Cities[Counter].Description;
                CityDto_Object.PointsOfInterest = new List <PointOfInterestDto>();

                for (int PointOfInterestsCounter = 0;
                     PointOfInterestsCounter < Cities[Counter].PointsOfInterest.Count();
                     PointOfInterestsCounter++)
                {
                    PointOfInterestDto PointOfInterestDto_Object = new PointOfInterestDto();
                    PointOfInterestDto_Object.Id          = Cities[Counter].PointsOfInterest.ElementAt(PointOfInterestsCounter).Id;
                    PointOfInterestDto_Object.CityID      = Cities[Counter].PointsOfInterest.ElementAt(PointOfInterestsCounter).CityId;
                    PointOfInterestDto_Object.Name        = Cities[Counter].PointsOfInterest.ElementAt(PointOfInterestsCounter).Name;
                    PointOfInterestDto_Object.Description = Cities[Counter].PointsOfInterest.ElementAt(PointOfInterestsCounter).Description;

                    CityDto_Object.PointsOfInterest.Add(PointOfInterestDto_Object);
                }

                CityDto_Object.CityLanguages = new List <LanguageDtoMinusRelations>();
                for (int CityLanguageCounter = 0;
                     CityLanguageCounter < Cities[Counter].CityLanguages.Count();
                     CityLanguageCounter++)
                {
                    LanguageDtoMinusRelations LanguageDto_Object = new LanguageDtoMinusRelations();
                    LanguageDto_Object.Id           = Cities[Counter].CityLanguages.ElementAt(CityLanguageCounter).LanguageId;
                    LanguageDto_Object.LanguageName = Cities[Counter].CityLanguages.ElementAt(CityLanguageCounter).Language.LanguageName;

                    CityDto_Object.CityLanguages.Add(LanguageDto_Object);
                }
                CityDtos.Add(CityDto_Object);
            }

            CityDto CityDto_Object_Final = new CityDto();

            CityDto_Object_Final.Id          = 0;
            CityDto_Object_Final.Name        = "Egen Konvertering !!!";
            CityDto_Object_Final.Description = "Det sidste objekt her er lavet for at illustrere det arbejde, som AutoMapper gør for os !!!";

            CityDtos.Add(CityDto_Object_Final);

            return(CityDtos);
        }
コード例 #23
0
        //Action:Generation of resources
        public IActionResult CreatePointOfInterest(int cityId, [FromBody] PointsOfInterestDtoResourceGeneration pointOfInterestPosted)
        {
            //input data validation. Input validation can be done via Data anotations in the entity used for generate resources; PointsOfInterestDtoResourceGeneration. This is the basic but not the best because doesn't respect separation of concerns by defining validation in controller and model. Check FluentVAlidation on Github to see a robust input validation.
            if (pointOfInterestPosted == null)
            {
                return(new BadRequestResult());
            }

            //Using ModelsState is a dictionary that checks DataAnnotations on DTOs adherence and contains error mesages if failed.
            if (!ModelState.IsValid)
            {
                return(new BadRequestObjectResult(ModelState));//returns the ModelState that will display errors when user inpunt doesn't comply data anottations
            }

            //Custom input validation using ModelState
            if (pointOfInterestPosted.Description == pointOfInterestPosted.Name)
            {
                ModelState.AddModelError("CustomErrorKey", "CustomError message: The provided description should be different from the name");
                return(new BadRequestObjectResult(ModelState));//returns the ModelState thar will display errors when user inpunt doesn't comply data anottations
            }

            var cityOfPoints = CitiesDataStore.Current.Cities.FirstOrDefault(city => city.Id == cityId);

            if (cityOfPoints == null)
            {
                return(new NotFoundResult());
            }

            //create the point of interest

            //Generating id for new point --temporary solution using maping. to be refactored
            //I need to iterate trhough all the point od interest of all cities to find the highest id and increment it
            var maxPointOfInterestId = CitiesDataStore.Current.Cities.SelectMany(city => city.PointsOfInterest).Max(pointOfInterest => pointOfInterest.Id);

            //generating the new poit of interest
            var newPointOfInterest = new PointOfInterestDto()
            {
                Id          = ++maxPointOfInterestId,
                Name        = pointOfInterestPosted.Name,
                Description = pointOfInterestPosted.Description
            };

            //Adding the newlly created point of interest to the city
            cityOfPoints.PointsOfInterest.Add(newPointOfInterest);

            //Generating response for the request

            //I need to sendback the ubication for the newlly created point. I use the name given to the get route to get a Interest point and pass the city and new point ids as a parameter in a annonimus type(new {}) and finally I pass the newlly created point to be sended in the body of the response.
            return(CreatedAtRoute("GetPointOfInterest", new
                                  { cityId = cityId, pointId = newPointOfInterest.Id }, newPointOfInterest));
        }
コード例 #24
0
        public IActionResult DeletePointOfInterest(int cityid, int pointid)
        {
            CityDto            city  = CitiesStore.Instance.Cities.FirstOrDefault(c => c.Id == cityid);
            PointOfInterestDto point = city.PointsOfInterest.FirstOrDefault(p => p.Id == pointid);

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

            city.PointsOfInterest.Remove(point);

            return(NoContent());
        }
コード例 #25
0
        public bool UpdatePointOfInterest(CityDto city, PointOfInterestDto pointOfInterest)
        {
            var entity = city.PointsOfInterest.SingleOrDefault(p => p.Id == pointOfInterest.Id);

            if (entity == null)
            {
                return(false);
            }

            entity.Id          = pointOfInterest.Id;
            entity.Name        = pointOfInterest.Name;
            entity.Description = pointOfInterest.Description;

            return(true);
        }
コード例 #26
0
        public IActionResult CreatPointOfInterest(int cityId,
                                                  [FromBody] PointOfInterestForCreationDto pointOfInterest)
        {
            // Error: Bad request
            if (pointOfInterest == null)
            {
                return(BadRequest());
            }
            // if description and name are the same, return an error
            if (pointOfInterest.Description == pointOfInterest.Name)
            {
                ModelState.AddModelError("Description", "The provided description should be different from the name.");
            }
            // make sure the request is valid according to our 'PointOfInterestForCreationDto' [required] blocks
            // it will also check to see if ModelState is set to invalid inside of this function, e.g., ModelState.AddModelError
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState)); // ModelState tells you the specifically what is wrong, in the response for the request. For customized error handling + default
            }
            // ---
            // Error: Trying to add a point of interest to a city that does not exist
            var city = CitiesDataStore.Current.Cities.FirstOrDefault(c => c.Id == cityId);

            if (city == null)
            {
                return(NotFound());
            }
            // ---
            // Bad Practice, will be improved: Calculate the number of cities we have by looping through all of them and finding the one with the highest Id
            var maxPointOfInterestId = CitiesDataStore.Current.Cities.SelectMany(
                c => c.PointsOfInterest).Max(p => p.Id);

            // Create the new point of interest object
            var finalPointOfInterest = new PointOfInterestDto()
            {
                Id          = ++maxPointOfInterestId, // add one more to the current value, which we will use for the new point of interest
                Name        = pointOfInterest.Name,
                Description = pointOfInterest.Description
            };

            // add the new point of interest
            city.PointsOfInterest.Add(finalPointOfInterest);

            // return our status code CreatedAtRoute which requires route(city) value, and the created object value (finalPointOfInterest)
            // note: getpoint ofinterest refers to the id that was sent in the GET route
            return(CreatedAtRoute("GetPointOfInterest", new { cityId = cityId, id = finalPointOfInterest.Id }, finalPointOfInterest));
        }
コード例 #27
0
        public IActionResult CreatePointOfInterest(int cityId, PointOfInterestForCreationDto pointOfInterest)
        {
            //---------------------------------------------------->
            // This section of code is custom validation to check if the name matches the description
            if (pointOfInterest.Description == pointOfInterest.Name)
            {
                ModelState.AddModelError(
                    "Description",
                    "The provided description should be different from the name"
                    );
            }

            // ModelState must be manually thrown if you add a Model Error
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            //---------------------------------------------------->

            var city = CitiesDataStore.Current.Cities.FirstOrDefault(item => item.Id == cityId);

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

            // Amp through all POI and get the highest value
            var maxPointOfInterestId = CitiesDataStore.Current.Cities.SelectMany(item => item.PointOfInterest).Max(poi => poi.Id);

            var finalPointOfInterest = new PointOfInterestDto()
            {
                Id          = ++maxPointOfInterestId,     // increment the existing id by +1
                Name        = pointOfInterest.Name,       // pointOfInterest.Name = user input
                Description = pointOfInterest.Description // pointOfInterest.Description = user input
            };

            city.PointOfInterest.Add(finalPointOfInterest); // Add the result into List<PointOfInterest> defined in CitiesDto

            // CreatedAtRoute(routeName, routeValues, objectValues)
            return(CreatedAtRoute("GetPointOfInterest", new { cityId, id = finalPointOfInterest.Id }, finalPointOfInterest));

            /* To execute an POST request, it requires 201 response code.
             *
             * CreatedAtRoute() returns a location header
             */
        }
コード例 #28
0
        public IActionResult CreatePointOfInterest(int cityId, [FromBody] PointOfInterestForCreationDto pointOfInterest)
        {
            // if body is null, send bad request
            if (pointOfInterest == null)
            {
                return(BadRequest(ModelState));
            }

            // add a validation check to the model state to check that the description is not the same as the name.
            if (pointOfInterest.Description.Equals(pointOfInterest.Name, System.StringComparison.InvariantCultureIgnoreCase))
            {
                ModelState.AddModelError("Description", "The description cannot be the same as the name.");
            }

            // if the model is not valid (decorated by attributes), send bad request
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            // get the specified city
            var foundCity = CitiesDataStore.Current.Cities.Find(city => city.Id == cityId);

            // if the city is not found, send not found
            if (foundCity == null)
            {
                return(NotFound());
            }

            // get the new POI ID - not optimal, will improve (todo)
            var currentMaxId = CitiesDataStore.Current.Cities.SelectMany(city => city.PointsOfInterest).Max(poiDto => poiDto.Id);

            var newPoi = new PointOfInterestDto
            {
                Id          = ++currentMaxId,
                Name        = pointOfInterest.Name,
                Description = pointOfInterest.Description
            };

            // add the new point of interest to the specified city
            foundCity.PointsOfInterest.Add(newPoi);


            // create a result pointing to the new city (with the route specified)
            return(CreatedAtRoute("GetPointOfInterest", new { cityId = cityId, poiId = newPoi.Id }, newPoi));
        }
コード例 #29
0
        public IActionResult CreatePointOfInterest(int cityId, [FromBody] PointOfInterestForCreationDto pointOfInterest)
        {
            // this block will contain the request body will contain the data for the point of interest.
            // we want to deseraialize into a point of interest, for creation dto.
            // Thats what a from body attribute is for.
            if (pointOfInterest == null)
            {
                return(BadRequest());
            }

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

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


            var city = CitiesDataStore.Current.Cities.FirstOrDefault(c => c.Id == cityId);

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

            var maxPointOfInterestId = CitiesDataStore.Current.Cities.SelectMany(
                c => c.PointsOfInterest).Max(p => p.Id);

            var finalPointOfInterest = new PointOfInterestDto()
            {
                Id          = ++maxPointOfInterestId,
                Name        = pointOfInterest.Name,
                Description = pointOfInterest.Description
            };

            city.PointsOfInterest.Add((finalPointOfInterest));

            return(CreatedAtRoute("GetPointOfInterest", new
                                  { cityId = cityId, id = finalPointOfInterest.Id }, finalPointOfInterest));
        }
コード例 #30
0
      public IActionResult CreatePointOfInterest(int cityId, [FromBody]  PointOfInterestForCreation pointOfInterest)
      {
          var city = CitiesDataStore.Current.Cities.FirstOrDefault(c => c.Id == cityId);
          var maxIdPointOfInterest = CitiesDataStore.Current.Cities.SelectMany(c => c.PointsOfInterest).Max(p => p.Id);

          if (city == null)
          {
              return(NotFound());
          }
          var newPoint = new PointOfInterestDto
          {
              Id          = ++maxIdPointOfInterest,
              Description = pointOfInterest.Description,
              Name        = pointOfInterest.Name,
          };

          city.PointsOfInterest.Add(newPoint);
          return(CreatedAtRoute("GetPointOfAction", new { cityId = city.Id, id = newPoint.Id }, newPoint));
      }