private static CityWeather GetWeatherFromCity(string city) { city = WebUtility.UrlEncode(city); string url = string.Format("http://api.openweathermap.org/data/2.5/weather?q={0}&units=imperial", city); WebRequest request = WebRequest.Create(url); WebResponse response = request.GetResponse(); using (var streamReader = new StreamReader(response.GetResponseStream())) { string responseString = streamReader.ReadToEnd(); Console.WriteLine(responseString); JObject joResponse = JObject.Parse(responseString); JObject main = (JObject)joResponse["main"]; double temp = (double) main["temp"]; JObject weather = (JObject)joResponse["weather"][0]; string description = (string) weather["description"]; string cityName = (string) joResponse["name"]; Console.WriteLine(string.Format("temp is: {0}", temp)); CityWeather cityWeather = new CityWeather(temp, description, cityName); return cityWeather; } }
public void ShouldGetWeatherForCities() { // Arrange var cities = new List <string> { "Kiev", "Vilnius", "Riga" }; var weather = new CityWeather { City = "Kiev", Precipitation = 2, Temperature = 2, Weather = "Test" }; var httpMessageHandler = new FakeHttpMessageHandler(SetupResponseMessage(System.Net.HttpStatusCode.OK, weather)); var client = new HttpClient(httpMessageHandler); // Sut var sut = new WeatherHttpClientBuilder().WithHttpClient(client).Build(); // Act var result = sut.GetWeatherFor(cities).Result; // Assert var cityList = result.ToList(); Assert.IsTrue(cityList.Count == 3); }
public void ValidateTheCityWeather() { HttpWeatherClient weatherClient = new HttpWeatherClient(serviceUrl, serviceAppId); CityWeather resultWeather = weatherClient.GetCityWeather("CA", "Toronto"); Assert.Equal("Toronto", resultWeather.name); }
private async Task UpdateWeatherDataAsync() { try { await _unitOfWork.BeginTransactionAsync(); var allCities = _cityRepository.Query().ToAsyncEnumerable(); await foreach (var city in allCities) { var cityCurrentWeather = await _weatherProvider.GetWeatherDataByCityNameAsync(city.Name); if (cityCurrentWeather == null) { continue; } var cityWeather = new CityWeather(city.Id, cityCurrentWeather.Date, cityCurrentWeather.Temperature); await _cityWeatherRepository.AddAsync(cityWeather); } await _unitOfWork.EndTransactionAsync(); } catch (Exception) { await _unitOfWork.EndTransactionAsync(false); } }
private CityWeather GetExampleCityWeather() { string cityWeatherJson = "{\"coord\":{\"lon\":-0.1257,\"lat\":51.5085},\"weather\":[{\"id\":802,\"main\":\"Clouds\",\"description\":\"scattered clouds\",\"icon\":\"03d\"}],\"base\":\"stations\",\"main\":{\"temp\":22.77,\"feels_like\":22.67,\"temp_min\":20.55,\"temp_max\":23.94,\"pressure\":1024,\"humidity\":60},\"visibility\":10000,\"wind\":{\"speed\":0.45,\"deg\":281,\"gust\":2.24},\"clouds\":{\"all\":40},\"dt\":1623078332,\"sys\":{\"type\":2,\"id\":2019646,\"country\":\"GB\",\"sunrise\":1623037511,\"sunset\":1623096831},\"timezone\":3600,\"id\":2643743,\"name\":\"London\",\"cod\":200}"; CityWeather cityWeather = JsonSerializer.Deserialize <CityWeather>(cityWeatherJson); return(cityWeather); }
void LoadWeatherPicture(CityWeather cityWeatherInfo) { this.chartControl1.Series[0].DataSource = cityWeatherInfo.Forecast; lbCity.Text = cityWeatherInfo.City; lbTemperature.Text = cityWeatherInfo.Weather.GetTemperatureString(actualMeasureUnits); peWeatherIcon.LoadAsync(cityWeatherInfo.WeatherIconPath); }
public async Task <CityWeather> GetDetailsByCityName(string cityName) { HttpClient client = ServiceClient.GetClient(); string responseResult = string.Empty; string requestUrl = $"{GlobalSettings.Url}{cityName}{GlobalSettings.ApplicationId}"; HttpResponseMessage response; try { response = await client.GetAsync(requestUrl); if (response.StatusCode == System.Net.HttpStatusCode.OK) { responseResult = await response.Content.ReadAsStringAsync(); } } catch (Exception ex) { string strErrorMessage = ex.Message; } CityWeather cityWeather = JsonConvert.DeserializeObject <CityWeather>(responseResult); return(cityWeather); }
public void Update(CityWeather weather) { _weather = weather; OnPropertyChanged(() => Temperature); OnPropertyChanged(() => Description); }
void cityWeatherInfo_ForecastUpdated(object sender, EventArgs e) { CityWeather cityWeatherInfo = sender as CityWeather; Action <CityWeather> del = LoadWeatherPicture; BeginInvoke(del, cityWeatherInfo); }
public async void Write(CityWeather weather) { if (weather.IsValid) { try { var cityRepository = _repositoryFactory.GetRepository <City>(); var cityId = (await cityRepository.AddOrUpdateAsync(new City() { Name = weather.CityName })).Id; var weatherRepository = _repositoryFactory.GetRepository <Weather>(); await weatherRepository.AddOrUpdateAsync(new Weather() { CityId = cityId, MaxTemperature = weather.MaxTemperature, MinTemperature = weather.MinTemperature, Day = DateTime.Today.AddDays(1) }); _logger.Info($"Data: {weather} added"); } catch (Exception e) { _logger.Error(e, $"Error with data writing: {weather}"); } } }
public static async Task <CityWeather> GetWeather(string cityName) { string key = "b7f10a8868ba2c83b0b49eff391c7f04"; string queryString = "http://api.openweathermap.org/data/2.5/weather?q=" + cityName + "&APPID=" + key + "&units=metric"; //Make sure developers running this sample replaced the API key if (key == "YOUR API KEY HERE") { throw new ArgumentException("You must obtain an API key from openweathermap.org/appid and save it in the 'key' variable."); } dynamic results = await DataService.GetDataFromService(queryString).ConfigureAwait(false); if (results["weather"] != null) { CityWeather weather = new CityWeather(); weather.Title = (string)results["name"]; weather.Temperature = (string)results["main"]["temp"] + " C"; weather.Wind = (string)results["wind"]["speed"] + " mph Direction: " + DegreesToCardinal((double)results["wind"]["deg"]); return(weather); } else { return(null); } }
private async Task <CityWeather> GetWeatherForSingleCity(string city) { CityWeather weather = null; try { var cityWeatherUrl = String.Format(_httpOptions.WeatherUrl, city); var url = cityWeatherUrl; var response = await _client.GetAsync(url).ConfigureAwait(false); if (response.IsSuccessStatusCode) { var json = await response.Content.ReadAsStringAsync(); return(JsonConvert.DeserializeObject <CityWeather>(json)); } else { _logger.LogError("Fetching city weather: response for city {0} is not successful. Response: {1}.", city, response.ReasonPhrase); } } catch (HttpRequestException ex) { _logger.LogError("Fetching city weather: request for city {0} failed. Exception: {1}", city, ex.Message); } catch (Exception ex) { _logger.LogError("Something went wrong. Exception: {0}", ex.Message); } return(weather); }
public async Task <ActionResult> Index(CityWeather cityWeather) { var appid = "d71a2d1f949793c83d9b8a3697d9d025"; var baseUrl = $"http://api.openweathermap.org/data/2.5/weather?q={cityWeather.CityName},{cityWeather.CountryAbbreviation}&APPID={appid}"; HttpClient httpClient = new HttpClient(); /* HttpResponseMessage httpResponseMessage = await httpClient.GetAsync(baseUrl); * httpResponseMessage.EnsureSuccessStatusCode(); * var data = await httpResponseMessage.Content.ReadAsStringAsync();*/ string data = await httpClient.GetStringAsync(baseUrl); var deserialize = JsonConvert.DeserializeObject <Example>(data); WeatherInfo weatherInfo = new WeatherInfo { CityName = deserialize.name, Weather = deserialize.weather[0].description, Temperature = deserialize.main.temp, TemperatureMin = deserialize.main.temp_min, TemperatureMax = deserialize.main.temp_max }; return(View("ShowWeatherDetail", weatherInfo)); }
private static CityWeather GetWeatherFromCity(string city) { city = WebUtility.UrlEncode(city); string url = string.Format("http://api.openweathermap.org/data/2.5/weather?q={0}&units=imperial", city); WebRequest request = WebRequest.Create(url); WebResponse response = request.GetResponse(); using (var streamReader = new StreamReader(response.GetResponseStream())) { string responseString = streamReader.ReadToEnd(); Console.WriteLine(responseString); JObject joResponse = JObject.Parse(responseString); JObject main = (JObject)joResponse["main"]; double temp = (double)main["temp"]; JObject weather = (JObject)joResponse["weather"][0]; string description = (string)weather["description"]; string cityName = (string)joResponse["name"]; Console.WriteLine(string.Format("temp is: {0}", temp)); CityWeather cityWeather = new CityWeather(temp, description, cityName); return(cityWeather); } }
public static void Main() { var citiesWeather = new Dictionary <string, CityWeather>(); var pattern = new Regex(@"([A-Z][A-Z])(\d{2}\.\d{1,})([a-zA-Z]+)\|"); var input = Console.ReadLine(); while (input != "end") { foreach (Match match in pattern.Matches(input)) { string name = match.Groups[1].Value; var city = new CityWeather() { Temperature = (double.Parse(match.Groups[2].Value)), Weather = match.Groups[3].Value }; citiesWeather[name] = city; } input = Console.ReadLine(); } foreach (var city in citiesWeather.OrderBy(x => x.Value.Temperature)) { Console.WriteLine($"{city.Key} => {city.Value.Temperature:f2} => {city.Value.Weather}"); } }
// GET: WeatherMain public ActionResult WeatherMainView() { PopulateModelsWithData obj = new PopulateModelsWithData(); CityWeather model = new CityWeather(); obj.PopulateTheCityWeatherObject(ref model); return(PartialView(model)); }
public void GetCityWeather() { ApiHandler <CityWeather> apiHandler = new ApiHandler <CityWeather>(); CityWeather cityWeather = apiHandler.GetCityWeather(1275339); //ID of Mumbai City Assert.That(cityWeather.name == "Mumbai"); // Tested that the apiHandler has successfully deserialized the object after api call. }
public WeatherHistoryModel GetWeatherHistory(string city) { city = city.ToLowerInvariant(); var weatherDataManager = new WeatherDataManager(); if (weatherDataManager.IsCityInMonitorList(city)) { List <WeatherInfoEntity> weatherInfo = weatherDataManager.GetWeatherHistory(city); weatherInfo = weatherInfo.OrderByDescending(o => DateTime.Parse(o.Date)).Take(50).OrderBy(o => DateTime.Parse(o.Date)).ToList(); List <double> highTempList = new List <double>(); List <double> lowTempList = new List <double>(); List <string> dateList = new List <string>(); foreach (WeatherInfoEntity entity in weatherInfo) { highTempList.Add(entity.HighTemp); lowTempList.Add(entity.LowTemp); dateList.Add(entity.Date); } return(new WeatherHistoryModel() { City = city, HighTemp = highTempList.ToArray(), LowTemp = lowTempList.ToArray(), Date = dateList.ToArray() }); } else { //Query OpenWeather CityWeather cityWeather = new CityWeather(); Rootobject weatherInfo = cityWeather.GetWeather(city); if (weatherInfo != null) { string today = DateTime.Now.ToString("d"); weatherDataManager.UpdateCityInfoToTable(city, today); WeatherInfoEntity model = new WeatherInfoEntity(city, convertKtoF(weatherInfo.main.temp_max), convertKtoF(weatherInfo.main.temp_min), today); weatherDataManager.UpdateHistoryInfoToTable(model); return(new WeatherHistoryModel() { City = city, HighTemp = new double[] { model.HighTemp }, LowTemp = new double[] { model.LowTemp }, Date = new string[] { today } }); } else { return(null); // error } } }
public static string GetWeatherFromTweet(string tweet) { string city = GetCityFromTweet(tweet); Console.WriteLine(city); CityWeather cityWeather = GetWeatherFromCity(city); return(string.Format("The weather in {0}: {1} and {2}°F", cityWeather.city, cityWeather.description, cityWeather.temp)); }
protected override void InitializeItem(MapItem item, object obj) { CityWeather cityWeather = obj as CityWeather; MapCustomElement element = item as MapCustomElement; if (element == null || cityWeather == null) { return; } element.ImageUri = new Uri(cityWeather.WeatherIconPath); }
private void HandleGerman(ITwitchClient client, IChatCommand command, CityWeather result) { if (result.City == null) { this.SendMessage(client, $"Tut mir leid {command.ChatMessage.UserName}, ich konnte keine Wetterdaten zu {command.ArgumentsAsString} finden."); } else { this.SendMessage(client, $"Wetter in {result.City}: {result.Weather.First().Description}. Es sind gerade {result.Temperatures.Temperature:0.#}°C ({result.Temperatures.FeelsLike:0.#}°C) mit {result.Temperatures.Humidity}% Luftfeuchtigkeit."); } }
private void HandleEnglish(ITwitchClient client, IChatCommand command, CityWeather result) { if (result.City == null) { this.SendMessage(client, $"Sorry {command.ChatMessage.UserName}, I couldn't find any weather data for {command.ArgumentsAsString}"); } else { this.SendMessage(client, $"The weather in {result.City} is {result.Weather.First().Description}. It is {result.Temperatures.Temperature:0.#}°C ({result.Temperatures.FeelsLike:0.#}°C) with {result.Temperatures.Humidity}% humidity."); } }
public void GetVisibility_ValueBelowOneThousand_ReturnInMeters() { var cityWeather = new CityWeather() { Visibility = 0 }; var visibility = cityWeather.GetVisibility(); Assert.Equal("0 m", visibility); }
public void GetVisibility_ValueOverOneThousand_ReturnInKilometers(string expected, int value) { var cityWeather = new CityWeather() { Visibility = value }; var visibility = cityWeather.GetVisibility(); Assert.Equal(expected, visibility); }
public void Test2GetWeatherData() { WeatherDataServiceFactory obj = WeatherDataServiceFactory.Instance; Location location = new Location(); location.city = "Barcelona"; CityWeather tmp = obj.GetWeatherDataService(location); //check if get worked Assert.IsNotNull(tmp); }
public IActionResult AddToCityWeathers([FromBody] CityWeather item) { if (item == null) { return(Ok()); } _context.CityWeathers.Add(item); _context.SaveChanges(); return(CreatedAtAction(nameof(GetCityWeatherItem), new { key = item.Key }, item)); }
public void UpdateWeatherInfo() { CityWeather cityWeather = new CityWeather(); var weatherDataManager = new WeatherDataManager(); string[] allCities = weatherDataManager.GetAllCities(); foreach (string c in allCities) { Thread.Sleep(1000); // sleep 1s to avoid throttle this.QueryOpenWeatherAndUpdateTable(cityWeather, weatherDataManager, c); } }
protected override void HandleInternal(ITwitchClient client, IChatCommand command) { CityWeather result = HttpService.Instance.GetAsync <CityWeather>($"https://api.openweathermap.org/data/2.5/weather?q={command.ArgumentsAsString}&appid={Settings.ApplicationSettings.Default.OpenWeatherMapApiKey}&lang={Settings.ApplicationSettings.Default.OpenWeatherMapApiLang}&units=metric").Result; if (ApplicationSettings.Default.OpenWeatherMapApiLang == "DE") { this.HandleGerman(client, command, result); } else { this.HandleEnglish(client, command, result); } }
public static string GetCountry(this CityWeather weather) { Log.Information("Looking for " + weather.SysData.Country + " short name"); foreach (Countries value in Enum.GetValues(typeof(Countries))) { var foundedShortName = value.GetShortName(); if (foundedShortName.Equals(weather.SysData.Country?.ToUpper())) { return(value.GetDisplayName()); } } return(null); }
public void GetFormattedTemperature_DoubleValue_RoundedValue() { var main = new Main() { Temp = 0.55f }; var cityWeather = new CityWeather() { Main = main }; Assert.Equal("0.6", cityWeather.GetFormattedTemperature()); }
/// <summary> /// 获取城市天气详情信息 /// </summary> /// <param name="cityId">天气城市代号</param> /// <returns>城市天气详情信息</returns> public CityWeather GetCityWeather(string cityId) { string getUrl = string.Format("http://wthrcdn.etouch.cn/WeatherApi?citykey={0}", cityId); string weatherXml = SimulateRequest.HttpClientGet(getUrl, true); if (string.IsNullOrWhiteSpace(weatherXml)) { throw new WeatherException(-200, "请求到的天气数据Xml为空!"); } CityWeather cityWeather = XmlConvert.DeserializeObject <CityWeather>(weatherXml); return(cityWeather); }