public async Task <List <DailyForecast> > GetWeekForecast( String cityName) { try { ForecastResponse response = await _client.Forecast.GetByName( cityName, false, MetricSystem.Metric); return(response.Forecast.GroupBy(f => f.From.Date) .Select(grp => new DailyForecast() { Date = grp.Key, Forecasts = grp.Select(ft => new TimeSpanForecast { FromTime = ft.From, ToTime = ft.To, Temperature = ft.Temperature.Value, TemperatureFrom = ft.Temperature.Min, TemperatureTo = ft.Temperature.Max, ImagePath = BuildImagePath(ft.Symbol.Var) }).ToList() }).ToList()); } catch (Exception) { return(null); } }
public void ctrlSearch_Click(object sender, EventArgs e) { WeatherStationClient weather = new WeatherStationClient(); string search = ctrlYourCityName.Text; Dictionary <string, string> dic = new Dictionary <string, string>(); dic.Add("lang", "en"); dic.Add("units", "metric"); dic.Add("mode", "json"); dic.Add("q", search); WeatherResponse res = weather.GetWeather(dic); ForecastResponse Forecast = weather.GetForecast(dic); loWeatherInCity.Text = "Weather in: " + Forecast.City.Name + ", " + Forecast.City.Country; SetUIValues(res); SetNext24Hours(Forecast); DegreesSetup(res); WindSpeedSetup(res); PictureSetup(res, weather); NextFiveDays(Forecast.Analysis); //SunriseSetup(res.SysInfo.Sunrise); //SunsetSetup(res.SysInfo.Sunset); ctrlSunrise.Text = DateSetup(res.SysInfo.Sunrise); ctrlSunset.Text = DateSetup(res.SysInfo.Sunset); }
public static ForecastResponse GetForecast(long id) { var user = UserExistCommand.GetUser(id); if (user.Latitude is null || user.Longitude is null) { return(null); } string response; var url = "https://api.openweathermap.org/data/2.5/forecast?lat=" + Convert.ToString(user.Latitude) + "&lon=" + Convert.ToString(user.Longitude) + "&units=metric&appid=" + Bot.ReadTokenOWM(@"[path].json"); if (!Bot.CheckUrl(url)) { return(null); } HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url); HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream())) { response = streamReader.ReadToEnd(); } ForecastResponse forecastResponse = JsonConvert.DeserializeObject <ForecastResponse>(response); return(forecastResponse); }
public static async Task <ForecastResponse> GetCurrentAsync(double latitude, double longitude, UserCredentials credentials) { var token = await GetToken(credentials); var URL = $"{ApiURL}{latitude.ToString(CultureInfo.InvariantCulture)},{longitude.ToString(CultureInfo.InvariantCulture)}/forecasts"; ForecastResponse forecast = null; try { forecast = await URL .WithOAuthBearerToken(token) .SetQueryParams(new { conditionsType = "standard", blockSize = "1", limit = "1" }) .GetJsonAsync <ForecastResponse>(); } catch (Exception e) { Crashes.TrackError(e); } return(forecast); }
public ForecastViewModel(ForecastResponse forecast) { Cod = forecast.Cod; Message = forecast.Message; Cnt = forecast.Cnt; List = new ObservableCollection <List>(forecast.List); City = forecast.City; }
public override async Task <ForecastResponse> GetWeatherForecasts(Empty request, ServerCallContext context) { var response = new ForecastResponse(); await FD.GetForecastData(); response.Data = Google.Protobuf.ByteString.CopyFrom(FD.ForecastBytes); return(response); }
public static async void Execute(object sender, Telegram.Bot.Args.MessageEventArgs e) { if (!keyboardButton.Contains(e.Message.Text)) { return; } ForecastResponse response = null; var count = 0; switch (e?.Message?.Text) { case "Сейчас": response = GetForecast(e.Message.Chat.Id); count = 0; break; case "На 12 часов": response = GetForecast(e.Message.Chat.Id); count = 4; break; case "На день": response = GetForecast(e.Message.Chat.Id); count = 8; break; case "На три дня": response = GetForecast(e.Message.Chat.Id); count = 24; break; } if (response is null) { SetLocation(e.Message.From.Id); return; } Func <WeatherInfo, string> answer = delegate(WeatherInfo data) { return($"{data.Dt_txt}: <em>температура</em> <b>{data.Main.Temp} ℃</b>, " + $"<em>скорость ветра:</em> <b>{data.Wind.Speed}м/с</b>, " + $"<em>облачность:</em> <b>{data.Clouds.All}%</b>\n\n"); }; string forecast = null; for (var i = 0; i <= count; i++) { forecast += answer(response.List[i]); } await Bot.client.SendTextMessageAsync(e?.Message?.Chat?.Id, forecast, ParseMode.Html); }
private Forecast GetTestForecast() { // Available values: // 30.07.2019 21:00 // 31.07.2019 00:00 return(ForecastResponse.FromJson(TestData.Forecast).Forecasts.Where(forecast => { return forecast.MeasureTime.Equals(new DateTime(2019, 7, 30, 21, 0, 0)); }) .Single()); }
public void SetNext24Hours(ForecastResponse Forecast) { ctrlForecast1.Text = ParseAnalysisObject(Forecast.Analysis[0]); ctrlForecast2.Text = ParseAnalysisObject(Forecast.Analysis[1]); ctrlForecast3.Text = ParseAnalysisObject(Forecast.Analysis[2]); ctrlForecast4.Text = ParseAnalysisObject(Forecast.Analysis[3]); ctrlForecast5.Text = ParseAnalysisObject(Forecast.Analysis[4]); ctrlForecast6.Text = ParseAnalysisObject(Forecast.Analysis[5]); ctrlForecast7.Text = ParseAnalysisObject(Forecast.Analysis[6]); ctrlForecast8.Text = ParseAnalysisObject(Forecast.Analysis[7]); }
public void TestAllProperties(ForecastResponse response) { Assert.IsNotNull(response); Assert.IsNotNull(response.Location); Assert.IsNotNull(response.Location.CityLocation); Assert.IsNotNull(response.Location.TimeZone); Assert.IsNotNull(response.Location.Type); Assert.IsNotNull(response.Meta); Assert.IsNotNull(response.Sun); Assert.IsNotNull(response.Forecast); Assert.IsTrue(response.Forecast.Any()); }
public async Task <ForecastResponse> GetForecastByZipCode(string zipCode) { var data = new ForecastResponse(); if (!int.TryParse(zipCode, out _)) { data.StatusMessage = "Zip Code not provided."; data.StatusCode = 400; return(data); } var response = await _handler.GetForecastByZipAsync(zipCode.Trim()); return(ForecastResponse(data, response)); }
public async Task <ForecastResponse> GetForecastByCity(string city) { var data = new ForecastResponse(); if (string.IsNullOrEmpty(city)) { data.StatusMessage = "City Name not provided."; data.StatusCode = 400; return(data); } var response = await _handler.GetForecastByCityAsync(city.Trim()); return(ForecastResponse(data, response)); }
public void GetReturnsEmptyObjectWhenApiResponseIsEmptyJson() { IForecastProxy forecastProxy = MockRepository.GenerateMock <IForecastProxy>(); int cityId = 12345; ForecastResponse apiresponse = new ForecastResponse("{\"cod\":\"0\"}"); forecastProxy.Expect(x => x.GetForecastByCityId(cityId)).Return(apiresponse); WeatherController controller = new WeatherController(forecastProxy); var response = controller.Get(cityId); Assert.IsNotNull(response); Assert.AreEqual(response, apiresponse); }
public void GetCapturesAllForecastsWhenApiResponseContainsMultipleForecasts() { IForecastProxy forecastProxy = MockRepository.GenerateMock <IForecastProxy>(); int cityId = 2643743; ForecastResponse apiresponse = new ForecastResponse(GetJson()); forecastProxy.Expect(x => x.GetForecastByCityId(cityId)).Return(apiresponse); WeatherController controller = new WeatherController(forecastProxy); var response = controller.Get(cityId); Assert.IsNotNull(response); Assert.AreEqual(response, apiresponse); Assert.AreEqual(7, response.Forecasts.Count); }
/// <summary> /// Gets the weather forecast for a given latitude and longitude /// </summary> /// <param name="lat">Latitude</param> /// <param name="lng">Longitude</param> /// <returns>A ForecastResponse containing forecast data for the given latitude and longitude</returns> public async Task <ForecastResponse> GetForecastAsync(decimal lat, decimal lng) { //Get the gridpoint information for the given latitude and longitude. var redirectResponseText = await webClient.GetAsync($"https://api.weather.gov/points/{ lat.ToString("0.####") },{ lng.ToString("0.####") }"); //Parse the json response dynamic json = JObject.Parse(redirectResponseText); //Get the forecast Url from the response var forecastUrl = (string)json.properties.forecast; //Load the forecast Url var forecastResponseText = await webClient.GetAsync(forecastUrl); //Parse the json response dynamic json2 = JObject.Parse(forecastResponseText); //Instantiate a new ForecastResponse object and fill it with the data received var response = new ForecastResponse() { Periods = new List <ForecastPeriod>(), ElevationInMeters = json2.properties.elevation.value, LastUpdatedDate = json2.properties.updated, Latitude = lat, Longitude = lng }; foreach (dynamic p in json2.properties.periods) { response.Periods.Add(new ForecastPeriod() { Name = p.name, StartTime = p.startTime, EndTime = p.endTime, IsDayTime = p.isDaytime, TemperatureInFahrenheit = p.temperature, WindSpeed = p.windSpeed, WindDirection = p.windDirection, ForecastShort = p.shortForecast, ForecastLong = p.detailedForecast }); } response.RawData = forecastResponseText; return(response); }
public void GetWeatherDescriptionWhenApiResponseContainsDescription() { IForecastProxy forecastProxy = MockRepository.GenerateMock <IForecastProxy>(); int cityId = 2643743; ForecastResponse apiresponse = new ForecastResponse(GetJson()); forecastProxy.Expect(x => x.GetForecastByCityId(cityId)).Return(apiresponse); WeatherController controller = new WeatherController(forecastProxy); var response = controller.Get(cityId); Assert.IsNotNull(response); Assert.AreEqual(response, apiresponse); Assert.AreEqual("Rain", response.Forecasts[0].WeatherList[0].Summary); Assert.AreEqual("light rain", response.Forecasts[0].WeatherList[0].Description); Assert.AreEqual("10d", response.Forecasts[0].WeatherList[0].Icon); }
public static List <WeatherForecast> GetForecastsFromApiResponse(ForecastResponse forecastResponse) { List <WeatherForecast> forecasts = new List <WeatherForecast>(); if (forecastResponse == null) { return(forecasts); } foreach (var forecastResponseItem in forecastResponse.Forecasts) { foreach (var forecastDay in forecastResponseItem.Forecast) { forecasts.Add(GetForecastFromApiResponse(forecastDay)); } } return(forecasts); }
public async Task ReturnEmptyIEnumerableWhenNoMatchFound() { string location = "Karlsruhe,de"; var urlBuilder = CreateFluentUrlProviderWithReturnUrl(); var client = CreateClient(new List <Helper.Maybe <ForecastResponse> >() { new Helper.Maybe <ForecastResponse>(ForecastResponse.FromJson(TestData.ForecastResponseKarlsruhe)) }); var mockQuery = CreateQuery(location); mockQuery.Setup(query => query.IsSatisfiedBy(It.IsAny <Forecast>())) .Returns((Forecast forecast) => false); var serviceUnderTest = new OpenWeatherService(client.Object, urlBuilder.Object); var result = await serviceUnderTest.GetForecasts(mockQuery.Object); Assert.False(result.Any()); }
public async Task ReturnsIEnumerableForGetForecast() { string location = "Karlsruhe,de"; var urlBuilder = CreateFluentUrlProviderWithReturnUrl(); var client = CreateClient(new List <Helper.Maybe <ForecastResponse> >() { new Helper.Maybe <ForecastResponse>(ForecastResponse.FromJson(TestData.ForecastResponseKarlsruhe)) }); var mockQuery = CreateQuery(location); mockQuery.Setup(query => query.IsSatisfiedBy(It.IsAny <Forecast>())) .Returns((Forecast forecast) => forecast.MeasureTime.Equals(new DateTimeOffset(2019, 7, 30, 21, 0, 0, new TimeSpan()))); var serviceUnderTest = new OpenWeatherService(client.Object, urlBuilder.Object); var result = await serviceUnderTest.GetForecasts(mockQuery.Object); Assert.IsAssignableFrom <IEnumerable <ForecastResult> >(result); }
public async Task <IActionResult> ByName(string cityName, int days) { if (cityName == null || days <= 0) { return(BadRequest("Invalid Data Entered")); } try { var apicall = ApiCall.CallAsync <ForecastResponse>($"http://api.weatherapi.com/v1/forecast.json?key={Secret.weatherapikey}&q={HttpUtility.UrlEncode(cityName)}&days={HttpUtility.UrlEncode(days.ToString())}"); ForecastResponse apiresponse = (ForecastResponse)apicall.Result; return(Ok(apiresponse)); } catch (Exception) { return(NotFound()); } }
public void GetReturnsCityObjectWhenApiResponseContainsCityJson() { IForecastProxy forecastProxy = MockRepository.GenerateMock <IForecastProxy>(); int cityId = 2643743; ForecastResponse apiresponse = new ForecastResponse(GetJson()); forecastProxy.Expect(x => x.GetForecastByCityId(cityId)).Return(apiresponse); WeatherController controller = new WeatherController(forecastProxy); var response = controller.Get(cityId); Assert.IsNotNull(response); Assert.AreEqual(response, apiresponse); Assert.AreEqual(2643743, response.City.Id); Assert.AreEqual("London", response.City.Name); Assert.AreEqual("GB", response.City.CountryCode); Assert.AreEqual(51.5085, response.City.Latitude); Assert.AreEqual(-0.1258, response.City.Longitude); }
public void GetTempratureForTheDayWhenApiResponseContainsDailyTempratureForecast() { IForecastProxy forecastProxy = MockRepository.GenerateMock <IForecastProxy>(); int cityId = 2643743; ForecastResponse apiresponse = new ForecastResponse(GetJson()); forecastProxy.Expect(x => x.GetForecastByCityId(cityId)).Return(apiresponse); WeatherController controller = new WeatherController(forecastProxy); var response = controller.Get(cityId); Assert.IsNotNull(response); Assert.AreEqual(response, apiresponse); Assert.AreEqual(17.6, response.Forecasts[0].Temperature.Day); Assert.AreEqual(17.6, response.Forecasts[0].Temperature.Evening); Assert.AreEqual(17.6, response.Forecasts[0].Temperature.Max); Assert.AreEqual(17.6, response.Forecasts[0].Temperature.Max); Assert.AreEqual(14.16, response.Forecasts[0].Temperature.Night); Assert.AreEqual(17.6, response.Forecasts[0].Temperature.Morning); }
private static ForecastResponse ForecastResponse(ForecastResponse data, OpenWeatherMapResponse response) { if (response.StatusCode >= 200 && response.StatusCode < 300) { data.City = response.OpenWeatherMapForecast.City.Name; data.Country = response.OpenWeatherMapForecast.City.Country; IEqualityComparer <ForecastResponse.Data> comparer = KeyEqualityComparer <ForecastResponse.Data> .Using(date => date.Date); data.Forecasts = response.OpenWeatherMapForecast.Forecasts .GroupBy(g => new ForecastResponse.Data { Temperature = g.Main.Temp, WindSpeed = g.Wind.Speed, Humidity = g.Main.Humidity, Weather = g.Weather[0].Main, WeatherIcon = g.Weather[0].Icon, Date = g.Dt.ToLongDateString() }, comparer) .Select(forecast => new ForecastResponse.Data { Temperature = forecast.Key.Temperature, WindSpeed = forecast.Key.WindSpeed, Humidity = forecast.Key.Humidity, Weather = forecast.Key.Weather, WeatherIcon = forecast.Key.WeatherIcon, Date = forecast.Key.Date } ) .ToArray(); data.StatusCode = response.OpenWeatherMapForecast.Cod; data.StatusMessage = "Success"; return(data); } data.StatusMessage = response.Message; data.StatusCode = response.StatusCode; return(data); }
private LocationForecast MapForecastResponse(ForecastResponse openWeatherApiResponse) { var locationForecast = new LocationForecast() { Success = true, ErrorMessage = String.Empty, Location = new ForecastLocation() { Name = openWeatherApiResponse.Location.Name, Latitude = openWeatherApiResponse.Location.Coordinates.Latitude, Longitude = openWeatherApiResponse.Location.Coordinates.Longitude }, FetchTime = DateTime.Now }; foreach (var openWeatherForecast in openWeatherApiResponse.ForecastPoints) { WeatherForecast forecast = new() { Conditions = openWeatherForecast.Conditions.FirstOrDefault()?.main, ConditionsDescription = openWeatherForecast.Conditions.FirstOrDefault()?.description, Temperature = openWeatherForecast.WeatherData.Temperature, Humidity = openWeatherForecast.WeatherData.Humidity, Pressure = openWeatherForecast.WeatherData.pressure * 0.0295301, // Pressure always comes back in millibars, even when imperial requested, ForecastTime = DateTimeOffset.FromUnixTimeSeconds(openWeatherForecast.Date + openWeatherApiResponse.Location.TimezoneOffset).DateTime, CloudCover = openWeatherForecast.Clouds.CloudCover, WindSpeed = openWeatherForecast.Wind.WindSpeed, WindDirectionDegrees = openWeatherForecast.Wind.WindDirectionDegrees, WindDirection = CompassDirection.GetDirection(openWeatherForecast.Wind.WindDirectionDegrees), ExpectedRainfall = (openWeatherForecast.Rain?.RainfallThreeHours ?? 0.0) * 0.03937008, ExpectedSnowfall = (openWeatherForecast.Snow?.SnowfallThreeHours ?? 0.0) * 0.03937008 }; locationForecast.Forecasts.Add(forecast); } return(locationForecast); }
/// <summary> /// Requests the five day forecast. This will retrieve data for the next five days. /// </summary> private void RequestFiveDayForecast() { rest_request = new RestRequest(string.Format("forecast?lat={0}&lon={1}&APPID={2}", strLatitude, strLongitude, API_KEY)); var response = rest_client.Execute(rest_request); if (string.IsNullOrWhiteSpace(response.Content) || response.StatusCode != System.Net.HttpStatusCode.OK) { LoadLocalSingleDay(); } else { try { objForecastRestResponse = JsonConvert.DeserializeObject <ForecastResponse>(response.Content); } catch (Exception ex) { error_logger.LogError("RequestFiveDayForecast", ex.GetType().FullName, ex.Message, "Failed to load five day forecast.", 004); LoadLocalForecast(); } } }
public async Task OneQueryWithOneLocationAndTwoHitsReturnsOneForecastResultWithTwoElements() { string location = "Karlsruhe,de"; var urlBuilder = CreateFluentUrlProviderWithReturnUrl(); var client = CreateClient(new List <Helper.Maybe <ForecastResponse> >() { new Helper.Maybe <ForecastResponse>(ForecastResponse.FromJson(TestData.ForecastResponseKarlsruhe)) }); var mockQuery = CreateQuery(location); mockQuery.Setup(query => query.IsSatisfiedBy(It.IsAny <Forecast>())) .Returns((Forecast forecast) => { return(forecast.MeasureTime.Equals(new DateTime(2019, 7, 30, 21, 0, 0)) || forecast.MeasureTime.Equals(new DateTime(2019, 7, 31, 9, 0, 0))); }); var serviceUnderTest = new OpenWeatherService(client.Object, urlBuilder.Object); var result = await serviceUnderTest.GetForecasts(mockQuery.Object); Assert.True(result.First().ForecastData.Count == 2); }
public async Task ReturnTwoForecastResultsWhenGivenTwoLocationsInQuery() { string firstLocation = "Karlsruhe,de"; string secondLocation = "Stuttgart,de"; var urlBuilder = CreateFluentUrlProviderWithReturnUrl(); var client = CreateClient(new List <Helper.Maybe <ForecastResponse> >() { new Helper.Maybe <ForecastResponse>(ForecastResponse.FromJson(TestData.ForecastResponseKarlsruhe)), new Helper.Maybe <ForecastResponse>(ForecastResponse.FromJson(TestData.ForecastResponseStuttgart)) }); var mockQuery = CreateQuery(new List <string>() { firstLocation, secondLocation }); mockQuery.Setup(query => query.IsSatisfiedBy(It.IsAny <Forecast>())) .Returns((Forecast forecast) => forecast.MeasureTime.Equals(new DateTime(2019, 7, 30, 21, 0, 0))); var serviceUnderTest = new OpenWeatherService(client.Object, urlBuilder.Object); var result = await serviceUnderTest.GetForecasts(mockQuery.Object); Assert.True(result.Count() == 2); }
async Task <Maybe <ForecastResponse> > IClient.GetForecastAsync(string url) { try { var response = await base.GetAsync(url).ConfigureAwait(false); if (response.StatusCode != System.Net.HttpStatusCode.OK) { return(new Maybe <ForecastResponse>()); } var deserializedResponse = ForecastResponse.FromJson(await response.Content.ReadAsStringAsync().ConfigureAwait(false)); return(new Maybe <ForecastResponse>(deserializedResponse)); } catch (HttpRequestException ex) { return(new Maybe <ForecastResponse>() { ErrorMessage = $"{ex.GetType().Name}: {ex.Message}" }); } catch (InvalidOperationException ex) { return(new Maybe <ForecastResponse>() { ErrorMessage = $"{ex.GetType().Name}: {ex.Message}" }); } catch (Newtonsoft.Json.JsonSerializationException ex) { return(new Maybe <ForecastResponse>() { ErrorMessage = $"{ex.GetType().Name}: {ex.Message}" }); } }
public void SaveNewForecast(ForecastResponse forecast) { ForecastDTO forecastDTO = forecast.ConvertToDTO(); sqLiteConnection.Insert(forecastDTO); }
private async void LoadWeather() { OpenWeatherMapClient client = null; try { client = new OpenWeatherMapClient("c6b82ccf5c40a3479dff0d236e06bc53"); if (client != null) { //string m_Location = "Lahore,PK"; //int m_LocationID = 1172451; //string m_Location = "Rawalpindi,PK"; //int m_LocationID = 1166993; string m_Location = "Sargodha,PK"; int m_LocationID = 1166000; //string m_Location = "Pattoki, PK"; //int m_LocationID = 1168226; //string m_Location = "Islamabad, PK"; //int m_LocationID = 1176615; //string m_Location = "Kot Momin, PK"; //int m_LocationID = 1182787; bool m_Degree = true; CurrentWeatherResponse currentWeather = null; if (!m_Degree) { currentWeather = await client.CurrentWeather.GetByCityId(m_LocationID, MetricSystem.Imperial); } else { currentWeather = await client.CurrentWeather.GetByCityId(m_LocationID, MetricSystem.Metric); } //set city v_City.Text = currentWeather.City.Name; lstWeatherData.Clear(); lstWeatherData.Add(LoadWeatherData(currentWeather.Weather.Icon, currentWeather.Temperature, false, System.DateTime.Now)); int forecastDays = 4; if (forecastDays > 1) { ForecastResponse forecast = null; if (!m_Degree) { forecast = await client.Forecast.GetByCityId(m_LocationID, true, MetricSystem.Imperial, OpenWeatherMapLanguage.EN, forecastDays); } else { forecast = await client.Forecast.GetByCityId(m_LocationID, true, MetricSystem.Metric, OpenWeatherMapLanguage.EN, forecastDays); } foreach (ForecastTime forecastTime in forecast.Forecast) { if (forecastTime.Day.Date != System.DateTime.Now.Date) { lstWeatherData.Add(LoadWeatherData(forecastTime.Symbol.Var, forecastTime.Temperature, true, forecastTime.Day)); } } } WeatherList.ItemsSource = lstWeatherData; } } catch (Exception ex) { Console.WriteLine("Weather exception " + ex.Message); } }