示例#1
0
        private static void PostCountry()
        {
            Console.WriteLine("Post album");
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:60039/");
                client.DefaultRequestHeaders.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                var album = new CountryRequestModel()
                {
                    Name = "Country1"
                };

                var postContent = new StringContent(JsonConvert.SerializeObject(album));
                postContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                HttpResponseMessage response = client.PostAsync("api/country", postContent).Result;

                if (response.IsSuccessStatusCode)
                {
                    Console.WriteLine("Post succsessful");
                }
                else
                {
                    Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
                }
            }
        }
        public IHttpActionResult Update(string id, CountryRequestModel request)
        {
            if (id == null)
            {
                return this.BadRequest(GlobalMessages.IdMustNotBeNullMessage);
            }

            if (request == null)
            {
                return this.BadRequest(GlobalMessages.EntityMustNotBeNullMessage);
            }

            Country entity = this.data.CountriesRepository.FindById(id);
            if (entity == null)
            {
                return this.BadRequest(GlobalMessages.EntityDoesNotExist);
            }

            // Map the request model to the db model
            entity.Name = request.Name;

            this.data.CountriesRepository.Update(entity);
            int result = this.data.SaveChanges();
            return this.Ok($"{GlobalMessages.EntitySuccessfullyUpdatedMessage} - {result}");
        }
示例#3
0
        public async Task <CountryDto> CreateAsync(CountryRequestModel requestModel)
        {
            await CheckCountryExist(requestModel);

            Country createdCountry = await _countryRepository.AddAsync(_mapper.Map <Country>(requestModel));

            return(_mapper.Map <CountryDto>(createdCountry));
        }
        public IHttpActionResult Create(CountryRequestModel country)
        {
            if (!this.ModelState.IsValid)
            {
                return(this.BadRequest(this.ModelState));
            }

            var countryToAdd   = Mapper.Map <Country>(country);
            var addedCountryId = this.countriesServices.AddCountry(countryToAdd);

            return(this.Ok(addedCountryId));
        }
示例#5
0
        public async Task <CountryDto> UpdateAsync(string id, CountryRequestModel requestModel)
        {
            if (!await _countryRepository.AnyAsync(country => country.Id == id))
            {
                throw new ItemNotFoundException(id);
            }

            await CheckCountryExist(requestModel, id);

            var updatedCountry = await _countryRepository.UpdateAsync(id, _mapper.Map <Country>(requestModel));

            return(_mapper.Map <CountryDto>(updatedCountry));
        }
        public async Task <ActionResult> Update(CountryRequestModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(new { Errors = ModelState.Values }));
            }

            if (model.Id == 0)
            {
                return(BadRequest(new { Errors = new[] { "Country Id must be provided" } }));
            }

            Country country = _context.Countries.Find(model.Id);

            if (country == null)
            {
                return(NotFound(new { Errors = new[] { "Country not found" } }));
            }

            country.Name         = model.Name;
            country.Alpha2Code   = model.Alpha2Code;
            country.Alpha3Code   = model.Alpha3Code;
            country.NumericCode  = model.NumericCode;
            country.ISOReference = model.ISOReference;
            country.Independent  = model.Independent;

            _context.Countries.Update(country);

            try
            {
                _context.SaveChanges();
                return(Accepted(Url.Action("Filter", "Country", new { Name = country.Name }), new
                {
                    Data = country,
                    Link = new
                    {
                        Self = Url.Action("Filter", "Country", new { Name = country.Name })
                    }
                }));
            }
            catch (Exception ex)
            {
                return(Ok(new
                {
                    Errors = "Error encountered, please try again later",
                    Meta = new { StackTrace = ex.Message }
                }));
            }
        }
