public async Task <IList <DayForecast> > GetDailyForecasts(string locationKey, ApiSettings apiSettings) { string url = BuildUri(locationKey, apiSettings, true); var response = await _httpClient.GetAsync(url); string apiResponseText = await response.Content.ReadAsStringAsync(); JObject apiResponse = JObject.Parse(apiResponseText); IList <JToken> results = apiResponse["DailyForecasts"].Children().ToList(); IList <DayForecast> forecasts = new List <DayForecast>(); foreach (JToken result in results) { DayForecast forecast = new DayForecast(); forecast.Day = result.Value <DateTime>("Date"); JToken tempList = result.Value <JToken>("Temperature"); forecast.MaximumTemp = tempList.Value <JToken>("Maximum").Value <double>("Value"); forecast.MinimumTemp = tempList.Value <JToken>("Minimum").Value <double>("Value"); forecasts.Add(forecast); } return(forecasts); }
private static DayForecast GetDayForecast(int position, HtmlNode[] describes, HtmlNode[] winds, HtmlNode[] precipitations, HtmlNode[] temperatures) { int?NullableIntParse(string data) { return(int.TryParse(data, out var mint) ? (int?)mint : null); } decimal DecimalParse(string data) { return(decimal.Parse(data.Replace(",", "."), CultureInfo.InvariantCulture)); } var dayForecast = new DayForecast { Describe = describes[position].GetDescribe(), Date = DateTime.Now.AddDays(position), WindSpeedMs = DecimalParse(winds[position].GetWindSpeed()), Precipitation = DecimalParse(precipitations[position].GetPrecipitationLevel()), TemperatureMax = NullableIntParse(temperatures[position].GetTemperatureMax()), TemperatureMin = NullableIntParse(temperatures[position].GetTemperatureMin()) }; return(dayForecast); }
public DailyForecastItem(DayForecast forecast) { ConditionDescription = forecast.ConditionsDescription; ImageUrl = forecast.ImageUrl; WindSpeed = $"{forecast.WindSpeed} mph ({forecast.WindDirection})"; HiTemp = $"Hi Temp: {forecast.HiTemp}"; LowTemp = $"Low Temp: {forecast.LowTemp}"; CalendarDay = forecast.TimeStamp.ToString("dddd, MMMM d"); }
private DayForecast CreateForecast(SqlDataReader results) { DayForecast forecast = new DayForecast(); forecast.ParkCode = Convert.ToString(results["parkCode"]); forecast.DaysOut = Convert.ToString(results["fiveDayForecastValue"]); forecast.Low = Convert.ToInt32(results["low"]); forecast.High = Convert.ToInt32(results["high"]); forecast.Forecast = Convert.ToString(results["forecast"]); return(forecast); }
public bool GetLocationData(City city) { int cityId; // Other grabbers store string IDs and this would fail here if (city.Grabber != GetServiceName() || !int.TryParse(city.Id, out cityId)) { return(false); } var client = new OpenWeatherMapClient(GetKey()); var currentWeather = Task.Run(async() => await client.CurrentWeather.GetByCityId(cityId, _metricSystem, _language)).Result; city.Condition.Temperature = FormatTemp(currentWeather.Temperature.Value, currentWeather.Temperature.Unit); city.Condition.Humidity = string.Format("{0} {1}", currentWeather.Humidity.Value, currentWeather.Humidity.Unit); city.Condition.Pressure = string.Format("{0:F0} {1}", currentWeather.Pressure.Value, currentWeather.Pressure.Unit); city.Condition.Precipitation = string.Format("{0} {1}", currentWeather.Precipitation.Value, currentWeather.Precipitation.Unit); city.Condition.Wind = string.Format("{0} {1}", currentWeather.Wind.Speed.Name, currentWeather.Wind.Direction.Name); city.Condition.Condition = currentWeather.Weather.Value; var now = DateTime.Now; bool isNight = now >= currentWeather.City.Sun.Set || now < currentWeather.City.Sun.Rise; city.Condition.BigIcon = @"Weather\128x128\" + GetWeatherIcon(currentWeather.Weather.Number, isNight); city.Condition.SmallIcon = @"Weather\64x64\" + GetWeatherIcon(currentWeather.Weather.Number, isNight); var forecasts = Task.Run(async() => await client.Forecast.GetByCityId(cityId, true, _metricSystem, _language)).Result; foreach (var forecast in forecasts.Forecast) { DayForecast dayForecast = new DayForecast(); dayForecast.High = FormatTemp(forecast.Temperature.Max, currentWeather.Temperature.Unit); dayForecast.Low = FormatTemp(forecast.Temperature.Min, currentWeather.Temperature.Unit); dayForecast.Humidity = string.Format("{0} {1}", forecast.Humidity.Value, forecast.Humidity.Unit); // TODO: //dayForecast.Pressure = string.Format("{0} {1}", forecast.Pressure.Value, forecast.Pressure.Unit); dayForecast.Precipitation = string.Format("{0} {1}", forecast.Precipitation.Value, forecast.Precipitation.Unit); dayForecast.Wind = string.Format("{0} {1}", forecast.WindSpeed.Mps, currentWeather.Wind.Direction.Name); dayForecast.Overview = forecast.Symbol.Name; dayForecast.BigIcon = @"Weather\128x128\" + GetWeatherIcon(forecast.Symbol.Number, false); dayForecast.SmallIcon = @"Weather\64x64\" + GetWeatherIcon(forecast.Symbol.Number, false); string fomattedDate = forecast.Day.ToString(_dateFormat.ShortDatePattern, _dateFormat); string day = _dateFormat.GetAbbreviatedDayName(forecast.Day.DayOfWeek); dayForecast.Day = String.Format("{0} {1}", day, fomattedDate); city.ForecastCollection.Add(dayForecast); } city.ForecastCollection.FireChange(); return(true); }
public async Task <bool> GetLocationData(City city) { int cityId; // Other grabbers store string IDs and this would fail here if (city.Grabber != GetServiceName() || !int.TryParse(city.Id, out cityId)) { return(false); } Tuple <City, DateTime> data; await _lock.WaitAsync(); try { if (_cache.TryGetValue(cityId, out data) && DateTime.Now - data.Item2 <= MAX_CACHE_DURATION) { city.Copy(data.Item1); return(true); } await new SynchronizationContextRemover(); var client = new OpenWeatherMapClient(GetKey()); var currentWeather = await client.CurrentWeather.GetByCityId(cityId, _metricSystem, _language); city.Condition.Temperature = FormatTemp(currentWeather.Temperature.Value, currentWeather.Temperature.Unit); city.Condition.Humidity = string.Format("{0} {1}", currentWeather.Humidity.Value, currentWeather.Humidity.Unit); city.Condition.Pressure = string.Format("{0:F0} {1}", currentWeather.Pressure.Value, currentWeather.Pressure.Unit); city.Condition.Precipitation = string.Format("{0} {1}", currentWeather.Precipitation.Value, currentWeather.Precipitation.Unit); city.Condition.Wind = string.Format("{0} {1}", currentWeather.Wind.Speed.Name, currentWeather.Wind.Direction.Name); city.Condition.Condition = currentWeather.Weather.Value; var now = DateTime.Now; bool isNight = now >= currentWeather.City.Sun.Set || now < currentWeather.City.Sun.Rise; city.Condition.BigIcon = @"Weather\128x128\" + GetWeatherIcon(currentWeather.Weather.Number, isNight); city.Condition.SmallIcon = @"Weather\64x64\" + GetWeatherIcon(currentWeather.Weather.Number, isNight); var forecasts = await client.Forecast.GetByCityId(cityId, true, _metricSystem, _language); foreach (var forecast in forecasts.Forecast) { DayForecast dayForecast = new DayForecast(); dayForecast.High = FormatTemp(forecast.Temperature.Max, currentWeather.Temperature.Unit); dayForecast.Low = FormatTemp(forecast.Temperature.Min, currentWeather.Temperature.Unit); dayForecast.Humidity = string.Format("{0} {1}", forecast.Humidity.Value, forecast.Humidity.Unit); // TODO: //dayForecast.Pressure = string.Format("{0} {1}", forecast.Pressure.Value, forecast.Pressure.Unit); dayForecast.Precipitation = string.Format("{0} {1}", forecast.Precipitation.Value, forecast.Precipitation.Unit); dayForecast.Wind = string.Format("{0} {1}", forecast.WindSpeed.Mps, currentWeather.Wind.Direction.Name); dayForecast.Overview = forecast.Symbol.Name; dayForecast.BigIcon = @"Weather\128x128\" + GetWeatherIcon(forecast.Symbol.Number, false); dayForecast.SmallIcon = @"Weather\64x64\" + GetWeatherIcon(forecast.Symbol.Number, false); string fomattedDate = forecast.Day.ToString(_dateFormat.ShortDatePattern, _dateFormat); string day = _dateFormat.GetAbbreviatedDayName(forecast.Day.DayOfWeek); dayForecast.Day = String.Format("{0} {1}", day, fomattedDate); city.ForecastCollection.Add(dayForecast); } city.ForecastCollection.FireChange(); _cache[cityId] = new Tuple <City, DateTime>(city, DateTime.Now); } finally { _lock.Release(); } return(true); }
private bool Parse(City city, XPathDocument doc) { if (city == null || doc == null) return false; CultureInfo currentCulture = ServiceRegistration.Get<ILocalization>().CurrentCulture; DateTimeFormatInfo dateFormat = currentCulture.DateTimeFormat; _isMetricRegion = new RegionInfo(currentCulture.LCID).IsMetric; XPathNavigator navigator = doc.CreateNavigator(); XPathNavigator condition = navigator.SelectSingleNode("/data/current_condition"); if (condition != null) { city.Condition.Temperature = FormatCurrentTemp(condition); city.Condition.Wind = FormatWind(condition); city.Condition.Humidity = FormatHumidity(condition); city.Condition.Precipitation = FormatPrecip(condition); city.Condition.Pressure = FormatPressure(condition); XPathNavigator node = condition.SelectSingleNode("weatherDesc"); if (node != null) city.Condition.Condition = node.Value; node = condition.SelectSingleNode("weatherCode"); if (node != null) { city.Condition.BigIcon = @"Weather\128x128\" + GetWeatherIcon(node.ValueAsInt); city.Condition.SmallIcon = @"Weather\64x64\" + GetWeatherIcon(node.ValueAsInt); } } XPathNodeIterator forecasts = navigator.Select("/data/weather"); city.ForecastCollection.Clear(); while (forecasts.MoveNext()) { if (forecasts.Current == null) continue; DayForecast dayForecast = new DayForecast(); XPathNavigator node = forecasts.Current.SelectSingleNode("date"); if (node != null) { DateTime date = node.ValueAsDateTime; string day = dateFormat.GetAbbreviatedDayName(date.DayOfWeek); // Attention: CurrentThread.Culture / UICulture are NOT set to ILocalization.Culture, so ILocalization.Culture // has to be used explicitly here for formatting date correctly. string fomattedDate = date.ToString(dateFormat.ShortDatePattern, dateFormat); dayForecast.Day = String.Format("{0} {1}", day, fomattedDate); } dayForecast.Low = FormatTempLow(forecasts.Current); dayForecast.High = FormatTempHigh(forecasts.Current); dayForecast.Precipitation = FormatPrecip(forecasts.Current); dayForecast.Wind = FormatWind(forecasts.Current); node = forecasts.Current.SelectSingleNode("weatherCode"); if (node != null) { dayForecast.BigIcon = @"Weather\128x128\" + GetWeatherIcon(node.ValueAsInt); dayForecast.SmallIcon = @"Weather\64x64\" + GetWeatherIcon(node.ValueAsInt); } node = forecasts.Current.SelectSingleNode("weatherDesc"); if (node != null) dayForecast.Overview = node.Value; city.ForecastCollection.Add(dayForecast); } return true; }
private bool Parse(City city, XPathDocument doc) { if (city == null || doc == null) { return(false); } CultureInfo currentCulture = ServiceRegistration.Get <ILocalization>().CurrentCulture; DateTimeFormatInfo dateFormat = currentCulture.DateTimeFormat; _isMetricRegion = new RegionInfo(currentCulture.LCID).IsMetric; XPathNavigator navigator = doc.CreateNavigator(); XPathNavigator condition = navigator.SelectSingleNode("/data/current_condition"); if (condition != null) { city.Condition.Temperature = FormatCurrentTemp(condition); city.Condition.Wind = FormatWind(condition); city.Condition.Humidity = FormatHumidity(condition); city.Condition.Precipitation = FormatPrecip(condition); city.Condition.Pressure = FormatPressure(condition); XPathNavigator node = condition.SelectSingleNode("weatherDesc"); if (node != null) { city.Condition.Condition = node.Value; } node = condition.SelectSingleNode("weatherCode"); if (node != null) { city.Condition.BigIcon = @"Weather\128x128\" + GetWeatherIcon(node.ValueAsInt); city.Condition.SmallIcon = @"Weather\64x64\" + GetWeatherIcon(node.ValueAsInt); } } XPathNodeIterator forecasts = navigator.Select("/data/weather"); city.ForecastCollection.Clear(); while (forecasts.MoveNext()) { if (forecasts.Current == null) { continue; } DayForecast dayForecast = new DayForecast(); XPathNavigator node = forecasts.Current.SelectSingleNode("date"); if (node != null) { DateTime date = node.ValueAsDateTime; string day = dateFormat.GetAbbreviatedDayName(date.DayOfWeek); // Attention: CurrentThread.Culture / UICulture are NOT set to ILocalization.Culture, so ILocalization.Culture // has to be used explicitly here for formatting date correctly. string fomattedDate = date.ToString(dateFormat.ShortDatePattern, dateFormat); dayForecast.Day = String.Format("{0} {1}", day, fomattedDate); } dayForecast.Low = FormatTempLow(forecasts.Current); dayForecast.High = FormatTempHigh(forecasts.Current); dayForecast.Precipitation = FormatPrecip(forecasts.Current); dayForecast.Wind = FormatWind(forecasts.Current); node = forecasts.Current.SelectSingleNode("weatherCode"); if (node != null) { dayForecast.BigIcon = @"Weather\128x128\" + GetWeatherIcon(node.ValueAsInt); dayForecast.SmallIcon = @"Weather\64x64\" + GetWeatherIcon(node.ValueAsInt); } node = forecasts.Current.SelectSingleNode("weatherDesc"); if (node != null) { dayForecast.Overview = node.Value; } city.ForecastCollection.Add(dayForecast); } return(true); }
public bool GetCityData(string city, WeatherInfo weatherInfo) { try { var resultApi3 = _client.DownloadString( $"http://api.openweathermap.org/data/2.5/weather?q={city}&units=metric&appid={_key3}"); dynamic jsonData3 = JsonConvert.DeserializeObject(resultApi3); var resultApi2 = _client.DownloadString($"https://api.weatherbit.io/v2.0/forecast/daily?city={city}&key={_key2}"); dynamic jsonData2 = JsonConvert.DeserializeObject(resultApi2); var resultApi = _client.DownloadString( $"http://api.worldweatheronline.com/premium/v1/weather.ashx?key={_key}&q={city}&num_of_days=10&tp=1&format=json"); dynamic jsonData = JsonConvert.DeserializeObject(resultApi); weatherInfo.Today.City = jsonData3.name.ToString(); weatherInfo.Today.Query = jsonData.data.request[0].query; weatherInfo.Today.Time = DateTime.Now; weatherInfo.Today.TempC = jsonData.data.current_condition[0].temp_C; weatherInfo.Today.TempF = jsonData.data.current_condition[0].temp_F; weatherInfo.Today.Des = jsonData.data.current_condition[0].weatherDesc[0].value; weatherInfo.Today.WindSpeedMiles = jsonData.data.current_condition[0].windspeedMiles; weatherInfo.Today.WindSpeedKm = jsonData.data.current_condition[0].windspeedKmph; weatherInfo.Today.WindDirDegree = jsonData.data.current_condition[0].winddirDegree; weatherInfo.Today.Humidity = jsonData.data.current_condition[0].humidity; weatherInfo.Today.VisibilityMiles = jsonData.data.current_condition[0].visibilityMiles; weatherInfo.Today.Visibility = jsonData.data.current_condition[0].visibility; weatherInfo.Today.Barometer = jsonData.data.current_condition[0].pressure; weatherInfo.Today.BarometerInches = jsonData.data.current_condition[0].pressureInches; weatherInfo.Today.FeelsLikeC = jsonData.data.current_condition[0].FeelsLikeC; weatherInfo.Today.FeelsLikeF = jsonData.data.current_condition[0].FeelsLikeF; weatherInfo.Today.UvIndex = jsonData.data.current_condition[0].uvIndex; weatherInfo.Today.Icon = jsonData3.weather[0].icon; weatherInfo.Forecast.Clear(); for (var i = 0; i < jsonData.data.weather.Count; i++) { DateTime.TryParse(jsonData.data.weather[i].astronomy[0].sunrise.ToString(), out DateTime sunrise); DateTime.TryParse(jsonData.data.weather[i].astronomy[0].sunset.ToString(), out DateTime sunset); DateTime.TryParse(jsonData.data.weather[i].astronomy[0].moonrise.ToString(), out DateTime moonrise); var today = new DayForecast { Date = jsonData.data.weather[i].date, Sunrise = sunrise, Sunset = sunset, Moonrise = moonrise }; try { today.Moonset = jsonData.data.weather[i].astronomy[0].moonset; } catch { // ignored } today.MoonPhase = jsonData.data.weather[i].astronomy[0].moon_phase; today.MaxTempC = jsonData.data.weather[i].maxtempC; today.MaxTempF = jsonData.data.weather[i].maxtempF; today.MinTempC = jsonData.data.weather[i].mintempC; today.MinTempF = jsonData.data.weather[i].mintempF; today.UvIndex = jsonData.data.weather[i].uvIndex; today.Far = weatherInfo.Today.Derge; if (jsonData2 != null) { foreach (var item in jsonData2.data) { if (jsonData.data.weather[i].date != item.valid_date) { continue; } today.Desc = item.weather.description; today.Icon = _iconConvert.ConverterIcon(item.weather.icon.ToString()); } } for (var j = 0; j < jsonData.data.weather[i].hourly.Count; j++) { today.hourForecasts.Add(new HourForecast { Time = _timeConverter.ConvertHour(jsonData.data.weather[i].hourly[j].time.ToString()), TempC = jsonData.data.weather[i].hourly[j].tempC, TempF = jsonData.data.weather[i].hourly[j].tempF, WindSpeedMiles = jsonData.data.weather[i].hourly[j].windspeedMiles, WindSpeedKm = jsonData.data.weather[i].hourly[j].windspeedKmph, WindDirDegree = jsonData.data.weather[i].hourly[j].winddirDegree, WeatherDesc = jsonData.data.weather[i].hourly[j].weatherDesc[0].value, Humidity = jsonData.data.weather[i].hourly[j].humidity, Far = weatherInfo.Today.Derge }); } weatherInfo.Forecast.Add(today); } weatherInfo.Forecast.RemoveAt(0); return(true); } catch { return(false); } }
public async void SetLocation(string location, double latitude, double longitude) { IsLoading = true; CurrentLocation = location; Latitude = latitude; Longitude = longitude; OlderDataVisible = false; var weather = Settings.Settings.Instance.GetWeather(latitude, longitude); if (weather is null) { try { weather = await OpenWeather.GetWeather(latitude, longitude, OpenWeather.Units.Metric); Settings.Settings.Instance.UpdatePlace(latitude, longitude, weather); } catch (Exception) { weather = Settings.Settings.Instance.GetWeatherFull(latitude, longitude); if (weather is null) { IsLoading = false; return; } OlderDataVisible = true; OlderDataText = string.Format(Resources.AppTranslations.OldDataFrom, Settings.Settings.Instance.GetWeatherRefreshTime(latitude, longitude)?.ToString("g")); } } DateText = DateTime.Now.ToString("d"); if (weather.Current.WeatherList.Count > 0) { WeatherIcon = StringToIconConverter.Convert(weather.Current.WeatherList[0].Icon); WeatherDescription = weather.Current.WeatherList[0].Description.FirstCharToUpper(); } WeatherTemperature = FormatTemperature(weather.Current.Temperature); if (weather.Current.Rain != null) { var max = Math.Max(weather.Current.Rain.ThreeHours, weather.Current.Rain.OneHour); WeatherRain = max.ToString("F0") + "mm"; } if (weather.Current.Snow != null) { var max = Math.Max(weather.Current.Snow.ThreeHours, weather.Current.Snow.OneHour); WeatherRain = max.ToString("F0") + "mm"; } WeatherWind = FormatWindSpeed(weather.Current.WindSpeed); WeatherPressure = weather.Current.Pressure.ToString("F0") + "hPa"; WeatherSunrise = string.Format(AppTranslations.Sunrise, UnixTimeStampToDateTimeConverter.Convert(weather.Current.Sunrise).ToString("t")); WeatherSunset = string.Format(AppTranslations.Sunset, UnixTimeStampToDateTimeConverter.Convert(weather.Current.Sunset).ToString("t")); HoursForecastItems.Clear(); foreach (var hourlyWeather in weather.Hourly) { var forecast = new HourForecast() { Time = UnixTimeStampToDateTimeConverter.Convert(hourlyWeather.Datetime) .ToString("t"), Temperature = FormatTemperature(hourlyWeather.Temperature) }; if (hourlyWeather.WeatherList.Count > 0) { forecast.IconSource = StringToIconConverter.Convert(hourlyWeather.WeatherList[0].Icon); } HoursForecastItems.Add(forecast); if (HoursForecastItems.Count >= 24) { break; } } DaysForecastItems.Clear(); foreach (var dailyWeather in weather.Daily) { var forecast = new DayForecast() { Temperature = FormatTemperature(dailyWeather.Temperature.Day), Time = UnixTimeStampToDateTimeConverter.Convert(dailyWeather.Datetime + weather.TimezoneOffset) .ToString("ddd"), Rain = (dailyWeather.Rain + dailyWeather.Snow).ToString("F0") + "mm", }; if (dailyWeather.WeatherList.Count > 0) { forecast.IconSource = StringToIconConverter.Convert(dailyWeather.WeatherList[0].Icon); } DaysForecastItems.Add(forecast); if (DaysForecastItems.Count >= 7) { break; } } RefreshFavoritePlaces(); IsLoading = false; }