public static async Task UpdateLocationWithKey(LocationData location, string oldKey) { if (location != null && location.IsValid() && !String.IsNullOrWhiteSpace(oldKey)) { // Get position from favorites table var favs = await locationDB.Table <Favorites>().ToListAsync(); var fav = favs.Find(f => f.query == oldKey); if (fav == null) { return; } int pos = fav.position; // Remove location from table await locationDB.DeleteAsync <LocationData>(oldKey); await locationDB.QueryAsync <Favorites>("delete from favorites where query = ?", oldKey); // Add updated location with new query (pkey) await locationDB.InsertOrReplaceAsync(location); await locationDB.InsertOrReplaceAsync(new Favorites() { query = location.query, position = pos }); } }
public static async Task UpdateLocation(LocationData location) { if (location != null && location.IsValid()) { await locationDB.UpdateAsync(location); } }
public static async Task AddLocation(LocationData location) { if (location != null && location.IsValid()) { await locationDB.InsertOrReplaceAsync(location); int pos = await locationDB.Table <LocationData>().CountAsync(); await locationDB.InsertOrReplaceAsync(new Favorites() { query = location.query, position = pos }); } }
public static async Task SaveWeatherAlerts(LocationData location, List <WeatherAlert> alerts) { if (location != null && location.IsValid()) { var alertdata = new WeatherAlerts(location.query, alerts); await weatherDB.InsertOrReplaceAsync(alertdata); await weatherDB.UpdateWithChildrenAsync(alertdata); } if (await weatherDB.Table <WeatherAlerts>().CountAsync() > CACHE_LIMIT) { CleanupWeatherAlertData(); } }
private async Task PrepareWidget() { // Update Settings if (refreshSpinner.SelectedItem is ComboBoxItem refreshItem) { if (int.TryParse(refreshItem.Value, out int refreshValue)) { Settings.RefreshInterval = refreshValue; } } // Get location data if (locSpinner.SelectedItem is ComboBoxItem locationItem) { LocationData locData = null; switch (locationItem.Value) { case "GPS": Settings.FollowGPS = true; if (gpsQuery_vm == null || mLocation == null) { await FetchGeoLocation(); } else { locData = new LocationData(gpsQuery_vm, mLocation); Settings.SaveLastGPSLocData(locData); // Save locdata for widget WidgetUtils.SaveLocationData(mAppWidgetId, locData); WidgetUtils.AddWidgetId(locData.query, mAppWidgetId); } break; default: // Get location data if (locSpinner.SelectedItem is ComboBoxItem item) { locData = Favorites.FirstOrDefault(loc => loc.query.Equals(item.Value)); if (locData == null && query_vm != null) { locData = new LocationData(query_vm); if (!locData.IsValid()) { SetResult(Result.Canceled, new Intent().PutExtra(AppWidgetManager.ExtraAppwidgetId, mAppWidgetId)); Finish(); return; } // Add location to favs await Settings.AddLocation(locData); } else if (locData == null) { SetResult(Result.Canceled, new Intent().PutExtra(AppWidgetManager.ExtraAppwidgetId, mAppWidgetId)); Finish(); return; } // Save locdata for widget WidgetUtils.SaveLocationData(mAppWidgetId, locData); WidgetUtils.AddWidgetId(locData.query, mAppWidgetId); } break; } // Trigger widget service to update widget WeatherWidgetService.EnqueueWork(this, new Intent(this, typeof(WeatherWidgetService)) .SetAction(WeatherWidgetService.ACTION_REFRESHWIDGET) .PutExtra(WeatherWidgetProvider.EXTRA_WIDGET_IDS, new int[] { mAppWidgetId })); // Create return intent Intent resultValue = new Intent(); resultValue.PutExtra(AppWidgetManager.ExtraAppwidgetId, mAppWidgetId); SetResult(Result.Ok, resultValue); Finish(); } else { SetResult(Result.Canceled, new Intent().PutExtra(AppWidgetManager.ExtraAppwidgetId, mAppWidgetId)); Finish(); } }
private async void GPS_Click(object sender, RoutedEventArgs e) { try { Button button = sender as Button; button.IsEnabled = false; LoadingRing.IsActive = true; // Cancel other tasks cts.Cancel(); cts = new CancellationTokenSource(); var ctsToken = cts.Token; ctsToken.ThrowIfCancellationRequested(); var geoStatus = GeolocationAccessStatus.Unspecified; try { // Catch error in case dialog is dismissed geoStatus = await Geolocator.RequestAccessAsync(); } catch (Exception ex) { Logger.WriteLine(LoggerLevel.Error, ex, "SetupPage: error requesting location permission"); System.Diagnostics.Debug.WriteLine(ex.StackTrace); } ctsToken.ThrowIfCancellationRequested(); Geolocator geolocal = new Geolocator() { DesiredAccuracyInMeters = 5000, ReportInterval = 900000, MovementThreshold = 1600 }; Geoposition geoPos = null; // Setup error just in case MessageDialog error = null; switch (geoStatus) { case GeolocationAccessStatus.Allowed: try { geoPos = await geolocal.GetGeopositionAsync(); } catch (Exception ex) { if (Windows.Web.WebError.GetStatus(ex.HResult) > Windows.Web.WebErrorStatus.Unknown) { error = new MessageDialog(App.ResLoader.GetString("WError_NetworkError"), App.ResLoader.GetString("Label_Error")); } else { error = new MessageDialog(App.ResLoader.GetString("Error_Location"), App.ResLoader.GetString("Label_ErrorLocation")); } await error.ShowAsync(); Logger.WriteLine(LoggerLevel.Error, ex, "SetupPage: error getting geolocation"); } break; case GeolocationAccessStatus.Denied: error = new MessageDialog(App.ResLoader.GetString("Msg_LocDeniedSettings"), App.ResLoader.GetString("Label_ErrLocationDenied")); error.Commands.Add(new UICommand(App.ResLoader.GetString("Label_Settings"), async(command) => { await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings:privacy-location")); }, 0)); error.Commands.Add(new UICommand(App.ResLoader.GetString("Label_Cancel"), null, 1)); error.DefaultCommandIndex = 0; error.CancelCommandIndex = 1; await error.ShowAsync(); break; case GeolocationAccessStatus.Unspecified: default: error = new MessageDialog(App.ResLoader.GetString("Error_Location"), App.ResLoader.GetString("Label_ErrorLocation")); await error.ShowAsync(); break; } // Access to location granted if (geoPos != null) { LocationQueryViewModel view = null; ctsToken.ThrowIfCancellationRequested(); button.IsEnabled = false; await Task.Run(async() => { ctsToken.ThrowIfCancellationRequested(); view = await wm.GetLocation(geoPos); if (String.IsNullOrEmpty(view.LocationQuery)) { view = new LocationQueryViewModel(); } }); if (String.IsNullOrWhiteSpace(view.LocationQuery)) { // Stop since there is no valid query EnableControls(true); return; } ctsToken.ThrowIfCancellationRequested(); // Weather Data var location = new LocationData(view, geoPos); if (!location.IsValid()) { await Toast.ShowToastAsync(App.ResLoader.GetString("WError_NoWeather"), ToastDuration.Short); EnableControls(true); return; } ctsToken.ThrowIfCancellationRequested(); Weather weather = await Settings.GetWeatherData(location.query); if (weather == null) { ctsToken.ThrowIfCancellationRequested(); try { weather = await wm.GetWeather(location); } catch (WeatherException wEx) { weather = null; await Toast.ShowToastAsync(wEx.Message, ToastDuration.Short); } } if (weather == null) { EnableControls(true); return; } ctsToken.ThrowIfCancellationRequested(); // We got our data so disable controls just in case EnableControls(false); // Save weather data Settings.SaveLastGPSLocData(location); await Settings.DeleteLocations(); await Settings.AddLocation(new LocationData(view)); if (wm.SupportsAlerts && weather.weather_alerts != null) { await Settings.SaveWeatherAlerts(location, weather.weather_alerts); } await Settings.SaveWeatherData(weather); Settings.FollowGPS = true; Settings.WeatherLoaded = true; this.Frame.Navigate(typeof(Shell), location); } else { EnableControls(true); } } catch (OperationCanceledException) { // Restore controls EnableControls(true); Settings.FollowGPS = false; Settings.WeatherLoaded = false; } }
private async void Location_QuerySubmitted(AutoSuggestBox sender, AutoSuggestBoxQuerySubmittedEventArgs args) { LocationQueryViewModel query_vm = null; if (args.ChosenSuggestion != null) { // User selected an item from the suggestion list, take an action on it here. var theChosenOne = args.ChosenSuggestion as LocationQueryViewModel; if (!String.IsNullOrEmpty(theChosenOne.LocationQuery)) { query_vm = theChosenOne; } else { query_vm = new LocationQueryViewModel(); } } else if (!String.IsNullOrEmpty(args.QueryText)) { if (cts.Token.IsCancellationRequested) { EnableControls(true); return; } // Use args.QueryText to determine what to do. var result = (await wm.GetLocations(args.QueryText)).First(); if (cts.Token.IsCancellationRequested) { EnableControls(true); return; } if (result != null && !String.IsNullOrWhiteSpace(result.LocationQuery)) { sender.Text = result.LocationName; query_vm = result; } else { query_vm = new LocationQueryViewModel(); } } else if (String.IsNullOrWhiteSpace(args.QueryText)) { // Stop since there is no valid query return; } if (String.IsNullOrWhiteSpace(query_vm.LocationQuery)) { // Stop since there is no valid query return; } // Cancel other tasks cts.Cancel(); cts = new CancellationTokenSource(); var ctsToken = cts.Token; LoadingRing.IsActive = true; if (ctsToken.IsCancellationRequested) { EnableControls(true); return; } // Weather Data var location = new LocationData(query_vm); if (!location.IsValid()) { await Toast.ShowToastAsync(App.ResLoader.GetString("WError_NoWeather"), ToastDuration.Short); EnableControls(true); return; } Weather weather = await Settings.GetWeatherData(location.query); if (weather == null) { try { weather = await wm.GetWeather(location); } catch (WeatherException wEx) { weather = null; await Toast.ShowToastAsync(wEx.Message, ToastDuration.Short); } } if (weather == null) { EnableControls(true); return; } // We got our data so disable controls just in case await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { EnableControls(false); sender.IsSuggestionListOpen = false; }); // Save weather data await Settings.DeleteLocations(); await Settings.AddLocation(location); if (wm.SupportsAlerts && weather.weather_alerts != null) { await Settings.SaveWeatherAlerts(location, weather.weather_alerts); } await Settings.SaveWeatherData(weather); // If we're using search // make sure gps feature is off Settings.FollowGPS = false; Settings.WeatherLoaded = true; await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { this.Frame.Navigate(typeof(Shell), location); }); }
private void AddSearchFragment() { if (mSearchFragment != null) { return; } FragmentTransaction ft = ChildFragmentManager.BeginTransaction(); LocationSearchFragment searchFragment = new LocationSearchFragment(); searchFragment.SetClickListener(async(object sender, RecyclerClickEventArgs e) => { if (mSearchFragment == null) { return; } LocationQueryAdapter adapter = sender as LocationQueryAdapter; LocationQuery v = (LocationQuery)e.View; LocationQueryViewModel query_vm = null; try { if (!String.IsNullOrEmpty(adapter.Dataset[e.Position].LocationQuery)) { query_vm = adapter.Dataset[e.Position]; } } catch (Exception) { query_vm = null; } finally { if (query_vm == null) { query_vm = new LocationQueryViewModel(); } } if (String.IsNullOrWhiteSpace(query_vm.LocationQuery)) { // Stop since there is no valid query return; } // Cancel other tasks mSearchFragment.CtsCancel(); var ctsToken = mSearchFragment.GetCancellationTokenSource().Token; ShowLoading(true); if (ctsToken.IsCancellationRequested) { ShowLoading(false); return; } // Check if location already exists var locData = await Settings.GetLocationData(); if (locData.Exists(l => l.query == query_vm.LocationQuery)) { ShowLoading(false); ExitSearchUi(); return; } if (ctsToken.IsCancellationRequested) { ShowLoading(false); return; } var location = new LocationData(query_vm); if (!location.IsValid()) { Toast.MakeText(App.Context, App.Context.GetString(Resource.String.werror_noweather), ToastLength.Short).Show(); ShowLoading(false); return; } Weather weather = await Settings.GetWeatherData(location.query); if (weather == null) { try { weather = await wm.GetWeather(location); } catch (WeatherException wEx) { weather = null; Toast.MakeText(App.Context, wEx.Message, ToastLength.Short).Show(); } } if (weather == null) { ShowLoading(false); return; } // We got our data so disable controls just in case mAdapter.Dataset.Clear(); mAdapter.NotifyDataSetChanged(); if (mSearchFragment?.View != null && mSearchFragment?.View?.FindViewById(Resource.Id.recycler_view) is RecyclerView recyclerView) { recyclerView.Enabled = false; } // Save data await Settings.AddLocation(location); if (wm.SupportsAlerts && weather.weather_alerts != null) { await Settings.SaveWeatherAlerts(location, weather.weather_alerts); } await Settings.SaveWeatherData(weather); var panel = new LocationPanelViewModel(weather) { LocationData = location }; // Set properties if necessary if (EditMode) { panel.EditMode = true; } int index = mAdapter.Dataset.Count; mAdapter.Add(panel); // Update shortcuts Task.Run(Shortcuts.ShortcutCreator.UpdateShortcuts); // Hide dialog ShowLoading(false); ExitSearchUi(); }); searchFragment.UserVisibleHint = false; ft.Add(Resource.Id.search_fragment_container, searchFragment); ft.CommitAllowingStateLoss(); }
private async void Location_QuerySubmitted(AutoSuggestBox sender, AutoSuggestBoxQuerySubmittedEventArgs args) { LocationQueryViewModel query_vm = null; if (args.ChosenSuggestion != null) { // User selected an item from the suggestion list, take an action on it here. var theChosenOne = args.ChosenSuggestion as LocationQueryViewModel; if (!String.IsNullOrEmpty(theChosenOne.LocationQuery)) { query_vm = theChosenOne; } else { query_vm = new LocationQueryViewModel(); } } else if (!String.IsNullOrEmpty(args.QueryText)) { // Use args.QueryText to determine what to do. var result = (await wm.GetLocations(args.QueryText)).First(); if (result != null && !String.IsNullOrWhiteSpace(result.LocationQuery)) { sender.Text = result.LocationName; query_vm = result; } else { query_vm = new LocationQueryViewModel(); } } else if (String.IsNullOrWhiteSpace(args.QueryText)) { // Stop since there is no valid query return; } if (String.IsNullOrWhiteSpace(query_vm.LocationQuery)) { // Stop since there is no valid query return; } // Cancel other tasks cts.Cancel(); cts = new CancellationTokenSource(); var ctsToken = cts.Token; LoadingRing.IsActive = true; if (ctsToken.IsCancellationRequested) { LoadingRing.IsActive = false; return; } // Check if location already exists var locData = await Settings.GetLocationData(); if (locData.Exists(l => l.query == query_vm.LocationQuery)) { LoadingRing.IsActive = false; ShowAddLocationsPanel(false); return; } if (ctsToken.IsCancellationRequested) { LoadingRing.IsActive = false; return; } var location = new LocationData(query_vm); if (!location.IsValid()) { await Toast.ShowToastAsync(App.ResLoader.GetString("WError_NoWeather"), ToastDuration.Short); LoadingRing.IsActive = false; return; } var weather = await Settings.GetWeatherData(location.query); if (weather == null) { try { weather = await wm.GetWeather(location); } catch (WeatherException wEx) { weather = null; await Toast.ShowToastAsync(wEx.Message, ToastDuration.Short); } } if (weather == null) { LoadingRing.IsActive = false; return; } // We got our data so disable controls just in case sender.IsSuggestionListOpen = false; // Save data await Settings.AddLocation(location); if (wm.SupportsAlerts && weather.weather_alerts != null) { await Settings.SaveWeatherAlerts(location, weather.weather_alerts); } await Settings.SaveWeatherData(weather); var panelView = new LocationPanelViewModel(weather) { LocationData = location }; // Set properties if necessary if (EditMode) { panelView.EditMode = true; } // Add to collection LocationPanels.Add(panelView); // Hide add locations panel LoadingRing.IsActive = false; ShowAddLocationsPanel(false); }