示例#7
0
        /// <summary>
        /// Expect CountryRequestModel with valid name.
        /// </summary>
        /// <param name="model"></param>
        /// <returns>
        /// If the country is added returns IHttpActionResult with status code 200 OK
        /// If the input data in not in the valid format retunrs  IHttpActionResult with status code 400 Bad Request
        /// </returns>
        public IHttpActionResult Post(CountryRequestModel model)
        {
            if (!this.ModelState.IsValid || model == null)
            {
                return(this.BadRequest(this.ModelState));
            }

            this.countries.Add(new Country
            {
                CountryName = model.Name
            });

            this.countries.SaveChanges();
            return(this.Ok());
        }
示例#8
0
        public IHttpActionResult Post(CountryRequestModel country)
        {
            if (country == null)
            {
                return(this.BadRequest());
            }
            countryData.Add(new Country()
            {
                Name = country.Name
            });

            countryData.SaveChanges();

            return(this.Ok());
        }
        public IHttpActionResult Update(CountryRequestModel targetCountry)
        {
            var countryToUpdate = this.db.Countries
                                  .FirstOrDefault(c => c.Id == targetCountry.Id);

            if (countryToUpdate == null)
            {
                return(this.NotFound());
            }

            countryToUpdate.Name = targetCountry.Name;
            this.db.SaveChanges();

            return(this.Ok(string.Format("The name of the country with id {0}, was successfully updated to {1}", targetCountry.Id, targetCountry.Name)));
        }
        // POST api/countries
        public async Task <HttpResponseMessage> PostCountry(CountryRequestModel requestModel)
        {
            Country country = _mapper.Map <CountryRequestModel, Country>(requestModel);

            country.CreatedOn = DateTimeOffset.Now;

            await _countryService.AddAsync(country);

            CountryDto          countryDto = _mapper.Map <Country, CountryDto>(country);
            HttpResponseMessage response   = Request.CreateResponse(HttpStatusCode.Created, countryDto);

            response.Headers.Location = GetCountryLink(country.Id);

            return(response);
        }
        // PUT api/countries/1
        public async Task <CountryDto> PutCountry(int id, CountryRequestModel requestModel)
        {
            Country country = await _countryService.GetByIdAsync(id);

            if (country == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            Country updatedCountry = requestModel.ToCountry(country);
            await _countryService.UpdateAsync(updatedCountry);

            CountryDto countryDto = _mapper.Map <Country, CountryDto>(country);

            return(countryDto);
        }
        // POST api/countries
        public HttpResponseMessage PostCountry(CountryRequestModel requestModel)
        {
            Country country = _mapper.Map <CountryRequestModel, Country>(requestModel);

            country.CreatedOn = DateTimeOffset.Now;

            _countryRepository.Add(country);
            _countryRepository.Save();

            CountryDto          countryDto = _mapper.Map <Country, CountryDto>(country);
            HttpResponseMessage response   = Request.CreateResponse(HttpStatusCode.Created, countryDto);

            response.Headers.Location = GetCountryLink(country.Id);

            return(response);
        }
        public IHttpActionResult Post(CountryRequestModel request)
        {
            if (request == null)
            {
                return this.BadRequest(GlobalMessages.EntityMustNotBeNullMessage);
            }

            var country = new Country
            {
                Name = request.Name
            };

            this.data.CountriesRepository.Add(country);
            int result = this.data.SaveChanges();
            return this.Ok($"{GlobalMessages.EntitySuccessfullyAddedMessage} - {result}");
        }
示例#14
0
        // POST a country
        private static async void PostCountry(string connection, string name)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(connection);
                var countryToAdd = new CountryRequestModel
                {
                    Name = name,
                    Id = 10
                };

                var result = await client.PostAsJsonAsync(connection, countryToAdd);
                string resultContent = result.Content.ReadAsStringAsync().Result;
                Console.WriteLine(resultContent);
            }
        }
        public IHttpActionResult Post(CountryRequestModel countryToAdd)
        {
            if (!this.ModelState.IsValid)
            {
                return(this.BadRequest());
            }

            var dbCountry = new Country
            {
                Name = countryToAdd.Name
            };

            this.db.Countries.Add(dbCountry);
            this.db.SaveChanges();

            return(this.Ok(string.Format("{0} was added to Countries database!", countryToAdd.Name)));
        }
