public void OnNavigatedTo(NavigationParameters parameters) { if (parameters.ContainsKey("WeatherItemInfo")) { WeatherItem = (WeatherItem)parameters["WeatherItemInfo"]; } }
public void TestWeather() { //add park so we have a park code to test with _db.AddNewParkItem(_park); WeatherItem weather = new WeatherItem { FiveDayForecast = 5, Forecast = "rain", High = 100, Low = 30, ParkCode = "CASH" }; // Tests add weather bool successful = _db.AddWeatherItem(weather); Assert.IsTrue(successful, "Weather not successfully added"); //Tests get weather by code int count = _db.GetWeatherByCode(_park.ParkCode).Count; Assert.IsTrue(count >= 1, "Did not return weather"); foreach (var item in _db.GetWeatherByCode(_park.ParkCode)) { Assert.AreEqual(weather.FiveDayForecast, item.FiveDayForecast, "Five day forecast did not match"); Assert.AreEqual(weather.Forecast, item.Forecast, "Forecast did not match"); Assert.AreEqual(weather.High, item.High, "High did not match"); Assert.AreEqual(weather.Low, item.Low, "Low did not match"); Assert.AreEqual(weather.ParkCode, item.ParkCode, "Park Code did not match"); } }
public async Task <ActionResult <WeatherItem> > PostTodoItem(WeatherItem weatherItem) { _context.WeatherItems.Add(weatherItem); await _context.SaveChangesAsync(); return(CreatedAtAction(nameof(GetWeatherItem), new { id = weatherItem.Id }, weatherItem)); }
public async Task <IActionResult> PutWeatherItem(long id, WeatherItem weatherItem) { if (id != weatherItem.Id) { return(BadRequest()); } _context.Entry(weatherItem).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!WeatherItemExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public async Task <ActionResult <WeatherItem> > Get(string searchString) { var weatherItem = await _weatherService.GetWeatherByCityAsync(searchString); if (weatherItem == null) { return(NotFound()); } var result = new WeatherItem { Id = weatherItem.Id, Date = weatherItem.Date, Temperature = weatherItem.Temperature, Wind = weatherItem.Wind, Humidity = weatherItem.Humidity, Location = new Location() { Id = weatherItem.LocationId, City = weatherItem.Location.City, ZipCode = weatherItem.Location.ZipCode } }; return(result); }
private void SetWeatherItem(WeatherItem item) { _weather = item; var path = ""; if (ThemeSelectorService.Theme == ElementTheme.Light) { path = "ms-appx:///Assets/WeatherIconsBlack/"; } else { path = "ms-appx:///Assets/WeatherIconsWhite/"; } var iconFilename = _weather.Icon + ".svg"; var iconFilePath = Path.Combine(path, iconFilename); SvgImageSource source = new SvgImageSource(new Uri(iconFilePath)); weatherIconImage.Source = source; var tempList = _weather.Temp.Split('.'); tempTextBlock.Text = tempList[0] + " \u00B0C"; pressureTextBlock.Text = _weather.Pressure + " hPa"; windSpeedTextBlock.Text = "Wind speed: " + _weather.Wind_speed + " m/s"; }
/// <summary> /// Read the passed in parameter /// </summary> /// <param name="year">The current year</param> /// <returns></returns> public List <WeatherItem> ReadFullYear(int year) { // file path string weatherData = AppDomain.CurrentDomain.BaseDirectory + $"WeatherPondData\\Environmental_Data_Deep_Moor_{year}.txt"; // read the lines from the text file List <string> lines = File.ReadAllLines(weatherData).ToList(); // Setup a list of weatherItems List <WeatherItem> weatherItems = new List <WeatherItem>(); foreach (string line in lines) { // we don't display the first line (the one which starts with 'date') if (!line.StartsWith("date")) { string[] entries = line.Split(Whitespace); WeatherItem weatherItem = new WeatherItem(); weatherItem.Date = entries[0]; weatherItem.Time = entries[1]; // parse the barometric pressure to the type double double barometricPress = 0; double.TryParse(entries[3], out barometricPress); // when the parsing works we associate the value with the weather item weatherItem.BarometricPress = barometricPress; weatherItems.Add(weatherItem); } } return(weatherItems); }
private async void NavToMoreInfoPage(WeatherItem weatherItem) { var navParams = new NavigationParameters(); navParams.Add("WeatherItemInfo", weatherItem); await _navigationService.NavigateAsync("MoreInfoPage", navParams); }
private void DeleteItem(WeatherItem weatherItem) { var navParams = new NavigationParameters(); navParams.Add("WeatherItemInfo", weatherItem); WeatherCollection.Remove(weatherItem); }
public WeatherItem GetWeatherApi(string city) { WebClient webclient = new WebClient(); string url = string.Format("http://api.openweathermap.org/data/2.5/weather?q=" + city + "&units=metric" + Const.ApiWeatherKey); string weatherjson = webclient.DownloadString(url); WeatherItem weatheritem = JsonConvert.DeserializeObject <WeatherItem>(weatherjson); return(weatheritem); }
public void TestRemoveWeatherItemCommandRemovesWeatherItemFromCollection() { var weatherItemToDelete = new WeatherItem(); weatherItemToDelete.Name = "San Marcos"; mainPageViewModel.WeatherCollection.Add(weatherItemToDelete); mainPageViewModel.RemoveWeatherItemCommand.Execute(weatherItemToDelete); CollectionAssert.DoesNotContain(mainPageViewModel.WeatherCollection, weatherItemToDelete); }
/// <summary> /// 天气预报中的 预报信息列表 点击事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void WeatherForecastListView_SelectionChanged(object sender, SelectionChangedEventArgs e) { WeatherItem weatherItem = this.WeatherForecastListView.SelectedItem as WeatherItem; if (weatherItem == null) { MessageBox.Show("点击的天气暂无信息。"); return; } RendererCharts(weatherItem.areaID, weatherItem.date); TagBtn_Click(this.TagBtn_detail, null); }
public IActionResult Update(string id, [FromBody] WeatherItem weatherItemIn) { var weatherItem = _weatherService.Get(id); if (weatherItem == null) { return(NotFound()); } _weatherService.Update(id, weatherItemIn); return(NoContent()); }
private IEnumerable <WeatherItem> ConvertMetaWeatherItemsToWeatherItems(IEnumerable <ConsolidatedWeather> items) { var weatherItems = new List <WeatherItem>(); foreach (var item in items) { var weatherItem = new WeatherItem { ApplicableDate = item.ApplicableDate.Date, State = item.WeatherStateName, StateAbbreviation = item.WeatherStateAbbr }; weatherItems.Add(weatherItem); } return(weatherItems); }
public static void WUServer(string[] args) { // // Weather update server // Binds PUB socket to tcp://*:5556 // Publishes random weather updates // // Author: metadings // // Prepare our (context and) publisher // using (var context = new ZContext()) using (var publisher = new ZSocket(ZSocketType.PUB)) { string address = "tcp://*:5556"; Console.WriteLine("I: Publisher.Bind'ing on {0}", address); publisher.Bind(address); // Initialize random number generator var rnd = new Random(); while (true) { // Get values that will fool the boss //int zipcode = rnd.Next(99999); int temperature = rnd.Next(-55, +45); var wi = new WeatherItem(); wi.Temperature = temperature; wi.City = "istanbul"; wi.Id = 34; wi.Status = WeatherStatus.Sun; string json = JsonConvert.SerializeObject(wi, Formatting.Indented); // Send message to all subscribers //var update = string.Format("{0:D5} {1}", zipcode, temperature); //var update = string.Format("{0}", temperature); var update = string.Format("72622*{0}", json); using (var updateFrame = new ZFrame(update)) { publisher.Send(updateFrame); } } } }
public PartialViewResult WeatherGadget() { WeatherGadgetViewModel model = new WeatherGadgetViewModel(); var user = UserManager.FindById(User.Identity.GetUserId()); Person person = user.person; WeatherItem weather = GetWeatherApi(person.City); model.Temp = weather.main.temp_min.ToString(); model.City = person.City; model.Speed = weather.wind.speed; model.Humidity = weather.main.humidity; model.Clouds = weather.clouds.all; model.Pressure = weather.main.pressure; string icon = weather.weather[0].icon; model.Picture = GetWeatherSourcePicture(icon); return(PartialView(model)); }
internal async void GetWeatherForLocation() { HttpClient client = new HttpClient(); var uri = new Uri( string.Format( $"https://jsonplaceholder.typicode.com/posts/{LocationEnteredByUser}")); var response = await client.GetAsync(uri); WeatherItem weatherData = null; if (response.IsSuccessStatusCode) { var content = await response.Content.ReadAsStringAsync(); weatherData = WeatherItem.FromJson(content); } WeatherCollection.Add(weatherData); }
internal async void GetWeatherForLocation() { HttpClient client = new HttpClient(); var uri = new Uri( string.Format( $"http://api.openweathermap.org/data/2.5/weather?q={LocationEnteredByUser}&units=imperial&APPID=" + $"{ApiKey.WeatherAPIKey}")); var response = await client.GetAsync(uri); WeatherItem weatherData = null; if (response.IsSuccessStatusCode) { var content = await response.Content.ReadAsStringAsync(); weatherData = WeatherItem.FromJson(content); } WeatherCollection.Add(weatherData); }
public void TestNavToMoreInfoPageCommandNavigateAsyncWithCorrectParameters() { WeatherItem weatherItemToPass = new WeatherItem(); var expectedNavParams = new NavigationParameters(); expectedNavParams.Add("WeatherItemInfo", weatherItemToPass); navigationServiceMock.Setup( ns => ns.NavigateAsync(It.IsAny <string>(), It.IsAny <NavigationParameters>(), It.IsAny <bool?>(), It.IsAny <bool>())); mainPageViewModel.NavToMoreInfoPageCommand.Execute(weatherItemToPass); navigationServiceMock.Verify( ns => ns.NavigateAsync("MoreInfoPage", expectedNavParams, false, true), Times.Once()); }
public IActionResult SaveSettingsScreen(string slideTime, bool clockSlideActive, int clockSlideInterval, bool weatherSlideActive, int weatherSlideInterval, string weatherSlideLocation) { ClockItem clock = _data.GetSingle <ClockItem>(); WeatherItem weather = _data.GetSingle <WeatherItem>(); clock.Active = clockSlideActive; clock.DisplayTime = clockSlideInterval; weather.Active = weatherSlideActive; weather.DisplayTime = weatherSlideInterval; _data.Edit(clock); _data.Edit(weather); _data.SetSettingByName("WeatherLocation", weatherSlideLocation); _data.SetSettingByName("DefaultDisplayTime", slideTime); _data.Commit(); return(Success()); }
internal async void GetWeatherForLocation() { //need Microsoft.Net.Http to use HTTP (and maybe Microsoft.BCL.Build if you're having issues like me) HttpClient client = new HttpClient(); //makes new accesable HTTP client var uri = new Uri( //gets the URI from openweather string.Format( $"http://api.openweathermap.org/data/2.5/weather?q={LocationEnteredByUser}&units=imperial&APPID=" + $"5da8d96113a5c72f1f9836c3c84a6351")); var response = await client.GetAsync(uri); WeatherItem weatherData = null; if (response.IsSuccessStatusCode) { var content = await response.Content.ReadAsStringAsync(); weatherData = WeatherItem.FromJson(content); } WeatherCollection.Add(weatherData); }
public async Task <WeatherItem> GetWeather(int wmo) { var station = stations[wmo]; var wh = await Globals.RequestUrl <WeatherModel>( string.Format(serviceUrl, wmo), HttpMethod.Get, headers : new Dictionary <string, string>() { { "User-Agent", "Milad/1.0.0" }, { "Accept", "*/*" } }); var res = new WeatherItem() { Wmo = wmo, Station = station, Data = wh.Observations.WeatherData }; return(res); }
private string FormatWeather(WeatherItem _item) { StringBuilder stringBuilder = new StringBuilder(); string pressureTrend = _item.Atmosphere.Rising == "0" ? "steady" : _item.Atmosphere.Rising == "1" ? "rising" : "falling"; stringBuilder.AppendLine( $"weather report for {_item.WLocation.City}, {_item.WLocation.Country} (Lat: {_item.Location.Latitude}, Long: {_item.Location.Longitude})"); stringBuilder.AppendLine("current conditions:"); // forecast [0] is the forecast for the current day stringBuilder.AppendLine($"\ttemperature: {_item.CurrentCondition.Temperature} °{_item.Units.Temperature}, Min: {_item.Forecasts[0].LowTemperature} °{_item.Units.Temperature}, Max: {_item.Forecasts[0].HighTemperature} °{_item.Units.Temperature}"); stringBuilder.AppendLine($"\twind: {_item.Wind.Speed} {_item.Units.Speed}, direction: {_item.Wind.Direction}°"); stringBuilder.AppendLine($"\tatmospheric pressure: {_item.Atmosphere.Pressure} {_item.Units.Pressure}, trend: {pressureTrend}"); stringBuilder.AppendLine("forecast:"); stringBuilder.AppendLine( $"\t{_item.Forecasts[1].Day}, {_item.Forecasts[1].Date}: {_item.Forecasts[1].HighTemperature}/{_item.Forecasts[1].LowTemperature} °{_item.Units.Temperature}"); stringBuilder.AppendLine( $"\t{_item.Forecasts[2].Day}, {_item.Forecasts[2].Date}: {_item.Forecasts[2].HighTemperature}/{_item.Forecasts[2].LowTemperature} °{_item.Units.Temperature}"); stringBuilder.AppendLine( $"\t{_item.Forecasts[3].Day}, {_item.Forecasts[3].Date}: {_item.Forecasts[3].HighTemperature}/{_item.Forecasts[3].LowTemperature} °{_item.Units.Temperature}"); return(stringBuilder.ToString()); }
internal async void GetWeatherForLocation() { Analytics.TrackEvent("GetWeatherButtonTapped", new Dictionary <string, string> { { "WeatherLocation", LocationEnteredByUser }, }); HttpClient client = new HttpClient(); var uri = new Uri( string.Format( $"http://api.openweathermap.org/data/2.5/weather?q={LocationEnteredByUser}&units=imperial&APPID=" + $"{ApiKeys.WeatherKey}")); var response = await client.GetAsync(uri); WeatherItem weatherData = null; if (response.IsSuccessStatusCode) { var content = await response.Content.ReadAsStringAsync(); weatherData = WeatherItem.FromJson(content); } WeatherCollection.Add(weatherData); }
private async Task GetWeatherReportForPosition() { var units = GetSelectedTemperatureUnit(); // create a new weather report WeatherReport report = m_weatherProvider.CreateReport(tbLocation.Text); report.TemperatureUnit = units; try { // query the report to receive the newest weather forecasts WeatherItem weatherItem = await report.Query(); WeatherBox.Text = FormatWeather(weatherItem); } catch (InvalidWoeidException _e) // WOEID unknown { WeatherBox.Text = _e.Message; } catch (WeatherParsingException _e) // server did not respond correctly { MessageBox.Show("Error while parsing the server response!", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } }
/* * public partial class WeatherItem * { * public static WeatherItem FromJson(string json) => JsonConvert.DeserializeObject<WeatherItem>(json, Converter.Settings); * } */ public static string ToJson(this WeatherItem self) => JsonConvert.SerializeObject(self, Converter.Settings);
protected override async Task ExecuteAsync(CancellationToken cancellationToken) { _logger.LogInformation("Screen Background Service is starting."); using (var scope = _scopeFactory.CreateScope()) { _data = scope.ServiceProvider.GetRequiredService <IVolatileDataService>(); IEnumerable <Item> activeCustomItems = _data.GetAllActive().Where(i => !(i is RSSItem || i is ClockItem || i is WeatherItem)); IEnumerable <Item> activeRSSItems = _data.GetAllActive().Where(i => i is RSSItem); activeCustomItems.ToList().Shuffle(); activeRSSItems.ToList().Shuffle(); Item currentItem = activeCustomItems.FirstOrDefault(); Item screenItem = currentItem; Item currentRssItem = null; bool showClock = true; while (!cancellationToken.IsCancellationRequested) { activeCustomItems = _data.GetAllActive() .Where(i => !(i is RSSItem || i is ClockItem || i is WeatherItem)); activeRSSItems = _data.GetAllActive().Where(i => i is RSSItem); try { if (screenItem != null) { // Send item to clients via websockets _logger.LogInformation($"Send item: {(screenItem.Title)}."); //SEND TO CLIENTS await _hubContext.Clients.All.BroadcastSlide(new ScreenItemViewModel(screenItem)); await Task.Delay(TimeSpan.FromSeconds(screenItem.DisplayTime)); } else { await Task.Delay(TimeSpan.FromSeconds(3)); } // Obtain new item Random r = new Random(); ClockItem clock = _data.GetSingle <ClockItem>(); WeatherItem weather = _data.GetSingle <WeatherItem>(); // bool checkIfRSSFeedActive = _data.AnyRssFeedActive(); // bool checkIfRssItemsExist = activeRSSItems.ToList().Count > 0; // bool checkIfRssShow = r.NextBool(25); if (_data.AnyRssFeedActive() && activeRSSItems.ToList().Count > 0 && r.NextBool(25)) { // Toon RSS Item als er actieve RSS feeds zijn en met een (pseudo) kans van 25% currentRssItem = GetNextItem(currentRssItem, activeRSSItems); screenItem = currentRssItem ?? screenItem; } else if (!(screenItem is ClockItem || screenItem is WeatherItem) && r.NextBool(35) && ((showClock && clock.Active) || (!showClock && weather.Active))) { screenItem = showClock ? (Item)clock : weather; showClock = !showClock; } else { currentItem = GetNextItem(currentItem, activeCustomItems); screenItem = currentItem ?? screenItem; } } catch (Exception ex) { _logger.LogError(ex, $"An unexpected error occurred in ScreenBackgroundController."); } } } _logger.LogInformation("Screen Background Service is stopping."); }
public async Task <WeatherItem> GetForecastAsync(IOptions <AppSettings> appSettings) { WeatherItem weatherForecast = new WeatherItem(); string apiKey = appSettings.Value.DarkSkyAPIKey; var darkSky = new DarkSky.Services.DarkSkyService(apiKey); var forecast = await darkSky.GetForecast(51.4557, -2.583, new OptionalParameters { MeasurementUnits = "si" }); if (forecast?.IsSuccessStatus == true) { weatherForecast.CurrentFeelsLikeTemperature = Convert.ToInt32(forecast.Response.Currently.ApparentTemperature); weatherForecast.CurrentSummary = forecast.Response.Currently.Summary; weatherForecast.CurrentTemperature = Convert.ToInt32(forecast.Response.Currently.Temperature); weatherForecast.CurrentIconPath = "/images/" + forecast.Response.Currently.Icon.ToString() + ".svg"; weatherForecast.MinutelySummary = forecast.Response.Minutely.Summary; List <HourData> hourData = new List <HourData>(); foreach (var hour in forecast.Response.Hourly.Data.GetRange(1, 3)) { HourData hdata = new HourData(); hdata.Time = DateTime.ParseExact(hour.DateTime.TimeOfDay.ToString(), "HH:mm:ss", new CultureInfo("en-GB")).ToString("HH:mm"); hdata.Summary = hour.Summary; hdata.Temp = Convert.ToInt32(hour.Temperature); hdata.Icon = "/images/" + hour.Icon.ToString() + ".svg"; hourData.Add(hdata); } weatherForecast.Hour = hourData; List <DayData> dayData = new List <DayData>(); foreach (var day in forecast.Response.Daily.Data.GetRange(0, 4)) { DayData ddata = new DayData(); ddata.Day = DateTime.ParseExact(day.DateTime.Date.ToString(), "dd/MM/yyyy HH:mm:ss", new CultureInfo("en-GB")).ToString("dd.MM yyyy"); ddata.Summary = day.Summary; ddata.Temp = Convert.ToInt32(day.TemperatureLow); ddata.TempLow = Convert.ToInt32(day.TemperatureLow); ddata.TempHigh = Convert.ToInt32(day.TemperatureHigh); ddata.Icon = "images/" + day.Icon.ToString() + ".svg"; dayData.Add(ddata); } weatherForecast.Day = dayData; weatherForecast.Alerts = forecast.Response.Alerts; } else { weatherForecast.CurrentSummary = "No current weather data"; } return(weatherForecast); }
/// <summary> /// 获取天气展示类别的信息 /// </summary> /// <param name="id">城市ID</param> /// <param name="name">城市名字</param> /// <returns></returns> private async Task GetWeatherByCity(int id, string name, string urlcode) { weatherDictionary = null; //先初始化为空。 await weatherHandler.GetWeatherByUrl(urlcode); List <IWeatherMsg> list = weatherHandler.WeatherMsgs; Dictionary <string, object> dic = new Dictionary <string, object>(); List <WeatherItem> weatherLists = new List <WeatherItem>(); WeatherItem weatherItem = new WeatherItem(); if (list.Count == 0) { MessageBox.Show("暂无天气数据"); return; } for (int i = 0; i < list.Count; i++) { if (list[i].flag == 2) //每天的数据 { WeatherDayMsg dayMsg = list[i] as WeatherDayMsg; if (dayMsg.time == DateTime.Today) //今天的数据 { if (string.IsNullOrEmpty(dayMsg.maxTemp)) //如果只有半天数据 { OnlyDayWeatherInfo od = new OnlyDayWeatherInfo(); od.city = name; od.date = dayMsg.time.ToString("MM月dd日"); od.week = dayMsg.time.ToString("dddd"); od.weatherStatus = dayMsg.weatherStatus; od.imgSrc = "Images/night/晚间" + GetWeatherImgSrcByWeatherStatus(dayMsg.weatherStatus); od.temperature = dayMsg.minTemp; od.wind = dayMsg.wind; od.windL = dayMsg.windL; dic.Add("onlyday", od); } else { DayAndNightWeatherInfo dn = new DayAndNightWeatherInfo(); dn.city = name; dn.date = dayMsg.time.ToString("MM月dd日"); dn.week = dayMsg.time.ToString("dddd"); dn.weatherStatus_day = dayMsg.weatherStatus.Split('转')[0].Trim(); dn.weatherStatus_night = dayMsg.weatherStatus.Split('转')[1].Trim(); dn.imgSrc_day = "Images/day/日间" + GetWeatherImgSrcByWeatherStatus(dn.weatherStatus_day); dn.imgSrc_night = "Images/night/晚间" + GetWeatherImgSrcByWeatherStatus(dn.weatherStatus_night); dn.maxTemperature = dayMsg.maxTemp; dn.minTemperature = dayMsg.minTemp; dn.wind_day = dayMsg.wind.Split('转')[0].Trim(); dn.wind_night = dayMsg.wind.Split('转')[1].Trim(); dn.windL_day = dayMsg.windL.Split('转')[0].Trim(); dn.windL_night = dayMsg.windL.Split('转')[1].Trim(); dic.Add("dayandnight", dn); } } else //之后7几天的数据 { weatherItem = new WeatherItem(); weatherItem.areaID = id; weatherItem.date = dayMsg.time.ToString("MM月dd日"); weatherItem.maxTemperature = dayMsg.maxTemp; weatherItem.minTemperature = dayMsg.minTemp; string weatherStatus = dayMsg.weatherStatus.Split('转')[0].Trim(); weatherItem.weatherStatus = weatherStatus; weatherItem.imageSrc = "../Images/night/晚间" + GetWeatherImgSrcByWeatherStatus(weatherStatus); weatherLists.Add(weatherItem); } } } dic.Add("weatherItem", weatherLists); weatherDictionary = dic; }
private void RemoveWeatherItem(WeatherItem itemToDelete) { WeatherCollection.Remove(itemToDelete); }