static void Main(string[] args) { var pattern = @"(?<city>[A-Z]{2})(?<temp>\d+\.\d+)(?<weather>[a-zA-Z]+)\|"; var cities = new Dictionary <string, WeatherInfo>(); var input = Console.ReadLine(); while (input != "end") { var weatherMatch = Regex.Match(input, pattern); if (!weatherMatch.Success) { input = Console.ReadLine(); continue; } var city = weatherMatch.Groups["city"].Value; var temp = double.Parse(weatherMatch.Groups["temp"].Value); var weather = weatherMatch.Groups["weather"].Value; var weatherInfo = new WeatherInfo { AverageTemp = temp, Weather = weather }; cities[city] = weatherInfo; input = Console.ReadLine(); } var sortedCities = cities.OrderBy(x => x.Value.AverageTemp) .ToDictionary(a => a.Key, a => a.Value); foreach (var cityInfo in sortedCities) { var city = cityInfo.Key; var weatherInfo = cityInfo.Value; Console.WriteLine($"{city} => {weatherInfo.AverageTemp:f2} => {weatherInfo.Weather}"); } }
//display weather info static private void DisplayWeather(WeatherInfo info) { Console.WriteLine($"City: {info.name}"); Console.WriteLine("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); Console.WriteLine($"Weather: {info.weather[0].main} ({info.weather[0].description})"); Console.WriteLine($"temperature: {ConvertToFahrenheit(info.main.temp)}" + "F"); Console.WriteLine($"pressure: {info.main.pressure}"); Console.WriteLine("humidity: " + info.main.humidity + "%\n"); }
protected static void DeserializeAndDisplay(string inffo) { //get weather info from cache //weather info instance WeatherInfo info = Newtonsoft.Json.JsonConvert.DeserializeObject <WeatherInfo>(inffo); //display weather info for each city DisplayWeather(info); }
public MainWindow() { var provider = new OpenWeatherMapProvider(); Weather = provider.ParseCurrentWeather(weatherJsonString); var forecast = provider.ParseForecast(forecastJsonString); WeatherInfo = new WeatherInfo() { Current = Weather, Forecast = forecast }; InitializeComponent(); }
/// <summary> /// Ok button clicked /// Adds the city to collection /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ButtonOk_Click(object sender, RoutedEventArgs e) { string newCity = TextBoxCity.Text; if (!WeatherInfo.CityIsValid(newCity)) { TextBoxCity.Text = "Not a valid city name"; return; } if (!collectionCitiesTemp.Contains(newCity)) { collectionCitiesTemp.Add(newCity); } this.Close(); }
public static WeatherInfo ForZipCode(IWeatherService weatherService, string zipCode) { try { var weatherInfo = new WeatherInfo(); weatherInfo.UpdateForZipCode(weatherService, zipCode); return weatherInfo; } catch (WebException webException) { throw new WeatherException("There was a network error while connecting to the weather service.", webException); } catch (XmlException xmlException) { throw new WeatherException("There was an xml error while parsing weather data from the weather service.", xmlException); } }
/// <summary> /// Constructor /// </summary> public MainWindow() { InitializeComponent(); /// default values for cities /// bind the collection to combobox and pass to modal windows collectionCities = new ObservableCollection <string>() { "Prague", "Brno", "Ostrava" }; Binding bindingCities = new Binding(); bindingCities.Source = collectionCities; ComboBoxCities.SetBinding(ComboBox.ItemsSourceProperty, bindingCities); ComboBoxCities.SelectedIndex = 0; /// Prepare api and get weather info WeatherInfo.SetApi(); UpdateDates(); UpdateForPlace(collectionCities[0]); previousCity = collectionCities[0]; }
static void Main(string[] args) { var regex = new Regex(@"(?<city>[A-Z]{2})(?<temp>\d+\.\d+)(?<weather>[A-Za-z]+)\|"); var cities = new Dictionary <string, WeatherInfo>(); var line = Console.ReadLine(); while (line != "end") { var weatherMatch = regex.Match(line); if (!weatherMatch.Success) { line = Console.ReadLine(); continue; } var city = weatherMatch.Groups["city"].Value; var averageTemp = double.Parse(weatherMatch.Groups["temp"].Value); var weather = weatherMatch.Groups["weather"].Value; var weatherInfo = new WeatherInfo { AverageTemperature = averageTemp, Weather = weather }; cities[city] = weatherInfo; line = Console.ReadLine(); } // var sortedCities = cities.OrderBy(a => a.Value.AverageTemperature).ToDictionary(a => a.Key, a => a.Value); foreach (var cityInfo in cities.OrderBy(x => x.Value.AverageTemperature)) { var city = cityInfo.Key; var weatherInfo = cityInfo.Value; Console.WriteLine($"{city} => {weatherInfo.AverageTemperature:F2} => {weatherInfo.Weather}"); } }
/// <summary> /// 更新天气信息 /// </summary> /// <param name="city">城市代码</param> /// <returns></returns> public WeatherInfo UpdateWeather(CityKeyInfo city) { try { if (string.IsNullOrEmpty(city?.CityKey)) { return(null); } HttpWebRequest httpWeather = WebRequest.CreateHttp($"http://zhwnlapi.etouch.cn/Ecalender/api/v2/weather?app_key=99817882&citykey={city.CityKey}"); httpWeather.Timeout = 5000; httpWeather.Method = WebRequestMethods.Http.Get; using (var responseStream = httpWeather.GetResponse().GetResponseStream()) { if (responseStream == null) { return(null); } var weatherData = new StreamReader(new GZipStream(responseStream, CompressionMode.Decompress)); var weatherString = weatherData.ReadToEnd(); var result = JsonConvert.DeserializeObject <WeatherInfo>(weatherString); WeatherInfo = result; WeatherInfoUpdated?.Invoke(); return(WeatherInfo); } } catch { return(null); } }
/// <summary> /// 在此页将要在 Frame 中显示时进行调用。 /// </summary> /// <param name="e">描述如何访问此页的事件数据。Parameter /// 属性通常用于配置页。</param> protected async override void OnNavigatedTo(NavigationEventArgs e) { Current = this; nowColor=GetColor(); background.Background = new SolidColorBrush(nowColor); if (e.NavigationMode == NavigationMode.New) { try { var file = await ApplicationData.Current.LocalFolder.GetFileAsync("save.data");//获取城市记录文件 string str = await FileIO.ReadTextAsync(file); saveWeather = JsonConvert.DeserializeObject<WeatherInfo>(str); await GetWeather(); UpdateInfo(); TimeSpan sp = DateTime.Now - saveWeather.UpdateTime; if (sp.Minutes>30) { await GetWeather(); } } catch (Exception)//第一次打开,文件未创建 { askl = new AskLocation(false); askl.Width = Window.Current.Bounds.Width; askl.Height = Window.Current.Bounds.Height; addCity.Child = askl; addCity.IsOpen = true; } } }
/// <summary> /// 设置中更改城市 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void addCity_Closed(object sender, object e) { if (askl.Result == true)//点确认关闭设置 { if (saveWeather == null)//第一次打开程序 { saveWeather = new WeatherInfo(askl.outCity.Code); await ApplicationData.Current.LocalFolder.CreateFileAsync("save.data"); } saveWeather.Cityid = askl.outCity.Code; //await GetWeather(); } }
public void Parse() { weatherInfo = new WeatherInfo(currentDoc); }
public WeatherLocationsBindingSource(WeatherInfo info) { locations = info.LocationNameToLocationInfoMapping.Keys.ToList(); }
/// <summary> /// Update temperature and humidity /// </summary> /// <param name="cityName"></param> private void UpdateForPlace(string cityName) { if (cityName == null) { SetWeatherLabelsError(); return; } UpdateDates(); /// current weather var current = WeatherInfo.CurrentWeather(cityName); if (current == null) { SetWeatherLabelsError(); return; } if (LabelTemperature0 != null) { LabelTemperature0.Content = Math.Ceiling(current.Temp).ToString() + " °C"; } if (LabelHumidity0 != null) { LabelHumidity0.Content = current.Humidity.ToString() + " %"; } /// tommorow's and aftertommorow's weather (average temperature and humidity) using /// data from a five day forecast, one made every 3 hours (total 40 items) var fiveDays = WeatherInfo.FiveDayForecast(cityName); if (fiveDays == null) { SetWeatherLabelsError(); return; } double tommorowTemperature = 0; double tommorowHumidity = 0; double afterTommorowTemperature = 0; double afterTommorowHumidity = 0; /// calculate foreach (var item in fiveDays) { if (item.Date.ToShortDateString() == tommorowDate.Date.ToShortDateString()) { tommorowTemperature += item.Temp; tommorowHumidity += item.Humidity; } else if (item.Date.ToShortDateString() == afterTommorowDate.Date.ToShortDateString()) { afterTommorowTemperature += item.Temp; afterTommorowHumidity += item.Humidity; } } tommorowTemperature /= 8; tommorowHumidity /= 8; afterTommorowTemperature /= 8; afterTommorowHumidity /= 8; /// set label values if (LabelTemperature1 != null) { LabelTemperature1.Content = Math.Ceiling(tommorowTemperature).ToString() + " °C"; } if (LabelHumidity1 != null) { LabelHumidity1.Content = Math.Ceiling(tommorowHumidity).ToString() + " %"; } if (LabelTemperature2 != null) { LabelTemperature2.Content = Math.Ceiling(afterTommorowTemperature).ToString() + " °C"; } if (LabelHumidity2 != null) { LabelHumidity2.Content = Math.Ceiling(afterTommorowHumidity).ToString() + " %"; } }
private void UpdateDateTimes(DateTime dateTime, WeatherInfo weatherInfo = null) { CurrentDateInfos = null; var tempDateInfos = new List<DateInfo>(); if (dateTime.Date != DateTime.Now.Date) { dateTime = new DateTime(dateTime.Year, dateTime.Month, 1); } Lunar lastMouth= new Lunar(dateTime.AddMonths(-1)); Lunar currentMouth = new Lunar(dateTime); Lunar nextMouth = new Lunar(dateTime.AddMonths(1)); DateTime firstDayOfMouth = dateTime.AddDays(-dateTime.Day + 1); DateTime lastDayOfLastMouth = dateTime.AddDays(-dateTime.Day); int startDay = (int)firstDayOfMouth.DayOfWeek; int daysOfMounth = (firstDayOfMouth.AddMonths(1) - firstDayOfMouth).Days; if (startDay == 0) startDay = 7; DateTime startDate = firstDayOfMouth.AddDays(1 - startDay); DateTime endDate = startDate.AddDays(41); for (int i = 0; i < 35; i++) { var day = startDate.AddDays(i); Lunar mouth = null; var ob = lastMouth.GetOBOfDay(day); if (ob != null) mouth = lastMouth; else { ob = currentMouth.GetOBOfDay(day); if (ob != null) mouth = currentMouth; else { ob = nextMouth.GetOBOfDay(day); if (ob != null) mouth = nextMouth; } } var dateInfo = new DateInfo() { DateTime = day, CurrentDate = dateTime, OB = ob, Lunar = mouth }; switch ((dateInfo.DateTime.Date - DateTime.Now.Date).Days) { case -1: dateInfo.Weather = weatherInfo?.YesterdayWeather; break; case 0: dateInfo.Weather = weatherInfo?.TodayWeather; break; case 1: dateInfo.Weather = weatherInfo?.TomorrowWeather; break; case 2: dateInfo.Weather = weatherInfo?.ThirdDayWeather; break; case 3: dateInfo.Weather = weatherInfo?.FourthDayWeather; break; case 4: dateInfo.Weather = weatherInfo?.FifthDayWeather; break; case 5: dateInfo.Weather = weatherInfo?.SixthDayWeather; break; } tempDateInfos.Add(dateInfo); } if (startDate.AddDays(35).Month == dateTime.Month) { MouthMargin = ExtendMargin; for (int i = 0; i < 7; i++) { var day = firstDayOfMouth.AddDays(i + 36 - startDay); Lunar mouth = null; var ob = lastMouth.GetOBOfDay(day); if (ob != null) mouth = lastMouth; else { ob = currentMouth.GetOBOfDay(day); if (ob != null) mouth = currentMouth; else { ob = nextMouth.GetOBOfDay(day); if (ob != null) mouth = nextMouth; } } var dateInfo = new DateInfo() { DateTime = day, CurrentDate = dateTime, OB = ob, Lunar = mouth }; switch ((dateInfo.DateTime.Date - DateTime.Now.Date).Days) { case -1: dateInfo.Weather = weatherInfo?.YesterdayWeather; break; case 0: dateInfo.Weather = weatherInfo?.TodayWeather; break; case 1: dateInfo.Weather = weatherInfo?.TomorrowWeather; break; case 2: dateInfo.Weather = weatherInfo?.ThirdDayWeather; break; case 3: dateInfo.Weather = weatherInfo?.FourthDayWeather; break; case 4: dateInfo.Weather = weatherInfo?.FifthDayWeather; break; case 5: dateInfo.Weather = weatherInfo?.SixthDayWeather; break; } tempDateInfos.Add(dateInfo); CalendarRows = 6; } IsExtendedMonth = true; } else { MouthMargin = NormalMargin; CalendarRows = 5; IsExtendedMonth = false; } CurrentDateInfos = tempDateInfos; }
/// <summary> /// 更新天气信息 /// </summary> /// <param name="searchString">城市名称或城市代码</param> /// <param name="searchType">查询类型</param> /// <returns></returns> public WeatherInfo UpdateWeather(string searchString, SearchType searchType = SearchType.CityName) { try { HttpWebRequest httpWeather; switch (searchType) { case SearchType.CityName: httpWeather = WebRequest.CreateHttp($"http://wthrcdn.etouch.cn/weather_mini?city={searchString.TrimEnd('市')}"); break; case SearchType.CityKey: httpWeather = WebRequest.CreateHttp($"http://wthrcdn.etouch.cn/weather_mini?citykey={searchString}"); break; default: return null; } httpWeather.Timeout = 5000; httpWeather.Method = WebRequestMethods.Http.Get; using (var responseStream = httpWeather.GetResponse().GetResponseStream()) { if (responseStream == null) return null; var weatherData = new StreamReader(new GZipStream(responseStream, CompressionMode.Decompress)); var weatherString = weatherData.ReadToEnd().Replace("fl", "fengli").Replace("fx", "fengxiang"); var result = JsonConvert.DeserializeObject<WeatherHelper>(weatherString); Description = result.Description; Status = result.Status; WeatherInfo = result.WeatherInfo; if (WeatherInfo.YesterdayWeather != null) WeatherInfo.YesterdayWeather.DateTime = DateTime.Now.AddDays(-1); if (WeatherInfo.TodayWeather != null) WeatherInfo.TodayWeather.DateTime = DateTime.Now; if (WeatherInfo.TomorrowWeather != null) WeatherInfo.TomorrowWeather.DateTime = DateTime.Now.AddDays(1); if (WeatherInfo.ThirdDayWeather != null) WeatherInfo.ThirdDayWeather.DateTime = DateTime.Now.AddDays(2); if (WeatherInfo.FourthDayWeather != null) WeatherInfo.FourthDayWeather.DateTime = DateTime.Now.AddDays(3); if (WeatherInfo.FifthDayWeather != null) WeatherInfo.FifthDayWeather.DateTime = DateTime.Now.AddDays(4); if (WeatherInfo.SixthDayWeather != null) WeatherInfo.SixthDayWeather.DateTime = DateTime.Now.AddDays(5); WeatherInfoUpdated?.Invoke(); return WeatherInfo; } } catch { return null; } }
public string GetWeather(string province, string city, string county, out string url,out string weather) { //{"weatherinfo":{"city":"河源","cityid":"101281201","temp":"7.1","WD":"东北风","WS":"小于3级","SD":"40%","AP":"1018.7hPa","njd":"暂无实况","WSE":"<3","time":"23:10","sm":"5","isRadar":"0","Radar":""}} url = this.GetUrl(province, city, county, 1); weather = ""; string Text = ""; string TextDetail = ""; HttpWebRequest request; HttpWebResponse response = null; Stream streamReceive; StreamReader streamReader; #region 获取当前天气实时数据 try { request = (HttpWebRequest)WebRequest.Create(this.GetUrl(province, city, county, 0)); request.Timeout = 8000; request.Headers.Set("Pragma", "no-cache"); //HttpWebResponse response = null; try { response = (HttpWebResponse)request.GetResponse(); } catch (WebException) { //this.notifyIcon1.ShowBalloonTip(3000, Application.ProductName, "从网络获取数据时出现错误:" + err.Message, ToolTipIcon.Info); throw new ApplicationException("获取当前天气详细数据失败!\n"); } streamReceive = response.GetResponseStream(); streamReader = new StreamReader(streamReceive); string strTemp = streamReader.ReadToEnd(); if (response != null) response.Close(); int infoStart = strTemp.IndexOf("{\"weatherinfo\":{\"", 0); int infoEnd = strTemp.IndexOf("\"}}", infoStart); string strInfo = strTemp.Substring(infoStart + 17, infoEnd - infoStart - 17); //city":"河源","cityid":"101281201","temp":"7.1","WD":"东北风","WS":"小于3级","SD":"40%","AP":"1018.7hPa","njd":"暂无实况","WSE":"<3","time":"23:10","sm":"5","isRadar":"0","Radar":" WeatherInfo info = new WeatherInfo(); if (!info.getWeatherInfo(strInfo)) throw new ApplicationException("获取当前天气详细数据失败!\n"); Text += "时间:" + info.time + "\n"; Text += "气温:" + info.temp + "\n"; Text += "湿度:" + info.SD + "\n"; Text += "风向:" + info.WD + "\n"; Text += "风力:" + info.WS + (info.sm == "暂无实况" ? "" : "[" + info.sm + "]") + "\n"; } catch (Exception) { Text = "获取当前天气详细数据失败!\n"; } #endregion #region 获取未来几天天气情况 try { request = (HttpWebRequest)WebRequest.Create(url); request.Timeout = 8000; request.Headers.Set("Pragma", "no-cache"); try { response = (HttpWebResponse)request.GetResponse(); } catch (WebException) { //this.notifyIcon1.ShowBalloonTip(3000, Application.ProductName, "获取未来几天天气信息失败:\n" + err.Message, ToolTipIcon.Info); TextDetail = "获取未来几天天气信息失败!"; } streamReceive = response.GetResponseStream(); streamReader = new StreamReader(streamReceive, Encoding.GetEncoding("UTF-8")); string strTemp = streamReader.ReadToEnd(); if (response != null) response.Close(); int detailStart = strTemp.IndexOf("<!--day 1-->", 0) + 12; int detailEnd = strTemp.IndexOf("<!--day 4-->", detailStart); string strWeb = strTemp.Substring(detailStart, detailEnd - detailStart); WebBrowser webb = new WebBrowser(); webb.Navigate("about:blank"); HtmlDocument htmldoc = webb.Document.OpenNew(true); htmldoc.Write(strWeb); HtmlElementCollection htmlTR = htmldoc.GetElementsByTagName("tr"); string strDay = "今日"; bool d1 = false; bool d2 = false; foreach (HtmlElement tr in htmlTR) { string strDate = ""; string strDayNight = ""; string strWeather = ""; string strTemperature = ""; string strWind = ""; string strImg = ""; if (tr.GetElementsByTagName("td").Count == 7) { strDate = tr.GetElementsByTagName("td")[0].InnerText.Trim(); strDayNight = tr.GetElementsByTagName("td")[1].InnerText.Trim(); strImg = tr.GetElementsByTagName("td")[2].InnerHtml.Replace("<A href=\"http://www.weather.com.cn/static/html/legend.shtml\"", "").Replace("target=_blank>", "").Replace("</A>", "").Replace("\">", "").Replace("<IMG src=\"/m2/i/icon_weather/29x20/", "").Replace(" ", ""); strWeather = tr.GetElementsByTagName("td")[3].InnerText.Trim(); strTemperature = tr.GetElementsByTagName("td")[4].InnerText.Trim(); strWind = tr.GetElementsByTagName("td")[6].InnerText.Trim(); strDay = strDate.Substring(0, strDate.Length - 3); } else { strDayNight = tr.GetElementsByTagName("td")[0].InnerText.Trim(); strImg = tr.GetElementsByTagName("td")[1].InnerHtml.Replace("<A href=\"http://www.weather.com.cn/static/html/legend.shtml\"", "").Replace("target=_blank>", "").Replace("</A>", "").Replace("\">", "").Replace("<IMG src=\"/m2/i/icon_weather/29x20/", "").Replace(" ", ""); strWeather = tr.GetElementsByTagName("td")[2].InnerText.Trim(); strTemperature = tr.GetElementsByTagName("td")[3].InnerText.Trim(); strWind = tr.GetElementsByTagName("td")[5].InnerText.Trim(); } if (!d1) { //if (strDayNight.IndexOf("白") > -1) //{ // //weather = strDay + "|" + strDayNight + "|D" + strWeather; // weather = "D" + strWeather; //} //else //{ // //weather = strDay + "|" + strDayNight + "|N" + strWeather; // weather = "N" + strWeather; //} //weather += "|" + strImg; weather = strImg; d1 = true; } else if (!d2) { //if (strDayNight.IndexOf("白") > -1) //{ // //weather += "|" + strDay + "|" + strDayNight + "|D" + strWeather; // weather += "|D" + strWeather; //} //else //{ // //weather += "|" + strDay + "|" + strDayNight + "|N" + strWeather; // weather += "|N" + strWeather; //} //weather += "|" + strImg; weather += "|" + strImg; d2 = true; } TextDetail += strDay + "|" + strDayNight + "|" + strWeather + "|" + strTemperature.Substring(2).Trim() + "|" + strWind + "\n"; } webb.Dispose(); } catch (Exception) { TextDetail = "获取未来几天天气信息失败!"; } #endregion return Text + "\n" + TextDetail; }