示例#16
0
        // POST a country
        private static async void PostCountry(string connection, string name)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(connection);
                var countryToAdd = new CountryRequestModel
                {
                    Name = name,
                    Id   = 10
                };

                var result = await client.PostAsJsonAsync(connection, countryToAdd);

                string resultContent = result.Content.ReadAsStringAsync().Result;
                Console.WriteLine(resultContent);
            }
        }
        public IHttpActionResult Post(CountryRequestModel countryToAdd)
        {
            if (!this.ModelState.IsValid)
            {
                return this.BadRequest();
            }

            var dbCountry = new Country
            {
                Name = countryToAdd.Name
            };

            this.db.Countries.Add(dbCountry);
            this.db.SaveChanges();

            return this.Ok(string.Format("{0} was added to Countries database!", countryToAdd.Name));
        }
示例#18
0
        public IHttpActionResult Post([FromBody] CountryRequestModel model)
        {
            if (!this.ModelState.IsValid)
            {
                return(this.BadRequest(this.ModelState));
            }

            var entity = new Country()
            {
                Name = model.Name
            };

            this.context.AddEntity(entity);
            this.context.Save();

            return(this.Created(this.Url.ToString(), entity));
        }
示例#19
0
        // PUT api/countries/1
        public async Task <CountryDto> PutCountry(int id, CountryRequestModel requestModel)
        {
            Country country = await _countryService.GetByIdAsync(id);

            if (country == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            // NOTE: AutoMapper goes bananas over this as
            // EF creates the poroxy class for Country
            // Country updatedCountry = Mapper.Map<CountryRequestModel, Country>(requestModel, country);

            Country updatedCountry = requestModel.ToCountry(country);
            await _countryService.UpdateAsync(country);

            CountryDto countryDto = _mapper.Map <Country, CountryDto>(country);

            return(countryDto);
        }
示例#20
0
        public IHttpActionResult Put(int id, CountryRequestModel model)
        {
            var countryToUpdate = this.countries
                                  .All()
                                  .FirstOrDefault(c => c.Id == id);

            if (countryToUpdate == null)
            {
                return(this.NotFound());
            }

            if (!this.ModelState.IsValid || model == null)
            {
                return(this.BadRequest(this.ModelState));
            }

            countryToUpdate.CountryName = model.Name;
            this.countries.SaveChanges();

            return(this.Ok("The country was updated successfully"));
        }
示例#21
0
        // PUT request doesn't work for some reason
        private static async void PutCountry(string connection, string name)
        {
            using (var client = new HttpClient())
            {
                var countryToUpdate = new CountryRequestModel
                {
                    Name = name
                };

                client.BaseAddress = new Uri(connection);
                var response = await client.PutAsJsonAsync(connection, countryToUpdate);

                if (response.IsSuccessStatusCode)
                {
                    Console.WriteLine("{0} added sccuessfully!", countryToUpdate.Name);
                }
                else
                {
                    Console.WriteLine("Awww that's awkward... Nothing has been added!");
                }
            }
        }
        // PUT api/countries/1
        public CountryDto PutCountry(int id, CountryRequestModel requestModel)
        {
            Country country = _countryRepository.GetSingle(id);

            if (country == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            // NOTE: AutoMapper goes bananas over this as
            // EF creates the poroxy class for Country
            // Country updatedCountry = Mapper.Map<CountryRequestModel, Country>(requestModel, country);

            Country updatedCountry = requestModel.ToCountry(country);

            _countryRepository.Edit(updatedCountry);
            _countryRepository.Save();

            CountryDto countryDto = _mapper.Map <Country, CountryDto>(country);

            return(countryDto);
        }
        public async Task <ActionResult> Create(CountryRequestModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(new { Errors = ModelState.Values }));
            }

            Country country = new Country
            {
                Name         = model.Name,
                Alpha2Code   = model.Alpha2Code,
                Alpha3Code   = model.Alpha3Code,
                NumericCode  = model.NumericCode,
                ISOReference = model.ISOReference,
                Independent  = model.Independent
            };

            _context.Countries.Add(country);

            try
            {
                _context.SaveChanges();
                return(Created(Url.Action("Filter", "Country", new { Name = country.Name }), new
                {
                    Data = country,
                    Link = new {
                        Self = Url.Action("Filter", "Country", new { Name = country.Name })
                    }
                }));
            } catch (Exception ex)
            {
                return(Ok(new {
                    Errors = "Error encountered, please try again later",
                    Meta = new { StackTrace = ex.Message }
                }));
            }
        }
