public void OnWeatherError(WeatherException wEx) { switch (wEx.ErrorStatus) { case WeatherUtils.ErrorStatus.NetworkError: case WeatherUtils.ErrorStatus.NoWeather: // Show error message and prompt to refresh // Only warn once if (!ErrorCounter[(int)wEx.ErrorStatus]) { Snackbar snackBar = Snackbar.Make(Content as Grid, wEx.Message, SnackbarDuration.Long); snackBar.SetAction(App.ResLoader.GetString("Action_Retry"), async() => { await RefreshLocations(); }); snackBar.Show(); ErrorCounter[(int)wEx.ErrorStatus] = true; } break; default: // Show error message // Only warn once if (!ErrorCounter[(int)wEx.ErrorStatus]) { Snackbar.Make(Content as Grid, wEx.Message, SnackbarDuration.Long).Show(); ErrorCounter[(int)wEx.ErrorStatus] = true; } break; } }
public void OnWeatherError(WeatherException wEx) { switch (wEx.ErrorStatus) { case WeatherUtils.ErrorStatus.NetworkError: case WeatherUtils.ErrorStatus.NoWeather: // Show error message and prompt to refresh // Only warn once if (!ErrorCounter[(int)wEx.ErrorStatus]) { var snackBar = Snackbar.Make(mMainView, wEx.Message, Snackbar.LengthLong); snackBar.SetAction(Resource.String.action_retry, async(View v) => { await RefreshLocations(); }); snackBar.Show(); ErrorCounter[(int)wEx.ErrorStatus] = true; } break; default: // Show error message // Only warn once if (!ErrorCounter[(int)wEx.ErrorStatus]) { Snackbar.Make(mMainView, wEx.Message, Snackbar.LengthLong).Show(); ErrorCounter[(int)wEx.ErrorStatus] = true; } break; } }
public void OnWeatherError(WeatherException wEx) { if (wEx != null) { // Show error message Activity?.RunOnUiThread(() => { Toast.MakeText(Activity, wEx.Message, ToastLength.Long).Show(); }); } }
public void OnWeatherError(WeatherException wEx) { switch (wEx.ErrorStatus) { case WeatherUtils.ErrorStatus.NetworkError: case WeatherUtils.ErrorStatus.NoWeather: // Show error message and prompt to refresh Snackbar snackBar = Snackbar.Make(Content as Grid, wEx.Message, SnackbarDuration.Long); snackBar.SetAction(App.ResLoader.GetString("Action_Retry"), () => { Task.Run(async() => await RefreshWeather(false)); }); snackBar.Show(); break; default: // Show error message Snackbar.Make(Content as Grid, wEx.Message, SnackbarDuration.Long).Show(); break; } }
public void OnWeatherError(WeatherException wEx) { AppCompatActivity?.RunOnUiThread(() => { switch (wEx.ErrorStatus) { case WeatherUtils.ErrorStatus.NetworkError: case WeatherUtils.ErrorStatus.NoWeather: // Show error message and prompt to refresh Snackbar snackBar = Snackbar.Make(mainView, wEx.Message, Snackbar.LengthLong); snackBar.SetAction(Resource.String.action_retry, async(View v) => { await RefreshWeather(false); }); snackBar.Show(); break; default: // Show error message Snackbar.Make(mainView, wEx.Message, Snackbar.LengthLong).Show(); break; } }); }
public override async Task <Weather> GetWeather(string location_query) { Weather weather = null; string forecastAPI = null; Uri forecastURL = null; string sunrisesetAPI = null; Uri sunrisesetURL = null; forecastAPI = "https://api.met.no/weatherapi/locationforecastlts/1.3/?{0}"; forecastURL = new Uri(string.Format(forecastAPI, location_query)); sunrisesetAPI = "https://api.met.no/weatherapi/sunrise/1.1/?{0}&date={1}"; string date = DateTime.Now.ToString("yyyy-MM-dd"); sunrisesetURL = new Uri(string.Format(sunrisesetAPI, location_query, date)); #if WINDOWS_UWP var handler = new HttpBaseProtocolFilter() { AllowAutoRedirect = true, AutomaticDecompression = true }; #else var handler = new HttpClientHandler() { AllowAutoRedirect = true, AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }; #endif HttpClient webClient = new HttpClient(handler); // Use GZIP compression #if WINDOWS_UWP var version = string.Format("v{0}.{1}.{2}", Package.Current.Id.Version.Major, Package.Current.Id.Version.Minor, Package.Current.Id.Version.Build); webClient.DefaultRequestHeaders.AcceptEncoding.Add(new HttpContentCodingWithQualityHeaderValue("gzip")); webClient.DefaultRequestHeaders.UserAgent.Add(new HttpProductInfoHeaderValue("SimpleWeather ([email protected])", version)); #elif __ANDROID__ var packageInfo = Application.Context.PackageManager.GetPackageInfo(Application.Context.PackageName, 0); var version = string.Format("v{0}", packageInfo.VersionName); webClient.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip")); webClient.DefaultRequestHeaders.TryAddWithoutValidation("user-agent", String.Format("SimpleWeather ([email protected]) {0}", version)); #endif WeatherException wEx = null; try { // Get response HttpResponseMessage forecastResponse = await webClient.GetAsync(forecastURL); forecastResponse.EnsureSuccessStatusCode(); HttpResponseMessage sunrisesetResponse = await webClient.GetAsync(sunrisesetURL); sunrisesetResponse.EnsureSuccessStatusCode(); Stream forecastStream = null; Stream sunrisesetStream = null; #if WINDOWS_UWP forecastStream = WindowsRuntimeStreamExtensions.AsStreamForRead(await forecastResponse.Content.ReadAsInputStreamAsync()); sunrisesetStream = WindowsRuntimeStreamExtensions.AsStreamForRead(await sunrisesetResponse.Content.ReadAsInputStreamAsync()); #elif __ANDROID__ forecastStream = await forecastResponse.Content.ReadAsStreamAsync(); sunrisesetStream = await sunrisesetResponse.Content.ReadAsStreamAsync(); #endif // Reset exception wEx = null; // Load weather weatherdata foreRoot = null; astrodata astroRoot = null; XmlSerializer foreDeserializer = new XmlSerializer(typeof(weatherdata)); foreRoot = (weatherdata)foreDeserializer.Deserialize(forecastStream); XmlSerializer astroDeserializer = new XmlSerializer(typeof(astrodata)); astroRoot = (astrodata)astroDeserializer.Deserialize(sunrisesetStream); weather = new Weather(foreRoot, astroRoot); } catch (Exception ex) { weather = null; #if WINDOWS_UWP if (WebError.GetStatus(ex.HResult) > WebErrorStatus.Unknown) #elif __ANDROID__ if (ex is WebException || ex is HttpRequestException) #endif { wEx = new WeatherException(WeatherUtils.ErrorStatus.NetworkError); } Logger.WriteLine(LoggerLevel.Error, ex, "MetnoWeatherProvider: error getting weather data"); } // End Stream webClient.Dispose(); if (weather == null || !weather.IsValid()) { wEx = new WeatherException(WeatherUtils.ErrorStatus.NoWeather); } else if (weather != null) { weather.query = location_query; foreach (Forecast forecast in weather.forecast) { forecast.condition = GetWeatherCondition(forecast.icon); forecast.icon = GetWeatherIcon(forecast.icon); } } if (wEx != null) { throw wEx; } return(weather); }
public override async Task <LocationQueryViewModel> GetLocation(string query) { LocationQueryViewModel location = null; string queryAPI = "https://autocomplete.wunderground.com/aq?query="; string options = "&h=0&cities=1"; Uri queryURL = new Uri(queryAPI + query + options); OpenWeather.AC_RESULT result; WeatherException wEx = null; try { // Connect to webstream HttpClient webClient = new HttpClient(); HttpResponseMessage response = await webClient.GetAsync(queryURL); response.EnsureSuccessStatusCode(); Stream contentStream = null; #if WINDOWS_UWP contentStream = WindowsRuntimeStreamExtensions.AsStreamForRead(await response.Content.ReadAsInputStreamAsync()); #elif __ANDROID__ contentStream = await response.Content.ReadAsStreamAsync(); #endif // End Stream webClient.Dispose(); // Load data var root = JSONParser.Deserializer <OpenWeather.AC_Rootobject>(contentStream); result = root.RESULTS.FirstOrDefault(); // End Stream if (contentStream != null) { contentStream.Dispose(); } } catch (Exception ex) { result = null; #if WINDOWS_UWP if (WebError.GetStatus(ex.HResult) > WebErrorStatus.Unknown) { wEx = new WeatherException(WeatherUtils.ErrorStatus.NetworkError); await Toast.ShowToastAsync(wEx.Message, ToastDuration.Short); } #elif __ANDROID__ if (ex is WebException || ex is HttpRequestException) { wEx = new WeatherException(WeatherUtils.ErrorStatus.NetworkError); new Android.OS.Handler(Android.OS.Looper.MainLooper).Post(() => { Toast.MakeText(Application.Context, wEx.Message, ToastLength.Short).Show(); }); } #endif Logger.WriteLine(LoggerLevel.Error, ex, "MetnoWeatherProvider: error getting location"); } if (result != null && !String.IsNullOrWhiteSpace(result.l)) { location = new LocationQueryViewModel(result); } else { location = new LocationQueryViewModel(); } return(location); }
public override async Task <LocationQueryViewModel> GetLocation(WeatherUtils.Coordinate coord) { LocationQueryViewModel location = null; string queryAPI = "https://api.wunderground.com/auto/wui/geo/GeoLookupXML/index.xml?query="; string options = ""; string query = string.Format("{0},{1}", coord.Latitude, coord.Longitude); Uri queryURL = new Uri(queryAPI + query + options); OpenWeather.location result; WeatherException wEx = null; try { // Connect to webstream HttpClient webClient = new HttpClient(); HttpResponseMessage response = await webClient.GetAsync(queryURL); response.EnsureSuccessStatusCode(); Stream contentStream = null; #if WINDOWS_UWP contentStream = WindowsRuntimeStreamExtensions.AsStreamForRead(await response.Content.ReadAsInputStreamAsync()); #elif __ANDROID__ contentStream = await response.Content.ReadAsStreamAsync(); #endif // End Stream webClient.Dispose(); // Load data XmlSerializer deserializer = new XmlSerializer(typeof(OpenWeather.location)); result = (OpenWeather.location)deserializer.Deserialize(contentStream); // End Stream if (contentStream != null) { contentStream.Dispose(); } } catch (Exception ex) { result = null; #if WINDOWS_UWP if (WebError.GetStatus(ex.HResult) > WebErrorStatus.Unknown) { wEx = new WeatherException(WeatherUtils.ErrorStatus.NetworkError); await Toast.ShowToastAsync(wEx.Message, ToastDuration.Short); } #elif __ANDROID__ if (ex is WebException || ex is HttpRequestException) { wEx = new WeatherException(WeatherUtils.ErrorStatus.NetworkError); new Android.OS.Handler(Android.OS.Looper.MainLooper).Post(() => { Toast.MakeText(Application.Context, wEx.Message, ToastLength.Short).Show(); }); } #endif Logger.WriteLine(LoggerLevel.Error, ex, "MetnoWeatherProvider: error getting location"); } if (result != null && !String.IsNullOrWhiteSpace(result.query)) { location = new LocationQueryViewModel(result); } else { location = new LocationQueryViewModel(); } return(location); }
public override async Task <Weather> GetWeather(string location_query) { Weather weather = null; string queryAPI = null; Uri weatherURL = null; #if WINDOWS_UWP var userlang = Windows.System.UserProfile.GlobalizationPreferences.Languages.First(); var culture = new System.Globalization.CultureInfo(userlang); #else var culture = System.Globalization.CultureInfo.CurrentCulture; #endif string locale = LocaleToLangCode(culture.TwoLetterISOLanguageName, culture.Name); if (int.TryParse(location_query, out int woeid)) { queryAPI = "https://query.yahooapis.com/v1/public/yql?q="; string query = "select * from weather.forecast where woeid=\"" + woeid + "\" and u='F'&format=json"; weatherURL = new Uri(queryAPI + query); } else { queryAPI = "https://query.yahooapis.com/v1/public/yql?q="; string query = "select * from weather.forecast where woeid in (select woeid from geo.places(1) where text=\"" + location_query + "\") and u='F'&format=json"; weatherURL = new Uri(queryAPI + query); } HttpClient webClient = new HttpClient(); WeatherException wEx = null; try { // Get response HttpResponseMessage response = await webClient.GetAsync(weatherURL); response.EnsureSuccessStatusCode(); Stream contentStream = null; #if WINDOWS_UWP contentStream = WindowsRuntimeStreamExtensions.AsStreamForRead(await response.Content.ReadAsInputStreamAsync()); #elif __ANDROID__ contentStream = await response.Content.ReadAsStreamAsync(); #endif // Reset exception wEx = null; // Load weather Rootobject root = null; await Task.Run(() => { root = JSONParser.Deserializer <Rootobject>(contentStream); }); // End Stream if (contentStream != null) { contentStream.Dispose(); } weather = new Weather(root); } catch (Exception ex) { weather = null; #if WINDOWS_UWP if (WebError.GetStatus(ex.HResult) > WebErrorStatus.Unknown) #elif __ANDROID__ if (ex is WebException || ex is HttpRequestException) #endif { wEx = new WeatherException(WeatherUtils.ErrorStatus.NetworkError); } Logger.WriteLine(LoggerLevel.Error, ex, "YahooWeatherProvider: error getting weather data"); } // End Stream webClient.Dispose(); if (weather == null || !weather.IsValid()) { wEx = new WeatherException(WeatherUtils.ErrorStatus.NoWeather); } else if (weather != null) { if (SupportsWeatherLocale) { weather.locale = locale; } weather.query = location_query; } if (wEx != null) { throw wEx; } return(weather); }
public override async Task <LocationQueryViewModel> GetLocation(string location_query) { LocationQueryViewModel location = null; string yahooAPI = "https://query.yahooapis.com/v1/public/yql?q="; string query = "select * from geo.places where woeid=\"" + location_query + "\""; Uri queryURL = new Uri(yahooAPI + query); place result = null; WeatherException wEx = null; try { // Connect to webstream HttpClient webClient = new HttpClient(); HttpResponseMessage response = await webClient.GetAsync(queryURL); response.EnsureSuccessStatusCode(); Stream contentStream = null; #if WINDOWS_UWP contentStream = WindowsRuntimeStreamExtensions.AsStreamForRead(await response.Content.ReadAsInputStreamAsync()); #elif __ANDROID__ contentStream = await response.Content.ReadAsStreamAsync(); #endif // End Stream webClient.Dispose(); // Load data XmlSerializer deserializer = new XmlSerializer(typeof(query)); query root = (query)deserializer.Deserialize(contentStream); if (root.results != null) { result = root.results[0]; } // End Stream if (contentStream != null) { contentStream.Dispose(); } } catch (Exception ex) { result = null; #if WINDOWS_UWP if (Windows.Web.WebError.GetStatus(ex.HResult) > Windows.Web.WebErrorStatus.Unknown) { wEx = new WeatherException(WeatherUtils.ErrorStatus.NetworkError); await Toast.ShowToastAsync(wEx.Message, ToastDuration.Short); } #elif __ANDROID__ if (ex is System.Net.WebException || ex is HttpRequestException) { wEx = new WeatherException(WeatherUtils.ErrorStatus.NetworkError); new Android.OS.Handler(Android.OS.Looper.MainLooper).Post(() => { Toast.MakeText(Application.Context, wEx.Message, ToastLength.Short).Show(); }); } #endif Logger.WriteLine(LoggerLevel.Error, ex, "YahooWeatherProvider: error getting location"); } if (result != null && !String.IsNullOrWhiteSpace(result.woeid)) { location = new LocationQueryViewModel(result); } else { location = new LocationQueryViewModel(); } return(location); }
public override async Task <Weather> GetWeather(string location_query) { Weather weather = null; string queryAPI = null; Uri weatherURL = null; #if WINDOWS_UWP var userlang = Windows.System.UserProfile.GlobalizationPreferences.Languages.First(); var culture = new System.Globalization.CultureInfo(userlang); #else var culture = System.Globalization.CultureInfo.CurrentCulture; #endif string locale = LocaleToLangCode(culture.TwoLetterISOLanguageName, culture.Name); string key = Settings.UsePersonalKey ? Settings.API_KEY : GetAPIKey(); queryAPI = "https://api.wunderground.com/api/" + key + "/astronomy/conditions/forecast10day/hourly/alerts/lang:" + locale; string options = ".json"; weatherURL = new Uri(queryAPI + location_query + options); HttpClient webClient = new HttpClient(); WeatherException wEx = null; try { // Get response HttpResponseMessage response = await webClient.GetAsync(weatherURL); response.EnsureSuccessStatusCode(); Stream contentStream = null; #if WINDOWS_UWP contentStream = WindowsRuntimeStreamExtensions.AsStreamForRead(await response.Content.ReadAsInputStreamAsync()); #elif __ANDROID__ contentStream = await response.Content.ReadAsStreamAsync(); #endif // Reset exception wEx = null; // Load weather Rootobject root = null; await Task.Run(() => { root = JSONParser.Deserializer <Rootobject>(contentStream); }); // Check for errors if (root.response.error != null) { switch (root.response.error.type) { case "querynotfound": wEx = new WeatherException(WeatherUtils.ErrorStatus.QueryNotFound); break; case "keynotfound": wEx = new WeatherException(WeatherUtils.ErrorStatus.InvalidAPIKey); break; default: break; } } // End Stream if (contentStream != null) { contentStream.Dispose(); } weather = new Weather(root); // Add weather alerts if available if (root.alerts != null && root.alerts.Length > 0) { if (weather.weather_alerts == null) { weather.weather_alerts = new List <WeatherAlert>(); } foreach (Alert result in root.alerts) { weather.weather_alerts.Add(new WeatherAlert(result)); } } } catch (Exception ex) { weather = null; #if WINDOWS_UWP if (WebError.GetStatus(ex.HResult) > WebErrorStatus.Unknown) #elif __ANDROID__ if (ex is WebException || ex is HttpRequestException) #endif { wEx = new WeatherException(WeatherUtils.ErrorStatus.NetworkError); } Logger.WriteLine(LoggerLevel.Error, ex, "WeatherUndergroundProvider: error getting weather data"); } // End Stream webClient.Dispose(); if (weather == null || !weather.IsValid()) { wEx = new WeatherException(WeatherUtils.ErrorStatus.NoWeather); } else if (weather != null) { if (SupportsWeatherLocale) { weather.locale = locale; } weather.query = location_query; } if (wEx != null) { throw wEx; } return(weather); }
public override async Task <WeatherData.Weather> GetWeather(string location_query) { WeatherData.Weather weather = null; string currentAPI = null; Uri currentURL = null; string forecastAPI = null; Uri forecastURL = null; string query = null; #if WINDOWS_UWP var userlang = Windows.System.UserProfile.GlobalizationPreferences.Languages.First(); var culture = new System.Globalization.CultureInfo(userlang); #else var culture = System.Globalization.CultureInfo.CurrentCulture; #endif string locale = LocaleToLangCode(culture.TwoLetterISOLanguageName, culture.Name); if (int.TryParse(location_query, out int id)) { query = string.Format("id={0}", id); } else { query = location_query; } string key = Settings.UsePersonalKey ? Settings.API_KEY : GetAPIKey(); currentAPI = "https://api.openweathermap.org/data/2.5/weather?{0}&appid={1}&lang=" + locale; currentURL = new Uri(string.Format(currentAPI, query, key)); forecastAPI = "https://api.openweathermap.org/data/2.5/forecast?{0}&appid={1}&lang=" + locale; forecastURL = new Uri(string.Format(forecastAPI, query, key)); HttpClient webClient = new HttpClient(); WeatherException wEx = null; try { // Get response HttpResponseMessage currentResponse = await webClient.GetAsync(currentURL); currentResponse.EnsureSuccessStatusCode(); HttpResponseMessage forecastResponse = await webClient.GetAsync(forecastURL); forecastResponse.EnsureSuccessStatusCode(); Stream currentStream = null; Stream forecastStream = null; #if WINDOWS_UWP currentStream = WindowsRuntimeStreamExtensions.AsStreamForRead(await currentResponse.Content.ReadAsInputStreamAsync()); forecastStream = WindowsRuntimeStreamExtensions.AsStreamForRead(await forecastResponse.Content.ReadAsInputStreamAsync()); #elif __ANDROID__ currentStream = await currentResponse.Content.ReadAsStreamAsync(); forecastStream = await forecastResponse.Content.ReadAsStreamAsync(); #endif // Reset exception wEx = null; // Load weather CurrentRootobject currRoot = null; ForecastRootobject foreRoot = null; await Task.Run(() => { currRoot = JSONParser.Deserializer <CurrentRootobject>(currentStream); }); await Task.Run(() => { foreRoot = JSONParser.Deserializer <ForecastRootobject>(forecastStream); }); // End Streams currentStream.Dispose(); forecastStream.Dispose(); weather = new WeatherData.Weather(currRoot, foreRoot); } catch (Exception ex) { weather = null; #if WINDOWS_UWP if (WebError.GetStatus(ex.HResult) > WebErrorStatus.Unknown) #elif __ANDROID__ if (ex is WebException || ex is HttpRequestException) #endif { wEx = new WeatherException(WeatherUtils.ErrorStatus.NetworkError); } Logger.WriteLine(LoggerLevel.Error, ex, "OpenWeatherMapProvider: error getting weather data"); } // End Stream webClient.Dispose(); if (weather == null || !weather.IsValid()) { wEx = new WeatherException(WeatherUtils.ErrorStatus.NoWeather); } else if (weather != null) { if (SupportsWeatherLocale) { weather.locale = locale; } weather.query = location_query; } if (wEx != null) { throw wEx; } return(weather); }
public override async Task <bool> IsKeyValid(string key) { string queryAPI = "https://api.openweathermap.org/data/2.5/"; string query = "forecast?appid="; Uri queryURL = new Uri(queryAPI + query + key); bool isValid = false; WeatherException wEx = null; try { if (String.IsNullOrWhiteSpace(key)) { throw (wEx = new WeatherException(WeatherUtils.ErrorStatus.InvalidAPIKey)); } // Connect to webstream HttpClient webClient = new HttpClient(); HttpResponseMessage response = await webClient.GetAsync(queryURL); // Check for errors switch (response.StatusCode) { // 400 (OK since this isn't a valid request) case HttpStatusCode.BadRequest: isValid = true; break; // 401 (Unauthorized - Key is invalid) case HttpStatusCode.Unauthorized: wEx = new WeatherException(WeatherUtils.ErrorStatus.InvalidAPIKey); isValid = false; break; } // End Stream response.Dispose(); webClient.Dispose(); } catch (Exception ex) { #if WINDOWS_UWP if (WebError.GetStatus(ex.HResult) > WebErrorStatus.Unknown) #elif __ANDROID__ if (ex is WebException || ex is HttpRequestException) #endif { wEx = new WeatherException(WeatherUtils.ErrorStatus.NetworkError); } isValid = false; } if (wEx != null) { #if WINDOWS_UWP await Toast.ShowToastAsync(wEx.Message, ToastDuration.Short); #elif __ANDROID__ new Android.OS.Handler(Android.OS.Looper.MainLooper).Post(() => { Toast.MakeText(Application.Context, wEx.Message, ToastLength.Short).Show(); }); #endif } return(isValid); }
public override async Task <Weather> GetWeather(string location_query) { Weather weather = null; string queryAPI = null; Uri weatherURL = null; #if WINDOWS_UWP var userlang = Windows.System.UserProfile.GlobalizationPreferences.Languages.First(); var culture = new CultureInfo(userlang); #else var culture = CultureInfo.CurrentCulture; #endif string locale = LocaleToLangCode(culture.TwoLetterISOLanguageName, culture.Name); queryAPI = "https://weather.cit.api.here.com/weather/1.0/report.json?product=alerts&product=forecast_7days_simple" + "&product=forecast_hourly&product=forecast_astronomy&product=observation&oneobservation=true&{0}" + "&language={1}&metric=false&app_id={2}&app_code={3}"; string key = Settings.UsePersonalKey ? Settings.API_KEY : GetAPIKey(); string app_id = ""; string app_code = ""; if (!String.IsNullOrWhiteSpace(key)) { string[] keyArr = key.Split(';'); if (keyArr.Length > 0) { app_id = keyArr[0]; app_code = keyArr[keyArr.Length > 1 ? keyArr.Length - 1 : 0]; } } weatherURL = new Uri(String.Format(queryAPI, location_query, locale, app_id, app_code)); HttpClient webClient = new HttpClient(); WeatherException wEx = null; try { // Get response HttpResponseMessage response = await webClient.GetAsync(weatherURL); response.EnsureSuccessStatusCode(); Stream contentStream = null; #if WINDOWS_UWP contentStream = WindowsRuntimeStreamExtensions.AsStreamForRead(await response.Content.ReadAsInputStreamAsync()); #elif __ANDROID__ contentStream = await response.Content.ReadAsStreamAsync(); #endif // Reset exception wEx = null; // Load weather Rootobject root = null; await Task.Run(() => { root = JSONParser.Deserializer <Rootobject>(contentStream); }); // Check for errors if (root.Type != null) { switch (root.Type) { case "Invalid Request": wEx = new WeatherException(WeatherUtils.ErrorStatus.QueryNotFound); break; case "Unauthorized": wEx = new WeatherException(WeatherUtils.ErrorStatus.InvalidAPIKey); break; default: break; } } // End Stream if (contentStream != null) { contentStream.Dispose(); } weather = new Weather(root); // Add weather alerts if available if (root.alerts?.alerts != null && root.alerts.alerts.Length > 0) { if (weather.weather_alerts == null) { weather.weather_alerts = new List <WeatherAlert>(); } foreach (Alert result in root.alerts.alerts) { weather.weather_alerts.Add(new WeatherAlert(result)); } } } catch (Exception ex) { weather = null; #if WINDOWS_UWP if (WebError.GetStatus(ex.HResult) > WebErrorStatus.Unknown) #elif __ANDROID__ if (ex is WebException || ex is HttpRequestException) #endif { wEx = new WeatherException(WeatherUtils.ErrorStatus.NetworkError); } Logger.WriteLine(LoggerLevel.Error, ex, "HEREWeatherProvider: error getting weather data"); } // End Stream webClient.Dispose(); if (weather == null || !weather.IsValid()) { wEx = new WeatherException(WeatherUtils.ErrorStatus.NoWeather); } else if (weather != null) { if (SupportsWeatherLocale) { weather.locale = locale; } weather.query = location_query; } if (wEx != null) { throw wEx; } return(weather); }
public override async Task <bool> IsKeyValid(string key) { string queryAPI = "https://weather.cit.api.here.com/weather/1.0/report.json"; string app_id = ""; string app_code = ""; if (!String.IsNullOrWhiteSpace(key)) { string[] keyArr = key.Split(';'); if (keyArr.Length > 0) { app_id = keyArr[0]; app_code = keyArr[keyArr.Length > 1 ? keyArr.Length - 1 : 0]; } } Uri queryURL = new Uri(String.Format("{0}?app_id={1}&app_code={2}", queryAPI, app_id, app_code)); bool isValid = false; WeatherException wEx = null; try { if (String.IsNullOrWhiteSpace(app_id) || String.IsNullOrWhiteSpace(app_code)) { throw (wEx = new WeatherException(WeatherUtils.ErrorStatus.InvalidAPIKey)); } // Connect to webstream HttpClient webClient = new HttpClient(); HttpResponseMessage response = await webClient.GetAsync(queryURL); // Check for errors switch (response.StatusCode) { // 400 (OK since this isn't a valid request) case HttpStatusCode.BadRequest: isValid = true; break; // 401 (Unauthorized - Key is invalid) case HttpStatusCode.Unauthorized: wEx = new WeatherException(WeatherUtils.ErrorStatus.InvalidAPIKey); isValid = false; break; } // End Stream response.Dispose(); webClient.Dispose(); } catch (Exception ex) { #if WINDOWS_UWP if (WebError.GetStatus(ex.HResult) > WebErrorStatus.Unknown) #elif __ANDROID__ if (ex is WebException || ex is HttpRequestException) #endif { wEx = new WeatherException(WeatherUtils.ErrorStatus.NetworkError); } isValid = false; } if (wEx != null) { #if WINDOWS_UWP await Toast.ShowToastAsync(wEx.Message, ToastDuration.Short); #elif __ANDROID__ new Android.OS.Handler(Android.OS.Looper.MainLooper).Post(() => { Toast.MakeText(Application.Context, wEx.Message, ToastLength.Short).Show(); }); #endif } return(isValid); }
private async Task GetWeatherData() { WeatherException wEx = null; bool loadedSavedData = false; try { weather = await wm.GetWeather(location); } catch (WeatherException weatherEx) { wEx = weatherEx; weather = null; } catch (Exception ex) { Logger.WriteLine(LoggerLevel.Error, ex, "WeatherDataLoader: error getting weather data"); weather = null; } // Load old data if available and we can't get new data if (weather == null) { loadedSavedData = await LoadSavedWeatherData(true); } else if (weather != null) { // Handle upgrades if (String.IsNullOrEmpty(location.name) || String.IsNullOrEmpty(location.tz_long)) { location.name = weather.location.name; location.tz_long = weather.location.tz_long; #if !__ANDROID_WEAR__ await Settings.UpdateLocation(location); #else Settings.SaveHomeData(location); #endif } if (location.latitude == 0 && location.longitude == 0) { location.latitude = double.Parse(weather.location.latitude); location.longitude = double.Parse(weather.location.longitude); #if !__ANDROID_WEAR__ await Settings.UpdateLocation(location); #else Settings.SaveHomeData(location); #endif } await SaveWeatherData(); } // Throw exception if we're unable to get any weather data if (weather == null && wEx != null) { throw wEx; } else if (weather == null && wEx == null) { throw new WeatherException(WeatherUtils.ErrorStatus.NoWeather); } else if (weather != null && wEx != null && loadedSavedData) { throw wEx; } }
public override async Task <bool> IsKeyValid(string key) { string queryAPI = "https://api.wunderground.com/api/"; string query = "/q/NY/New_York.json"; Uri queryURL = new Uri(queryAPI + key + query); bool isValid = false; WeatherException wEx = null; try { if (String.IsNullOrWhiteSpace(key)) { throw (wEx = new WeatherException(WeatherUtils.ErrorStatus.InvalidAPIKey)); } // Connect to webstream HttpClient webClient = new HttpClient(); HttpResponseMessage response = await webClient.GetAsync(queryURL); response.EnsureSuccessStatusCode(); Stream contentStream = null; #if WINDOWS_UWP contentStream = WindowsRuntimeStreamExtensions.AsStreamForRead(await response.Content.ReadAsInputStreamAsync()); #elif __ANDROID__ contentStream = await response.Content.ReadAsStreamAsync(); #endif // Reset exception wEx = null; // End Stream webClient.Dispose(); // Load data Rootobject root = await JSONParser.DeserializerAsync <Rootobject>(contentStream); // Check for errors if (root.response.error != null) { switch (root.response.error.type) { case "keynotfound": wEx = new WeatherException(WeatherUtils.ErrorStatus.InvalidAPIKey); isValid = false; break; } } else { isValid = true; } // End Stream if (contentStream != null) { contentStream.Dispose(); } } catch (Exception) { isValid = false; } if (wEx != null) { #if WINDOWS_UWP await Toast.ShowToastAsync(wEx.Message, ToastDuration.Short); #elif __ANDROID__ new Android.OS.Handler(Android.OS.Looper.MainLooper).Post(() => { Toast.MakeText(Application.Context, wEx.Message, ToastLength.Short).Show(); }); #endif } return(isValid); }