Exemplo n.º 1
0
        /// <summary>
        ///  Searches for cities that match the given cityName, countryCode and countyName,
        ///  returning a list of matching cities.
        /// </summary>
        /// <param name="cityName">Mandatory. Name of the city to search for.</param>
        /// <param name="countryCode">Optional. Two letter country code for the city to search for.</param>
        /// <param name="countryName">Optional. Name of the country to search for. </param>
        public async Task <IList <City> > SearchForCities(string cityName, string countryCode = null,
                                                          string countryName = null)
        {
            string requestUri = string.Empty;

            if (countryCode == null && countryName != null)
            {
                GlobalizationHelper globalizationHelper = new GlobalizationHelper();
                countryCode = globalizationHelper.GetCountryCode(countryName);
            }

            if (countryCode != null)
            {
                requestUri = $"{_serachBaseUrl}{cityName},{countryCode}&type=like&appid={_searchApiKey}";
            }
            else
            {
                requestUri = $"{_serachBaseUrl}{cityName}&type=like&appid={_searchApiKey}";
            }

            HttpClient client = new HttpClient {
                BaseAddress = new Uri(requestUri)
            };

            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response = await client.GetAsync(requestUri);

            if (response.IsSuccessStatusCode)
            {
                string responseJsonString = await response.Content.ReadAsStringAsync();

                WeatherSearchResultDto deserializedProduct = JsonConvert.DeserializeObject <WeatherSearchResultDto>(responseJsonString);

                IDomainMapper <WeatherSearchResultDto, IList <City> > cityMapper = new CityMap();
                IList <City> cityList = cityMapper.MapTo(deserializedProduct);

                return(cityList);
            }

            return(null);
        }