示例#24
0
        private async Task CheckCountryExist(CountryRequestModel requestModel, string id = null)
        {
            var existingCountry = await _countryRepository.FirstOrDefaultAsync(country =>
                                                                               (string.IsNullOrEmpty(id) || country.Id != id) &&
                                                                               (country.Name == requestModel.Name ||
                                                                                country.Iso2 == requestModel.Iso2 ||
                                                                                country.Iso3 == requestModel.Iso3 ||
                                                                                country.PhoneCode == requestModel.PhoneCode
                                                                               ));

            if (existingCountry != null)
            {
                var allreadyExistingDataList = new List <object>();

                if (existingCountry.Name == requestModel.Name)
                {
                    allreadyExistingDataList.Add(existingCountry.Name);
                }

                if (existingCountry.Iso2 == requestModel.Iso2)
                {
                    allreadyExistingDataList.Add(existingCountry.Iso2);
                }

                if (existingCountry.Iso3 == requestModel.Iso3)
                {
                    allreadyExistingDataList.Add(existingCountry.Iso3);
                }

                if (existingCountry.PhoneCode == requestModel.PhoneCode)
                {
                    allreadyExistingDataList.Add(existingCountry.PhoneCode);
                }

                throw new ItemAlreadyExistsException(string.Join(",", allreadyExistingDataList));
            }
        }
示例#25
0
 public virtual async Task <CountryDto> CreateAsync([FromBody] CountryRequestModel request)
 => await _countryService.CreateAsync(request);
示例#26
0
 public virtual async Task <CountryDto> UpdateAsync(string id, [FromBody] CountryRequestModel request)
 => await _countryService.UpdateAsync(id, request);
示例#27
0
        // PUT request doesn't work for some reason
        private static async void PutCountry(string connection, string name)
        {
            using (var client = new HttpClient())
            {
                var countryToUpdate = new CountryRequestModel
                {
                    Name = name
                };

                client.BaseAddress = new Uri(connection);
                var response = await client.PutAsJsonAsync(connection, countryToUpdate);
                if (response.IsSuccessStatusCode)
                {
                    Console.WriteLine("{0} added sccuessfully!", countryToUpdate.Name);
                }
                else
                {
                    Console.WriteLine("Awww that's awkward... Nothing has been added!");
                }
            }
        }
        public IHttpActionResult Update(CountryRequestModel targetCountry)
        {
            var countryToUpdate = this.db.Countries
               .FirstOrDefault(c => c.Id == targetCountry.Id);

            if (countryToUpdate == null)
            {
                return this.NotFound();
            }

            countryToUpdate.Name = targetCountry.Name;
            this.db.SaveChanges();

            return this.Ok(string.Format("The name of the country with id {0}, was successfully updated to {1}", targetCountry.Id, targetCountry.Name));
        }
示例#29
0
        private static void PostCountry()
        {
            Console.WriteLine("Post album");
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:60039/");
                client.DefaultRequestHeaders.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                var album = new CountryRequestModel()
                {
                    Name = "Country1"
                };

                var postContent = new StringContent(JsonConvert.SerializeObject(album));
                postContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                HttpResponseMessage response = client.PostAsync("api/country", postContent).Result;

                if (response.IsSuccessStatusCode)
                {
                    Console.WriteLine("Post succsessful");
                }
                else
                {
                    Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
                }
            }
        }