private WeatherResult MapResponseToWeatherResult(OpenWeatherMapResponse response)
 {
     return(response == null ? null : new WeatherResult(
                response.WeatherDescription?.FirstOrDefault()?.Title,
                response.WeatherDescription?.FirstOrDefault()?.FullDescription,
                (int)Math.Round(UnitsConverter.ConvertTemperatureKelvinToCelsius((double)(response.WeatherGeneralInformation?.Temperature ?? 0M)), 0),
                response.WeatherGeneralInformation?.Pressure ?? 0
                ));
 }
Beispiel #2
0
        public async Task <WeatherResult> ParseAsync(string cityName, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(cityName))
            {
                throw new ArgumentException("cityName is required");
            }

            cancellationToken.ThrowIfCancellationRequested();

            string apiRequestUrl = GetApiRequestUrl(cityName);

            _logger.WriteLog("Begin request to OpenWeatherMap Api");
            var httpResponse = await _client.GetAsync(apiRequestUrl, cancellationToken);

            _logger.WriteLog($"Response from OpenWeatherMap Api received. Http Code: {httpResponse?.StatusCode}");

            cancellationToken.ThrowIfCancellationRequested();

            var responseJson = await httpResponse.Content.ReadAsStringAsync();

            _logger.WriteLog($"Response from OpenWeatherMap: {responseJson}");

            cancellationToken.ThrowIfCancellationRequested();

            dynamic parsedResponse = JsonConvert.DeserializeObject <ExpandoObject>(responseJson);
            var     last           = parsedResponse.list.Count > 0 ? parsedResponse.list[parsedResponse.list.Count - 1] : null;

            if (last == null)
            {
                return(null);
            }

            var lastWeather = (last.weather?.Count ?? 0) >= 1 ? last.weather[0] : null;

            return(new WeatherResult((string)lastWeather?.main, (string)lastWeather?.description,
                                     (int)Math.Round(UnitsConverter.ConvertTemperatureKelvinToCelsius((double)(last.main?.temp ?? 0M)), 0),
                                     (int?)last.main?.pressure ?? 0));
        }