public static bool Exists(String location_query) { String listJson = widgetPrefs.GetString(location_query, String.Empty); if (!String.IsNullOrWhiteSpace(listJson)) { var idList = JSONParser.Deserializer <List <int> >(listJson); if (idList != null && idList.Count > 0) { return(true); } } return(false); }
public static int[] GetWidgetIds(String location_query) { String listJson = widgetPrefs.GetString(location_query, String.Empty); if (!String.IsNullOrWhiteSpace(listJson)) { var idList = JSONParser.Deserializer <List <int> >(listJson); if (idList != null) { return(idList.ToArray()); } } return(new List <int>().ToArray()); }
public static void AddWidgetId(String location_query, int widgetId) { String listJson = widgetPrefs.GetString(location_query, String.Empty); if (String.IsNullOrWhiteSpace(listJson)) { var newlist = new List <int>() { widgetId }; SaveIds(location_query, newlist); } else { var idList = JSONParser.Deserializer <List <int> >(listJson); if (idList != null && !idList.Contains(widgetId)) { idList.Add(widgetId); SaveIds(location_query, idList); } } }
public static void RemoveWidgetId(String location_query, int widgetId) { String listJson = widgetPrefs.GetString(location_query, String.Empty); if (!String.IsNullOrWhiteSpace(listJson)) { var idList = JSONParser.Deserializer <List <int> >(listJson); if (idList != null) { idList.Remove(widgetId); if (idList.Count == 0) { widgetPrefs.Edit().Remove(location_query).Commit(); } else { SaveIds(location_query, idList); } } } DeletePreferences(widgetId); }
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 <ObservableCollection <LocationQueryViewModel> > GetLocations(string query) { ObservableCollection <LocationQueryViewModel> locations = null; string queryAPI = "https://autocomplete.wunderground.com/aq?query="; string options = "&h=0&cities=1"; Uri queryURL = new Uri(queryAPI + query + options); // Limit amount of results shown int maxResults = 10; 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 locations = new ObservableCollection <LocationQueryViewModel>(); var root = JSONParser.Deserializer <OpenWeather.AC_Rootobject>(contentStream); foreach (OpenWeather.AC_RESULT result in root.RESULTS) { // Filter: only store city results if (result.type != "city") { continue; } locations.Add(new LocationQueryViewModel(result)); // Limit amount of results maxResults--; if (maxResults <= 0) { break; } } // End Stream if (contentStream != null) { contentStream.Dispose(); } } catch (Exception ex) { locations = new ObservableCollection <LocationQueryViewModel>(); Logger.WriteLine(LoggerLevel.Error, ex, "MetnoWeatherProvider: error getting locations"); } if (locations == null || locations.Count == 0) { locations = new ObservableCollection <LocationQueryViewModel>() { new LocationQueryViewModel() } } ; return(locations); }
public async Task <List <WeatherAlert> > GetAlerts(LocationData location) { List <WeatherAlert> alerts = null; string queryAPI = null; Uri weatherURL = null; queryAPI = "https://api.weather.gov/alerts/active?point={0},{1}"; weatherURL = new Uri(string.Format(queryAPI, location.latitude, location.longitude)); try { // Connect to webstream HttpClient webClient = new HttpClient(); #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.Accept.Add(new HttpMediaTypeWithQualityHeaderValue("application/ld+json")); 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.Accept.Add(new MediaTypeWithQualityHeaderValue("application/ld+json")); webClient.DefaultRequestHeaders.TryAddWithoutValidation("user-agent", String.Format("SimpleWeather ([email protected]) {0}", version)); #endif 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 // End Stream webClient.Dispose(); // Load data alerts = new List <WeatherAlert>(); var root = JSONParser.Deserializer <AlertRootobject>(contentStream); foreach (Graph result in root.graph) { alerts.Add(new WeatherAlert(result)); } // End Stream if (contentStream != null) { contentStream.Dispose(); } } catch (Exception ex) { alerts = new List <WeatherAlert>(); Logger.WriteLine(LoggerLevel.Error, ex, "NWSAlertProvider: error getting weather alert data"); } if (alerts == null) { alerts = new List <WeatherAlert>(); } return(alerts); }
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 <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 <List <WeatherAlert> > GetAlerts(LocationData location) { List <WeatherAlert> alerts = 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&{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)); try { // Connect to webstream HttpClient webClient = new HttpClient(); 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 // End Stream webClient.Dispose(); // Load data alerts = new List <WeatherAlert>(); Rootobject root = JSONParser.Deserializer <Rootobject>(contentStream); foreach (Alert result in root.alerts.alerts) { alerts.Add(new WeatherAlert(result)); } // End Stream if (contentStream != null) { contentStream.Dispose(); } } catch (Exception ex) { alerts = new List <WeatherAlert>(); Logger.WriteLine(LoggerLevel.Error, ex, "HEREWeatherProvider: error getting weather alert data"); } if (alerts == null) { alerts = new List <WeatherAlert>(); } return(alerts); }
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 <List <WeatherAlert> > GetAlerts(LocationData location) { List <WeatherAlert> alerts = 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 + "/alerts/lang:" + locale; string options = ".json"; weatherURL = new Uri(queryAPI + location.query + options); try { // Connect to webstream HttpClient webClient = new HttpClient(); 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 // End Stream webClient.Dispose(); // Load data alerts = new List <WeatherAlert>(); AlertRootobject root = JSONParser.Deserializer <AlertRootobject>(contentStream); foreach (Alert result in root.alerts) { alerts.Add(new WeatherAlert(result)); } // End Stream if (contentStream != null) { contentStream.Dispose(); } } catch (Exception ex) { alerts = new List <WeatherAlert>(); Logger.WriteLine(LoggerLevel.Error, ex, "WeatherUndergroundProvider: error getting weather alert data"); } if (alerts == null) { alerts = new List <WeatherAlert>(); } return(alerts); }
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); }