private void extract_current_weather(XmlNode node) { WeatherInfo w = new WeatherInfo { TemperatureLow = double.Parse(node["temp_c"].InnerText), TemperatureHigh = double.Parse(node["temp_c"].InnerText), Pressure = double.Parse(node["pressure_mb"].InnerText) * 0.75006375541921, WindSpeed = double.Parse(node["wind_kph"].InnerText) / 3.6, WeatherType = weather_type_encoding.Keys.Contains(node["icon"].InnerText) ? weather_type_encoding[node["icon"].InnerText] : WeatherType.Undefined }; string hum = node["relative_humidity"].InnerText; hum = hum.Substring(0, hum.IndexOf('%')); w.Humidity = double.Parse(hum); // WindDirection = wind_direction_encoding.Keys.Contains(node["wind_direction"].InnerText) ? wind_direction_encoding[node["wind_direction"].InnerText] : WindDirection.Undefined, double wind_degrees = double.Parse(node["wind_degrees"].InnerText); foreach (var d in wind_direction_degrees.Keys) { if (wind_degrees >= d - 22.5 / 2.0 && wind_degrees < d + 22.5 / 2.0) { w.WindDirection = wind_direction_degrees[d]; break; } } }
protected override void read_current_weather() { WeatherInfo w = new WeatherInfo(); read_nsu_current_temp(w); read_ngs_current_weather(w); lock (_locker) { _weather.Clear(); _weather[WeatherPeriod.Now] = w; } }
internal void get_nsu_current_temp(WeatherInfo w) { string st = _sitereader.temperature(); if (st != null || !st.Contains("°")) { CultureInfo culture = new CultureInfo("en"); double t = double.Parse(st.Substring(0, st.IndexOf("°")), culture); w.TemperatureLow = w.TemperatureHigh = t; } else { throw new Exception("incorrect NSU current temperature"); } }
public void get_forecast(Dictionary <WeatherPeriod, WeatherInfo> weather) { string forecast = _sitereader.forecast(); if (forecast == null) { throw new Exception("incorrect current weather structure "); } XmlDocument pg = new XmlDocument(); pg.LoadXml(forecast); XmlNode pgd_forecast = pg.DocumentElement; var day_divs = pgd_forecast.SelectNodes("//div[@class = 'card']"); if (day_divs.Count == 0) { day_divs = pgd_forecast.SelectNodes("//article[@class = 'card']"); } int day_period = 0; for (int day = 0; day < day_divs.Count; day++) { XmlNode day_div = day_divs[day]; var table_rows = day_div.SelectNodes("./dd[@class='forecast-details__day-info']/table[@class = 'weather-table']/tbody[@class = 'weather-table__body']/tr[@class = 'weather-table__row']"); if (table_rows.Count == 0) { table_rows = day_div.SelectNodes("./div[@class='forecast-details__day-info']/table[@class = 'weather-table']/tbody[@class = 'weather-table__body']/tr[@class = 'weather-table__row']"); } for (int period = 0; period < 4; period++) // утро, день, вечер, ночь { XmlNode row = table_rows[period]; WeatherInfo w = new WeatherInfo(); get_daypart_weather(row, w); if (day_period < day_periods.Length) { weather[day_periods[day_period]] = w; } day_period++; } } }
private WeatherInfo get_current_weather() { Trace.WriteLine(">>> get_current_weather()"); bool success = true; _succeeded = true; lock (_locker) { if (_extractor == null) { return(null); } } try { var wi = new WeatherInfo(); _extractor.get_current_weather(wi); return(wi); } catch (Exception e) { success = false; _error_descr = e.Message; string fname = string.Format(@"d:\LOG\{0} -- {1}", DateTime.Now.ToString("yyyy_MM_dd HH-mm-ss"), _error_descr); } finally { if (!success) { lock (_locker) { _succeeded = false; } } } return(null); }
private void read_nsu_current_temp(WeatherInfo w) { bool success = false; try { string st = _sitereader.temperature(); if (st != null || !st.Contains("°")) { success = true; CultureInfo culture = new CultureInfo("en"); double t = double.Parse(st.Substring(0, st.IndexOf("°")), culture); lock (_locker) { w.TemperatureLow = w.TemperatureHigh = t; _succeeded = true; } } } catch (Exception e) { success = false; _error_descr = e.Message; } finally { if (!success) { lock (_locker) { _succeeded = false; } } } try { _sitereader.getrest(); } catch (Exception) { } }
private WeatherInfo get_nsu_current_temp() { bool success = true; lock (_locker) { if (_extractor == null) { return(null); } } try { WeatherInfo wi = new WeatherInfo(); _extractor.get_nsu_current_temp(wi); return(wi); } catch (Exception e) { success = false; _error_descr = e.Message; } finally { if (!success) { lock (_locker) { _succeeded = false; } } } return(null); }
public void get_current_weather(WeatherInfo w) { string current = _sitereader.current(); if (current == null) { throw new Exception("incorrect current weather structure "); } XmlDocument pg = new XmlDocument(); pg.LoadXml(current); XmlNode pgd_current = pg.DocumentElement; // weather character string wt = get_weather_type(pgd_current, "./div/a//img"); w.WeatherType = weather_type_encoding.Keys.Contains(wt) ? weather_type_encoding[wt] : WeatherType.Undefined; #if STATISTICS if (!stat_weather_type.Keys.Contains(wt)) { class_name = "link__condition"; XmlNode weather_type = pgd_current.SelectSingleNode($"./div/a/div/div[starts-with(@class, '{class_name}')]"); if (weather_type == null) { throw new Exception("incorrect current weather structure-- cant find weather type string"); } string wts = weather_type.InnerText; write_statistics(wt, wts); } #endif // air temperature w.TemperatureHigh = w.TemperatureLow = get_air_temperature(pgd_current, "./div/a//div/span[@class = 'temp__value temp__value_with-unit']"); // wind w.WindSpeed = null; XmlNode wind_speed = pgd_current.SelectSingleNode($"./div[@class = 'fact__props']//span[@class = 'wind-speed']"); if (wind_speed == null) { throw new Exception("incorrect current weather structure -- cant find wind speed"); } if (double.TryParse(wind_speed.InnerText.Replace(',', '.').Replace('−', '-').Trim(), NumberStyles.Number, new CultureInfo("en"), out double windspeed)) { w.WindSpeed = windspeed; } w.WindDirection = WindDirection.Undefined; XmlNode wind_dir = pgd_current.SelectSingleNode($"./div[@class = 'fact__props']//span[@class = 'fact__unit']/abbr"); if (wind_dir == null) { throw new Exception("incorrect current weather structure -- cant find wind direction"); } string wind_dir_name = wind_dir.InnerText; if (wind_direction_encoding.Keys.Contains(wind_dir_name)) { w.WindDirection = wind_direction_encoding[wind_dir_name]; } // humidity w.Humidity = null; XmlNode humidity = pgd_current.SelectSingleNode($"./div[@class = 'fact__props']//div[@class = 'term term_orient_v fact__humidity']/div[@class='term__value']"); if (humidity == null) { throw new Exception("incorrect current weather structure -- cant find humidity"); } if (double.TryParse(humidity.InnerText.Replace(',', '.').Replace('−', '-').Replace('%', ' ').Trim(), NumberStyles.Number, new CultureInfo("en"), out double hum)) { w.Humidity = hum; } // pressure w.Pressure = null; XmlNode pressure = pgd_current.SelectSingleNode($"./div[@class = 'fact__props']//div[@class = 'term term_orient_v fact__pressure']"); if (pressure == null) { throw new Exception("incorrect current weather structure -- cant find pressure"); } if (double.TryParse(pressure.InnerText.Split(' ')[0].Replace(',', '.').Replace('−', '-').Trim(), NumberStyles.Number, new CultureInfo("en"), out double press)) { w.Pressure = press; } // hourly temperature forecast var hour_spans = pgd_current.SelectNodes("//span[@class = 'fact__hour-elem']"); if (hour_spans.Count == 0) { hour_spans = pgd_current.SelectNodes("//div[@class = 'fact__hour-elem']"); } foreach (XmlNode hour_span in hour_spans) { wt = get_weather_type(hour_span, "./img"); if (!wt.Equals("sunset") && !wt.Equals("sunrise")) { ShortWeatherInfo swi = new ShortWeatherInfo(); double? temp = get_air_temperature(hour_span, "./div[@class = 'fact__hour-temp']"); XmlNode hour = hour_span.SelectSingleNode($"./div[@class = 'fact__hour-label']"); if (hour != null && temp.HasValue) { if (int.TryParse(hour.InnerText.Trim().Split(':')[0], NumberStyles.Number, new CultureInfo("en"), out int hr)) { w.HourlyWeather.Add(new ShortWeatherInfo() { Hour = hr, Temperature = temp.Value, WeatherType = weather_type_encoding.Keys.Contains(wt) ? weather_type_encoding[wt] : WeatherType.Undefined }); } } } #if STATISTICS if (!wt.Equals("sunset") && !wt.Equals("sunrise") && !stat_weather_type.Keys.Contains(wt)) { string wts = hour_span.SelectSingleNode("@aria-label").Value; wts = wts.Substring(0, wts.IndexOf(',')); for (int i = 0; i < 3; i++) { wts = wts.Substring(wts.IndexOf(' ') + 1); } write_statistics(wt, wts); } #endif } }
private void get_daypart_weather(XmlNode row, WeatherInfo w) { // type string wt = get_weather_type(row, "./td/img", "icon icon_thumb_"); w.WeatherType = weather_type_encoding.Keys.Contains(wt) ? weather_type_encoding[wt] : WeatherType.Undefined; #if STATISTICS if (!wt.Equals("sunset") && !wt.Equals("sunrise") && !stat_weather_type.Keys.Contains(wt)) { string wts = row.SelectSingleNode("./td[@class = 'weather-table__body-cell weather-table__body-cell_type_condition']").InnerText; write_statistics(wt, wts); } #endif // temperature var air_temps = row.SelectNodes("./td//div/span[@class='temp__value temp__value_with-unit']"); if (air_temps.Count >= 2) { w.TemperatureLow = get_air_temperature(air_temps[0]); w.TemperatureHigh = get_air_temperature(air_temps[1]); } else if (air_temps.Count == 1) { w.TemperatureLow = w.TemperatureHigh = get_air_temperature(air_temps[0]); } else { throw new Exception("incorrect forecast structure-- cant find temperature "); } // pressure var pressure = row.SelectSingleNode("./td[@class = 'weather-table__body-cell weather-table__body-cell_type_air-pressure']"); if (pressure == null) { throw new Exception("incorrect forecast structure-- cant find pressure"); } if (double.TryParse(pressure.InnerText.Replace(',', '.').Replace('−', '-').Trim(), NumberStyles.Number, new CultureInfo("en"), out double press)) { w.Pressure = press; } // humidity var humidity = row.SelectSingleNode("./td[@class = 'weather-table__body-cell weather-table__body-cell_type_humidity']"); if (humidity == null) { throw new Exception("incorrect forecast structure-- cant find humidity"); } if (double.TryParse(humidity.InnerText.Replace(',', '.').Replace('−', '-').Replace('%', ' ').Trim(), NumberStyles.Number, new CultureInfo("en"), out double humi)) { w.Humidity = humi; } // wind w.WindDirection = WindDirection.Undefined; w.WindSpeed = 0.0; XmlNode wind_speed = row.SelectSingleNode("./td//div//span[@class = 'wind-speed']"); if (wind_speed != null) { if (double.TryParse(wind_speed.InnerText.Replace(',', '.').Replace('−', '-').Trim(), NumberStyles.Number, new CultureInfo("en"), out double windspeed)) { w.WindSpeed = windspeed; } XmlNode wind_dir = row.SelectSingleNode($"./td//div[@class = 'weather-table__wind-direction']/abbr"); if (wind_dir == null) { throw new Exception("incorrect current weather structure -- cant find wind direction"); } string wind_dir_name = wind_dir.InnerText; if (wind_direction_encoding.Keys.Contains(wind_dir_name)) { w.WindDirection = wind_direction_encoding[wind_dir_name]; } } else { // may be it is штиль? wind_speed = row.SelectSingleNode("./td//div//span[@class = 'weather-table__wind']"); if (wind_speed == null || !wind_speed.InnerText.Equals("Штиль")) { throw new Exception("incorrect forecast structure -- cant find wind speed"); } } }
private void read_ngs_current_weather(WeatherInfo w) { bool success = true; _succeeded = true; try { string current = _sitereader.current(); if (current == null) { throw new Exception("incorrect current weather structure "); } XmlDocument pg = new XmlDocument(); pg.LoadXml(current); XmlNode pgd_current = pg.DocumentElement; // weather character string class_name = "icon-weather-big "; XmlNode icon_weather = pgd_current.SelectSingleNode(string.Format("./div/div[starts-with(@class, '{0}')]", class_name)); if (icon_weather == null) { throw new Exception("incorrect current weather structure-- cant find weather type icon"); } string wt = icon_weather.SelectSingleNode("@class").Value.Substring(class_name.Length); w.WeatherType = weather_type_encoding.Keys.Contains(wt) ? weather_type_encoding[wt] : WeatherType.Undefined; XmlNode today = pgd_current.SelectSingleNode("./div[@class = 'today-panel__info__main']"); if (today == null) { throw new Exception("incorrect current weather structure -- cant find today weather panel"); } XmlNode curr = today.SelectSingleNode("./div[starts-with(@class, 'today-panel__info__main__item')]"); if (curr == null) { throw new Exception("incorrect current weather structure -- cant find weather panel"); } // temperature XmlNode temp = curr.SelectSingleNode("./div/span/span[@class = 'value__main']"); if (temp == null) { throw new Exception("incorrect current weather structure -- cant find current temperature"); } string st = temp.InnerText.Trim().Replace(',', '.').Replace('−', '-'); if (string.IsNullOrEmpty(st)) { throw new Exception("incorrect current weather structure -- incorrect current temperature string"); } double t = double.Parse(st, new CultureInfo("en")); w.TemperatureHigh = w.TemperatureLow = t; //File.WriteAllText(@"D:\Projects\YetAnotherPictureSlideshow\PictureSlideshowScreensaver\samples\XMLFile2.xml", curr.OuterXml); // wind string cn = "icon-small icon-wind-"; XmlNode ei = curr.SelectSingleNode(string.Format("./dl/dd/i[starts-with(@class, '{0}')]", cn)); if (ei == null) { throw new Exception("incorrect current weather structure -- cant find wind direction"); } string wd = ei.SelectSingleNode("@class").Value.Substring(cn.Length); w.WindDirection = wind_direction_encoding.Keys.Contains(wd) ? wind_direction_encoding[wd] : WindDirection.Undefined; XmlNode edt = ei.ParentNode.NextSibling; if (edt == null || edt.Name.ToLower() != "dt") { throw new Exception("incorrect structure -- 2.1"); } string wind = edt.InnerText.TrimStart('\n', '\r', '\t', ' '); double ws; if (double.TryParse(wind.Substring(0, wind.IndexOf(' ')), NumberStyles.Number, new CultureInfo("en"), out ws)) { w.WindSpeed = ws; } // pressure ei = curr.SelectSingleNode("./dl/dd/i[@class = 'icon-small icon-pressure']"); if (ei == null || ei.Name.ToLower() != "i") { throw new Exception("incorrect structure -- 2.2"); } double p; string pr = ei.SelectSingleNode("@title").Value; if (double.TryParse(pr.Substring(0, pr.IndexOf(' ')), NumberStyles.Number, new CultureInfo("ru"), out p)) { w.Pressure = p; } // humidity ei = curr.SelectSingleNode("./dl/dd/i[@class = 'icon-small icon-humidity']"); if (ei == null || ei.Name.ToLower() != "i") { throw new Exception("incorrect structure -- 2.3"); } double h; string humidity = ei.SelectSingleNode("@title").Value; if (double.TryParse(humidity.Substring(0, humidity.IndexOf('%')), NumberStyles.Number, new CultureInfo("ru"), out h)) { w.Humidity = h; } } catch (Exception e) { success = false; _error_descr = e.Message; string fname = string.Format(@"d:\LOG\{0} -- {1}", DateTime.Now.ToString("yyyy_MM_dd HH-mm-ss"), _error_descr); } finally { if (!success) { lock (_locker) { _succeeded = false; } } } }
private bool extract_day_forecast(int day, XmlNode tr) { XmlNode tc = tr.SelectSingleNode("./td[@class='elements__section-day']"); if (tc == null) { _error_descr = "cant find day " + day.ToString(); return(false); } // check day of month XmlNodeList spans = tc.SelectNodes("./div/span"); if (spans.Count != 1) { _error_descr = "incorrect days in day" + day.ToString(); return(false); } string dt = spans[0].InnerText; int di; if (!int.TryParse(dt.Substring(0, dt.IndexOf(' ')), out di)) { di = 0; } if ((DateTime.Now + TimeSpan.FromDays(day)).Day != di) { _error_descr = "incorrect day"; return(false); } // day's periods XmlNodeList period_divs = tr.SelectCellDivs("elements__section-daytime"); // temperature XmlNodeList temperature_divs = tr.SelectCellDivs("elements__section-temperature"); if (temperature_divs.Count != period_divs.Count) { throw new Exception(string.Format("incorrect temperature count in day {0}", day)); } // weather type XmlNodeList weather_divs = tr.SelectCellDivs("elements__section-weather"); if (weather_divs.Count != period_divs.Count) { throw new Exception(string.Format("incorrect weather type count in day {0}", day)); } // wind XmlNodeList wind_divs = tr.SelectCellDivs("elements__section-wind"); if (wind_divs.Count != period_divs.Count) { throw new Exception(string.Format("incorrect wind count in day {0}", day)); } // pressure XmlNodeList pressure_divs = tr.SelectCellDivs("elements__section-pressure"); if (pressure_divs.Count != period_divs.Count) { throw new Exception(string.Format("incorrect pressure count in day {0}", day)); } // humidity XmlNodeList humidity_divs = tr.SelectCellDivs("elements__section-humidity"); if (humidity_divs.Count != period_divs.Count) { throw new Exception(string.Format("incorrect humidity count in day {0}", day)); } int pcount = period_divs.Count; for (int period = 0; period < pcount; period++) { WeatherInfo w = new WeatherInfo(); // weather period string pname = period_divs[period].InnerText; if (!_day_periods[day].Keys.Contains(pname)) { throw new Exception("invalid period name"); } WeatherPeriod wp = _day_periods[day][pname]; // temperature string temperature_s = temperature_divs[period].InnerText.Trim().Replace('−', '-'); w.TemperatureLow = w.TemperatureHigh = int.Parse(temperature_s); // weather type string cn = "icon-weather icon-weather-"; XmlNode e = weather_divs[period].SelectSingleNode("./i"); if (e == null) { throw new Exception("cant find weather type"); } string wt = e.SelectSingleNode("@class").Value.Substring(cn.Length); if (wt.IndexOf(' ') != -1) { wt = wt.Substring(0, wt.IndexOf(' ')); } w.WeatherType = weather_type_encoding.Keys.Contains(wt) ? weather_type_encoding[wt] : WeatherType.Undefined; if (w.WeatherType == WeatherType.Undefined) { int i = 0; } // wind cn = "icon-small icon-wind-"; e = wind_divs[period].SelectSingleNode("./i"); if (e == null) { throw new Exception("cant find wind direction"); } string wd = e.SelectSingleNode("@class").Value.Substring(cn.Length); if (wd.IndexOf(' ') != -1) { wd = wd.Substring(0, wd.IndexOf(' ')); } w.WindDirection = wind_direction_encoding.Keys.Contains(wd) ? wind_direction_encoding[wd] : WindDirection.Undefined; string ws = wind_divs[period].InnerText.TrimStart('\n', '\r', '\t', ' '); ws = ws.Substring(0, ws.IndexOf(' ')); w.WindSpeed = int.Parse(ws); // pressure string pr = pressure_divs[period].InnerText.TrimStart('\n', '\r', '\t', ' '); pr = pr.Substring(0, pr.IndexOf(' ')); w.Pressure = int.Parse(pr); // humidity string hu = humidity_divs[period].InnerText; hu = hu.Substring(0, hu.IndexOf('%')); w.Humidity = int.Parse(hu); lock (_locker) { _weather[wp] = w; } } return(true); }
private void startButton_Click(object sender, EventArgs e) { if (latitudeTextBox.Text.Length != 0 && longitudeTextBox.Text.Length != 0) { string dataWeatherFromUserTown = null; string dataGeonamesFromUserTown = null; bool reussite = false; try { // if an exception is raise the program will ask for a town again dataWeatherFromUserTown = Client.DownloadString(String.Format("http://api.openweathermap.org/data/2.5/weather?lat={0}&lon={1}&appid={2}", latitudeTextBox.Text, longitudeTextBox.Text, IdWeather)); dataGeonamesFromUserTown = Client.DownloadString(String.Format("http://api.geonames.org/timezoneJSON?&lat={0}&lng={1}&username={2}", latitudeTextBox.Text, longitudeTextBox.Text, idGeonames)); Thread.Sleep(300); reussite = true; } catch (WebException ex) { MessageBox.Show(string.Format("la ville n'existe pas ou est mal écrite : {0}.", ex.Message)); } if (reussite) { WeatherInfo testDayDuration = JsonConvert.DeserializeObject <WeatherInfo>(dataGeonamesFromUserTown); this.info = testDayDuration; changementInfo(); } } else if (villeTextBox.Text.Length != 0) { string urlTownOpenWeather = String.Format("http://api.openweathermap.org/data/2.5/weather?q={0},fr&appid={1}", villeTextBox.Text, IdWeather); string rechercheVille = null; try { // if an exception is raise the program will ask for a town again rechercheVille = Client.DownloadString(urlTownOpenWeather); Thread.Sleep(300); MessageBox.Show(rechercheVille); } catch (WebException ex) { MessageBox.Show(string.Format("la ville n'existe pas ou est mal écrite : {0}.", ex.Message)); } if (rechercheVille.Length != 0) { JObject weatherUserTownJson = JObject.Parse(rechercheVille); string dataGeonamesFromUserTown = null; try { // if an exception is raise the program will ask for a town again dataGeonamesFromUserTown = Client.DownloadString(String.Format("http://api.geonames.org/timezoneJSON?&lat={0}&lng={1}&username={2}", double.Parse(weatherUserTownJson.SelectToken("coord.lat").ToString()).ToString(CultureInfo.InvariantCulture), double.Parse(weatherUserTownJson.SelectToken("coord.lon").ToString()).ToString(CultureInfo.InvariantCulture), idGeonames)); Thread.Sleep(300); } catch (WebException ex) { Console.WriteLine("la ville n'existe pas ou est mal écrite : {0}.", ex.Message); } if (dataGeonamesFromUserTown.Length != 0) { WeatherInfo testDayDuration = JsonConvert.DeserializeObject <WeatherInfo>(dataGeonamesFromUserTown); this.info = testDayDuration; changementInfo(); } } } }