private async Task FetchGeoLocation()
        {
            if (cts.Token.IsCancellationRequested)
            {
                return;
            }

            if (mLocation != null)
            {
                LocationQueryViewModel view = null;

                // Cancel other tasks
                CtsCancel();
                var ctsToken = cts.Token;

                if (ctsToken.IsCancellationRequested)
                {
                    return;
                }

                await Task.Run(async() =>
                {
                    if (ctsToken.IsCancellationRequested)
                    {
                        return;
                    }

                    // Get geo location
                    view = await wm.GetLocation(mLocation);

                    if (String.IsNullOrEmpty(view.LocationQuery))
                    {
                        view = new LocationQueryViewModel();
                    }
                });

                if (String.IsNullOrWhiteSpace(view.LocationQuery))
                {
                    // Stop since there is no valid query
                    return;
                }

                if (ctsToken.IsCancellationRequested)
                {
                    return;
                }

                // Set gps location data
                gpsQuery_vm = view;

                // We got our location data, so setup the widget
                await PrepareWidget();
            }
            else
            {
                await UpdateLocation();
            }
        }
Exemple #2
0
        public async Task <ActionResult> Query(LocationQueryViewModel model)
        {
            if (ModelState.IsValid)
            {
                using (LocationServiceClient client = new LocationServiceClient())
                {
                    await Task.Run(() =>
                    {
                        StringBuilder where = new StringBuilder();
                        if (model != null)
                        {
                            if (model.Level != null)
                            {
                                where.AppendFormat("  Level = '{0}'"
                                                   , Convert.ToInt32(model.Level));
                            }
                            if (!string.IsNullOrEmpty(model.Name))
                            {
                                where.AppendFormat(" {0} Key LIKE '{1}%'"
                                                   , where.Length > 0 ? "AND" : string.Empty
                                                   , model.Name);
                            }

                            if (!string.IsNullOrEmpty(model.ParentLocationName))
                            {
                                where.AppendFormat(" {0} ParentLocationName LIKE '{1}%'"
                                                   , where.Length > 0 ? "AND" : string.Empty
                                                   , model.ParentLocationName);
                            }
                        }
                        PagingConfig cfg = new PagingConfig()
                        {
                            OrderBy = "Key,Level",
                            Where   = where.ToString()
                        };
                        MethodReturnResult <IList <Location> > result = client.Get(ref cfg);

                        if (result.Code == 0)
                        {
                            ViewBag.PagingConfig = cfg;
                            ViewBag.List         = result.Data;
                        }
                    });
                }
            }
            return(PartialView("_ListPartial"));
        }
Exemple #3
0
        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();
        }
Exemple #4
0
        private async Task <LocationData> UpdateLocation()
        {
            LocationData locationData = null;

            if (Settings.FollowGPS)
            {
                if (AppCompatActivity != null && ContextCompat.CheckSelfPermission(AppCompatActivity, Manifest.Permission.AccessFineLocation) != Permission.Granted &&
                    ContextCompat.CheckSelfPermission(AppCompatActivity, Manifest.Permission.AccessCoarseLocation) != Permission.Granted)
                {
                    ActivityCompat.RequestPermissions(AppCompatActivity, new String[] { Manifest.Permission.AccessCoarseLocation, Manifest.Permission.AccessFineLocation },
                                                      PERMISSION_LOCATION_REQUEST_CODE);
                    return(null);
                }

                LocationManager locMan       = (LocationManager)AppCompatActivity.GetSystemService(Context.LocationService);
                bool            isGPSEnabled = locMan.IsProviderEnabled(LocationManager.GpsProvider);
                bool            isNetEnabled = locMan.IsProviderEnabled(LocationManager.NetworkProvider);

                Android.Locations.Location location = null;

                if (isGPSEnabled || isNetEnabled)
                {
                    Criteria locCriteria = new Criteria()
                    {
                        Accuracy = Accuracy.Coarse, CostAllowed = false, PowerRequirement = Power.Low
                    };
                    string provider = locMan.GetBestProvider(locCriteria, true);
                    location = locMan.GetLastKnownLocation(provider);

                    if (location == null)
                    {
                        locMan.RequestSingleUpdate(provider, mLocListnr, null);
                    }
                    else
                    {
                        LocationQueryViewModel view = null;

                        await Task.Run(async() =>
                        {
                            view = await wm.GetLocation(location);

                            if (String.IsNullOrEmpty(view.LocationQuery))
                            {
                                view = new LocationQueryViewModel();
                            }
                        });

                        if (String.IsNullOrWhiteSpace(view.LocationQuery))
                        {
                            // Stop since there is no valid query
                            AppCompatActivity?.RunOnUiThread(() =>
                            {
                                gpsPanelViewModel         = null;
                                gpsPanelLayout.Visibility = ViewStates.Gone;
                            });
                            return(null);
                        }

                        // Save location as last known
                        locationData = new LocationData(view, location);
                    }
                }
                else
                {
                    AppCompatActivity?.RunOnUiThread(() =>
                    {
                        Toast.MakeText(AppCompatActivity, Resource.String.error_retrieve_location, ToastLength.Short).Show();
                        gpsPanelViewModel         = null;
                        gpsPanelLayout.Visibility = ViewStates.Gone;
                    });
                }
            }

            return(locationData);
        }
        private async Task <bool> UpdateLocation()
        {
            bool locationChanged = false;

            if (Settings.FollowGPS)
            {
                if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.AccessFineLocation) != Permission.Granted)
                {
                    return(false);
                }

                Android.Locations.Location location = null;

                if (WearableHelper.IsGooglePlayServicesInstalled && !WearableHelper.HasGPS)
                {
                    var mFusedLocationClient = new FusedLocationProviderClient(this);
                    location = await mFusedLocationClient.GetLastLocationAsync();
                }
                else
                {
                    LocationManager locMan       = GetSystemService(Context.LocationService) as LocationManager;
                    bool            isGPSEnabled = (bool)locMan?.IsProviderEnabled(LocationManager.GpsProvider);
                    bool            isNetEnabled = (bool)locMan?.IsProviderEnabled(LocationManager.NetworkProvider);

                    if (isGPSEnabled || isNetEnabled)
                    {
                        Criteria locCriteria = new Criteria()
                        {
                            Accuracy = Accuracy.Coarse, CostAllowed = false, PowerRequirement = Power.Low
                        };
                        string provider = locMan.GetBestProvider(locCriteria, true);
                        location = locMan.GetLastKnownLocation(provider);
                    }
                    else
                    {
                        Toast.MakeText(this, Resource.String.error_retrieve_location, ToastLength.Short).Show();
                    }
                }

                if (location != null)
                {
                    LocationData lastGPSLocData = await Settings.GetLastGPSLocData();

                    // Check previous location difference
                    if (lastGPSLocData.query != null &&
                        Math.Abs(ConversionMethods.CalculateHaversine(lastGPSLocData.latitude, lastGPSLocData.longitude,
                                                                      location.Latitude, location.Longitude)) < 1600)
                    {
                        return(false);
                    }

                    LocationQueryViewModel view = null;

                    await Task.Run(async() =>
                    {
                        view = await wm.GetLocation(location);

                        if (String.IsNullOrEmpty(view.LocationQuery))
                        {
                            view = new LocationQueryViewModel();
                        }
                    });

                    if (String.IsNullOrWhiteSpace(view.LocationQuery))
                    {
                        // Stop since there is no valid query
                        return(false);
                    }

                    // Save location as last known
                    lastGPSLocData.SetData(view, location);
                    Settings.SaveHomeData(lastGPSLocData);

                    locationChanged = true;
                }
            }

            return(locationChanged);
        }
Exemple #6
0
        private async Task <LocationData> UpdateLocation()
        {
            LocationData locationData = null;

            if (Settings.FollowGPS)
            {
                Geoposition newGeoPos = null;

                try
                {
                    newGeoPos = await geolocal.GetGeopositionAsync(TimeSpan.FromMinutes(15), TimeSpan.FromSeconds(10));
                }
                catch (Exception)
                {
                    var geoStatus = GeolocationAccessStatus.Unspecified;

                    try
                    {
                        geoStatus = await Geolocator.RequestAccessAsync();
                    }
                    catch (Exception ex)
                    {
                        Logger.WriteLine(LoggerLevel.Error, ex, "LocationsPage: error getting location permission");
                    }
                    finally
                    {
                        if (geoStatus == GeolocationAccessStatus.Allowed)
                        {
                            try
                            {
                                newGeoPos = await geolocal.GetGeopositionAsync(TimeSpan.FromMinutes(15), TimeSpan.FromSeconds(10));
                            }
                            catch (Exception ex)
                            {
                                Logger.WriteLine(LoggerLevel.Error, ex, "LocationsPage: error getting location");
                            }
                        }
                        else if (geoStatus == GeolocationAccessStatus.Denied)
                        {
                            // Disable gps feature
                            Settings.FollowGPS   = false;
                            GPSPanelViewModel[0] = null;
                            GPSPanel.Visibility  = Visibility.Collapsed;
                        }
                        else
                        {
                            GPSPanelViewModel[0] = null;
                            GPSPanel.Visibility  = Visibility.Collapsed;
                        }
                    }

                    if (!Settings.FollowGPS)
                    {
                        return(null);
                    }
                }

                // Access to location granted
                if (newGeoPos != null)
                {
                    LocationQueryViewModel view = null;

                    await Task.Run(async() =>
                    {
                        view = await wm.GetLocation(newGeoPos);

                        if (String.IsNullOrEmpty(view.LocationQuery))
                        {
                            view = new LocationQueryViewModel();
                        }
                    });

                    if (String.IsNullOrWhiteSpace(view.LocationQuery))
                    {
                        // Stop since there is no valid query
                        GPSPanelViewModel[0] = null;
                        GPSPanel.Visibility  = Visibility.Collapsed;
                    }

                    // Save location as last known
                    locationData = new LocationData(view, newGeoPos);
                }
            }

            return(locationData);
        }
Exemple #7
0
        private async Task <bool> UpdateLocation()
        {
            bool locationChanged = false;

            if (Settings.DataSync == WearableDataSync.Off &&
                Settings.FollowGPS && (location == null || location.locationType == LocationType.GPS))
            {
                if (Activity != null && ContextCompat.CheckSelfPermission(Activity, Manifest.Permission.AccessFineLocation) != Permission.Granted)
                {
                    RequestPermissions(new String[] { Manifest.Permission.AccessFineLocation },
                                       PERMISSION_LOCATION_REQUEST_CODE);
                    return(false);
                }

                Android.Locations.Location location = null;

                if (WearableHelper.IsGooglePlayServicesInstalled && !WearableHelper.HasGPS)
                {
                    location = await mFusedLocationClient.GetLastLocationAsync();

                    if (location == null)
                    {
                        var mLocationRequest = new LocationRequest();
                        mLocationRequest.SetInterval(10000);
                        mLocationRequest.SetFastestInterval(1000);
                        mLocationRequest.SetPriority(LocationRequest.PriorityHighAccuracy);
                        await mFusedLocationClient.RequestLocationUpdatesAsync(mLocationRequest, mLocCallback, null);

                        await mFusedLocationClient.FlushLocationsAsync();
                    }
                }
                else
                {
                    LocationManager locMan       = Activity?.GetSystemService(Context.LocationService) as LocationManager;
                    bool            isGPSEnabled = (bool)locMan?.IsProviderEnabled(LocationManager.GpsProvider);
                    bool            isNetEnabled = (bool)locMan?.IsProviderEnabled(LocationManager.NetworkProvider);

                    if (isGPSEnabled || isNetEnabled)
                    {
                        Criteria locCriteria = new Criteria()
                        {
                            Accuracy = Accuracy.Coarse, CostAllowed = false, PowerRequirement = Power.Low
                        };
                        string provider = locMan.GetBestProvider(locCriteria, true);
                        location = locMan.GetLastKnownLocation(provider);

                        if (location == null)
                        {
                            locMan.RequestSingleUpdate(provider, mLocListnr, null);
                        }
                    }
                    else
                    {
                        Toast.MakeText(Activity, Resource.String.error_retrieve_location, ToastLength.Short).Show();
                    }
                }

                if (location != null)
                {
                    LocationData lastGPSLocData = await Settings.GetLastGPSLocData();

                    // Check previous location difference
                    if (lastGPSLocData.query != null &&
                        mLocation != null && ConversionMethods.CalculateGeopositionDistance(mLocation, location) < 1600)
                    {
                        return(false);
                    }

                    if (lastGPSLocData.query != null &&
                        Math.Abs(ConversionMethods.CalculateHaversine(lastGPSLocData.latitude, lastGPSLocData.longitude,
                                                                      location.Latitude, location.Longitude)) < 1600)
                    {
                        return(false);
                    }

                    LocationQueryViewModel view = null;

                    await Task.Run(async() =>
                    {
                        view = await wm.GetLocation(location);

                        if (String.IsNullOrEmpty(view.LocationQuery))
                        {
                            view = new LocationQueryViewModel();
                        }
                    });

                    if (String.IsNullOrWhiteSpace(view.LocationQuery))
                    {
                        // Stop since there is no valid query
                        return(false);
                    }

                    // Save location as last known
                    lastGPSLocData.SetData(view, location);
                    Settings.SaveHomeData(lastGPSLocData);

                    this.location   = lastGPSLocData;
                    mLocation       = location;
                    locationChanged = true;
                }
            }

            return(locationChanged);
        }
        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;
            }
        }
 public void SetLocation(LocationQueryViewModel view)
 {
     locationNameView.Text    = view.LocationName;
     locationCountryView.Text = view.LocationCountry;
 }
Exemple #10
0
        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);
        }
Exemple #11
0
        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);
        }
Exemple #12
0
        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);
        }
        private async Task <bool> UpdateLocation()
        {
            bool locationChanged = false;

            if (Settings.FollowGPS && (location == null || location.locationType == LocationType.GPS))
            {
                if (AppCompatActivity != null && ContextCompat.CheckSelfPermission(AppCompatActivity, Manifest.Permission.AccessFineLocation) != Permission.Granted &&
                    ContextCompat.CheckSelfPermission(AppCompatActivity, Manifest.Permission.AccessCoarseLocation) != Permission.Granted)
                {
                    ActivityCompat.RequestPermissions(AppCompatActivity, new String[] { Manifest.Permission.AccessCoarseLocation, Manifest.Permission.AccessFineLocation },
                                                      PERMISSION_LOCATION_REQUEST_CODE);
                    return(false);
                }

                LocationManager locMan       = AppCompatActivity?.GetSystemService(Context.LocationService) as LocationManager;
                bool            isGPSEnabled = (bool)locMan?.IsProviderEnabled(LocationManager.GpsProvider);
                bool            isNetEnabled = (bool)locMan?.IsProviderEnabled(LocationManager.NetworkProvider);

                Android.Locations.Location location = null;

                if (isGPSEnabled || isNetEnabled)
                {
                    Criteria locCriteria = new Criteria()
                    {
                        Accuracy = Accuracy.Coarse, CostAllowed = false, PowerRequirement = Power.Low
                    };
                    string provider = locMan.GetBestProvider(locCriteria, true);
                    location = locMan.GetLastKnownLocation(provider);

                    if (location == null)
                    {
                        locMan.RequestSingleUpdate(provider, mLocListnr, null);
                    }
                    else
                    {
                        LocationData lastGPSLocData = await Settings.GetLastGPSLocData();

                        // Check previous location difference
                        if (lastGPSLocData.query != null &&
                            mLocation != null && ConversionMethods.CalculateGeopositionDistance(mLocation, location) < 1600)
                        {
                            return(false);
                        }

                        if (lastGPSLocData.query != null &&
                            Math.Abs(ConversionMethods.CalculateHaversine(lastGPSLocData.latitude, lastGPSLocData.longitude,
                                                                          location.Latitude, location.Longitude)) < 1600)
                        {
                            return(false);
                        }

                        LocationQueryViewModel view = null;

                        await Task.Run(async() =>
                        {
                            view = await wm.GetLocation(location);

                            if (String.IsNullOrEmpty(view.LocationQuery))
                            {
                                view = new LocationQueryViewModel();
                            }
                        });

                        if (String.IsNullOrWhiteSpace(view.LocationQuery))
                        {
                            // Stop since there is no valid query
                            return(false);
                        }

                        // Save oldkey
                        string oldkey = lastGPSLocData.query;

                        // Save location as last known
                        lastGPSLocData.SetData(view, location);
                        Settings.SaveLastGPSLocData(lastGPSLocData);

                        App.Context.StartService(
                            new Intent(App.Context, typeof(WearableDataListenerService))
                            .SetAction(WearableDataListenerService.ACTION_SENDLOCATIONUPDATE));

                        this.location = lastGPSLocData;
                        mLocation     = location;

                        // Update widget ids for location
                        if (oldkey != null && WidgetUtils.Exists(oldkey))
                        {
                            WidgetUtils.UpdateWidgetIds(oldkey, lastGPSLocData);
                        }

                        locationChanged = true;
                    }
                }
                else
                {
                    AppCompatActivity?.RunOnUiThread(() =>
                    {
                        Toast.MakeText(AppCompatActivity, Resource.String.error_retrieve_location, ToastLength.Short).Show();
                    });
                }
            }

            return(locationChanged);
        }
Exemple #14
0
        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);
        }
Exemple #15
0
        private async Task <bool> UpdateLocation()
        {
            bool locationChanged = false;

            if (Settings.FollowGPS && (location == null || location.locationType == LocationType.GPS))
            {
                Geoposition newGeoPos = null;

                try
                {
                    newGeoPos = await geolocal.GetGeopositionAsync(TimeSpan.FromMinutes(15), TimeSpan.FromSeconds(10));
                }
                catch (Exception)
                {
                    var geoStatus = GeolocationAccessStatus.Unspecified;

                    try
                    {
                        geoStatus = await Geolocator.RequestAccessAsync();
                    }
                    catch (Exception ex)
                    {
                        Logger.WriteLine(LoggerLevel.Error, ex, "WeatherNow: GetWeather error");
                    }
                    finally
                    {
                        if (geoStatus == GeolocationAccessStatus.Allowed)
                        {
                            try
                            {
                                newGeoPos = await geolocal.GetGeopositionAsync(TimeSpan.FromMinutes(15), TimeSpan.FromSeconds(10));
                            }
                            catch (Exception ex)
                            {
                                Logger.WriteLine(LoggerLevel.Error, ex, "WeatherNow: GetWeather error");
                            }
                        }
                        else if (geoStatus == GeolocationAccessStatus.Denied)
                        {
                            // Disable gps feature
                            Settings.FollowGPS = false;
                        }
                    }

                    if (!Settings.FollowGPS)
                    {
                        return(false);
                    }
                }

                // Access to location granted
                if (newGeoPos != null)
                {
                    LocationData lastGPSLocData = await Settings.GetLastGPSLocData();

                    // Check previous location difference
                    if (lastGPSLocData.query != null &&
                        geoPos != null && ConversionMethods.CalculateGeopositionDistance(geoPos, newGeoPos) < geolocal.MovementThreshold)
                    {
                        return(false);
                    }

                    if (lastGPSLocData.query != null &&
                        Math.Abs(ConversionMethods.CalculateHaversine(lastGPSLocData.latitude, lastGPSLocData.longitude,
                                                                      newGeoPos.Coordinate.Point.Position.Latitude, newGeoPos.Coordinate.Point.Position.Longitude)) < geolocal.MovementThreshold)
                    {
                        return(false);
                    }

                    LocationQueryViewModel view = null;

                    await Task.Run(async() =>
                    {
                        view = await wm.GetLocation(newGeoPos);

                        if (String.IsNullOrEmpty(view.LocationQuery))
                        {
                            view = new LocationQueryViewModel();
                        }
                    });

                    if (String.IsNullOrWhiteSpace(view.LocationQuery))
                    {
                        // Stop since there is no valid query
                        return(false);
                    }

                    // Save oldkey
                    string oldkey = lastGPSLocData.query;

                    // Save location as last known
                    lastGPSLocData.SetData(view, newGeoPos);
                    Settings.SaveLastGPSLocData(lastGPSLocData);

                    // Update tile id for location
                    if (oldkey != null && SecondaryTileUtils.Exists(oldkey))
                    {
                        await SecondaryTileUtils.UpdateTileId(oldkey, lastGPSLocData.query);
                    }

                    location        = lastGPSLocData;
                    geoPos          = newGeoPos;
                    locationChanged = true;
                }
            }

            return(locationChanged);
        }
        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);
            });
        }
Exemple #17
0
        private async void LocationSearchFragment_clickListener(object sender, RecyclerClickEventArgs e)
        {
            // Get selected query view
            LocationQuery          v        = (LocationQuery)e.View;
            LocationQueryViewModel query_vm = null;

            try
            {
                if (!String.IsNullOrEmpty(mAdapter.Dataset[e.Position].LocationQuery))
                {
                    query_vm = mAdapter.Dataset[e.Position];
                }
            }
            catch (ArgumentOutOfRangeException)
            {
                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;
            }

            if (Settings.UsePersonalKey && String.IsNullOrWhiteSpace(Settings.API_KEY) && wm.KeyRequired)
            {
                Toast.MakeText(App.Context, App.Context.GetString(Resource.String.werror_invalidkey), ToastLength.Short).Show();
                return;
            }

            // Cancel pending searches
            CtsCancel();
            var ctsToken = cts.Token;

            ShowLoading(true);

            if (ctsToken.IsCancellationRequested)
            {
                ShowLoading(false);
                return;
            }

            // Get Weather Data
            var location = new WeatherData.LocationData(query_vm);

            if (!location.IsValid())
            {
                Toast.MakeText(App.Context, App.Context.GetString(Resource.String.werror_noweather), ToastLength.Short).Show();
                ShowLoading(false);
                return;
            }
            WeatherData.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();
            mRecyclerView.Enabled = 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;

            // Send data for wearables
            mActivity.StartService(new Intent(mActivity, typeof(WearableDataListenerService))
                                   .SetAction(WearableDataListenerService.ACTION_SENDSETTINGSUPDATE));
            mActivity.StartService(new Intent(mActivity, typeof(WearableDataListenerService))
                                   .SetAction(WearableDataListenerService.ACTION_SENDLOCATIONUPDATE));
            mActivity.StartService(new Intent(mActivity, typeof(WearableDataListenerService))
                                   .SetAction(WearableDataListenerService.ACTION_SENDWEATHERUPDATE));

            if (mAppWidgetId == AppWidgetManager.InvalidAppwidgetId)
            {
                // Start WeatherNow Activity with weather data
                Intent intent = new Intent(mActivity, typeof(MainActivity));
                intent.PutExtra("data", location.ToJson());

                mActivity.StartActivity(intent);
                mActivity.FinishAffinity();
            }
            else
            {
                // Create return intent
                Intent resultValue = new Intent();
                resultValue.PutExtra(AppWidgetManager.ExtraAppwidgetId, mAppWidgetId);
                resultValue.PutExtra("data", location.ToJson());
                mActivity.SetResult(Android.App.Result.Ok, resultValue);
                mActivity.Finish();
            }
        }
        private void AddSearchFragment()
        {
            if (mSearchFragment != null)
            {
                return;
            }

            var ft             = SupportFragmentManager.BeginTransaction();
            var searchFragment = new LocationSearchFragment();

            searchFragment.SetClickListener((object sender, RecyclerClickEventArgs e) =>
            {
                var adapter = sender as LocationQueryAdapter;
                var v       = (LocationQuery)e.View;

                if (!String.IsNullOrEmpty(adapter.Dataset[e.Position].LocationQuery))
                {
                    query_vm = adapter.Dataset[e.Position];
                }
                else
                {
                    query_vm = null;
                }

                if (String.IsNullOrWhiteSpace(query_vm.LocationQuery))
                {
                    // Stop since there is no valid query
                    query_vm = null;
                    return;
                }

                // Cancel other tasks
                mSearchFragment.CtsCancel();

                ShowLoading(true);

                if (mSearchFragment.CtsCancelRequested())
                {
                    ShowLoading(false);
                    query_vm = null;
                    return;
                }

                // Check if location already exists
                if (Favorites.FirstOrDefault(l => l.query == query_vm.LocationQuery) is LocationData loc)
                {
                    ShowLoading(false);
                    ExitSearchUi();

                    // Set selection
                    query_vm = null;
                    locSpinner.SetSelection(
                        locAdapter.GetPosition(new ComboBoxItem(loc.name, loc.query)));
                    return;
                }

                if (mSearchFragment.CtsCancelRequested())
                {
                    ShowLoading(false);
                    query_vm = null;
                    return;
                }

                // We got our data so disable controls just in case
                adapter.Dataset.Clear();
                adapter.NotifyDataSetChanged();
                searchFragment.View.FindViewById <RecyclerView>(Resource.Id.recycler_view).Enabled = false;

                // Save data
                var item = new ComboBoxItem(query_vm.LocationName, query_vm.LocationQuery);
                var idx  = locAdapter.Count - 1;
                locAdapter.Insert(item, idx);
                locSpinner.SetSelection(idx);
                locSummary.Text = item.Display;

                // Hide dialog
                ShowLoading(false);
                ExitSearchUi();
            });
            searchFragment.UserVisibleHint = false;
            ft.Add(Resource.Id.search_fragment_container, searchFragment);
            ft.CommitAllowingStateLoss();
        }
Exemple #19
0
        private async void LocationSearchFragment_clickListener(object sender, RecyclerClickEventArgs e)
        {
            // Get selected query view
            LocationQuery          v        = (LocationQuery)e.View;
            LocationQueryViewModel query_vm = null;

            if (!String.IsNullOrEmpty(mAdapter.Dataset[e.Position].LocationQuery))
            {
                query_vm = mAdapter.Dataset[e.Position];
            }
            else
            {
                query_vm = new LocationQueryViewModel();
            }

            if (String.IsNullOrWhiteSpace(query_vm.LocationQuery))
            {
                // Stop since there is no valid query
                return;
            }

            if (Settings.UsePersonalKey && String.IsNullOrWhiteSpace(Settings.API_KEY) && wm.KeyRequired)
            {
                Toast.MakeText(App.Context, App.Context.GetString(Resource.String.werror_invalidkey), ToastLength.Short).Show();
                return;
            }

            // Cancel pending searches
            cts.Cancel();
            cts = new CancellationTokenSource();
            var ctsToken = cts.Token;

            ShowLoading(true);

            if (ctsToken.IsCancellationRequested)
            {
                ShowLoading(false);
                return;
            }

            // Get Weather Data
            var location = new WeatherData.LocationData(query_vm);
            var 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();
            mRecyclerView.Enabled = false;

            // Save weather data
            Settings.SaveHomeData(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;

            // Start WeatherNow Activity with weather data
            Intent intent = new Intent(mActivity, typeof(MainActivity));

            intent.PutExtra("data", location.ToJson());

            mActivity.StartActivity(intent);
            mActivity.FinishAffinity();
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Set the result to CANCELED.  This will cause the widget host to cancel
            // out of the widget placement if they press the back button.
            SetResult(Result.Canceled, new Intent().PutExtra(AppWidgetManager.ExtraAppwidgetId, mAppWidgetId));

            // Find the widget id from the intent.
            if (Intent != null && Intent.Extras != null)
            {
                mAppWidgetId = Intent.GetIntExtra(AppWidgetManager.ExtraAppwidgetId, AppWidgetManager.InvalidAppwidgetId);
            }

            if (mAppWidgetId == AppWidgetManager.InvalidAppwidgetId)
            {
                // If they gave us an intent without the widget id, just bail.
                Finish();
            }

            SetContentView(Resource.Layout.activity_widget_setup);

            wm = WeatherManager.GetInstance();

            // Setup location spinner
            locSpinner = FindViewById <Spinner>(Resource.Id.location_pref_spinner);
            locSummary = FindViewById <TextView>(Resource.Id.location_pref_summary);

            var comboList = new List <ComboBoxItem>()
            {
                new ComboBoxItem(GetString(Resource.String.pref_item_gpslocation), "GPS"),
                new ComboBoxItem(GetString(Resource.String.label_btn_add_location), "Search")
            };
            var favs = Task.Run(Settings.GetFavorites).Result;

            Favorites = new ReadOnlyCollection <LocationData>(favs);
            foreach (LocationData location in Favorites)
            {
                comboList.Insert(comboList.Count - 1, new ComboBoxItem(location.name, location.query));
            }

            locAdapter = new ArrayAdapter <ComboBoxItem>(
                this, Android.Resource.Layout.SimpleSpinnerItem,
                comboList);
            locAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
            locAdapter.SetNotifyOnChange(true);
            locSpinner.Adapter = locAdapter;

            FindViewById(Resource.Id.location_pref).Click += (object sender, EventArgs e) =>
            {
                locSpinner.PerformClick();
            };
            locSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) =>
            {
                CtsCancel();

                if (locSpinner.SelectedItem is ComboBoxItem item)
                {
                    locSummary.Text = item.Display;

                    if (item.Value.Equals("Search"))
                    {
                        mActionMode = StartSupportActionMode(mActionModeCallback);
                    }
                    else
                    {
                        selectedItem = item;
                    }
                }
                else
                {
                    selectedItem = null;
                }
                query_vm = null;
            };
            locSpinner.SetSelection(0);

            // Setup interval spinner
            refreshSpinner     = FindViewById <Spinner>(Resource.Id.interval_pref_spinner);
            var refreshSummary = FindViewById <TextView>(Resource.Id.interval_pref_summary);
            var refreshList    = new List <ComboBoxItem>();
            var refreshEntries = this.Resources.GetStringArray(Resource.Array.refreshinterval_entries);
            var refreshValues  = this.Resources.GetStringArray(Resource.Array.refreshinterval_values);

            for (int i = 0; i < refreshEntries.Length; i++)
            {
                refreshList.Add(new ComboBoxItem(refreshEntries[i], refreshValues[i]));
            }
            var refreshAdapter = new ArrayAdapter <ComboBoxItem>(
                this, Android.Resource.Layout.SimpleSpinnerItem,
                refreshList);

            refreshAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
            refreshSpinner.Adapter = refreshAdapter;
            FindViewById(Resource.Id.interval_pref).Click += (object sender, EventArgs e) =>
            {
                refreshSpinner.PerformClick();
            };
            refreshSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) =>
            {
                if (refreshSpinner.SelectedItem is ComboBoxItem item)
                {
                    refreshSummary.Text = item.Display;
                }
            };
            refreshSpinner.SetSelection(
                refreshList.FindIndex(item => item.Value.Equals(Settings.RefreshInterval.ToString())));

            SetSupportActionBar(FindViewById <Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar));
            SupportActionBar.SetDisplayHomeAsUpEnabled(true);
            SupportActionBar.SetHomeAsUpIndicator(Resource.Drawable.ic_arrow_back_white_24dp);

            mActionModeCallback.CreateActionMode  += OnCreateActionMode;
            mActionModeCallback.DestroyActionMode += OnDestroyActionMode;

            FindViewById(Resource.Id.search_fragment_container).Click += delegate
            {
                ExitSearchUi();
            };

            appBarLayout      = FindViewById <AppBarLayout>(Resource.Id.app_bar);
            collapsingToolbar = FindViewById <CollapsingToolbarLayout>(Resource.Id.collapsing_toolbar);

            cts = new CancellationTokenSource();

            // Location Listener
            mLocListnr = new LocationListener();
            mLocListnr.LocationChanged += async(Android.Locations.Location location) =>
            {
                mLocation = location;
                await FetchGeoLocation();
            };

            if (!Settings.WeatherLoaded)
            {
                Toast.MakeText(this, GetString(Resource.String.prompt_setup_app_first), ToastLength.Short).Show();

                Intent intent = new Intent(this, typeof(SetupActivity))
                                .SetAction(AppWidgetManager.ActionAppwidgetConfigure)
                                .PutExtra(AppWidgetManager.ExtraAppwidgetId, mAppWidgetId);
                StartActivityForResult(intent, SETUP_REQUEST_CODE);
            }
        }
        public async Task FetchGeoLocation()
        {
            try
            {
                gpsFollowButton.Enabled = false;

                if (mLocation != null)
                {
                    LocationQueryViewModel view = null;

                    // Cancel other tasks
                    cts?.Cancel();
                    cts = new CancellationTokenSource();
                    var ctsToken = cts.Token;

                    ctsToken.ThrowIfCancellationRequested();

                    // Show loading bar
                    RunOnUiThread(() => progressBar.Visibility = ViewStates.Visible);

                    await Task.Run(async() =>
                    {
                        ctsToken.ThrowIfCancellationRequested();

                        // Get geo location
                        view = await wm.GetLocation(mLocation);

                        if (String.IsNullOrEmpty(view.LocationQuery))
                        {
                            view = new LocationQueryViewModel();
                        }
                    });

                    if (String.IsNullOrWhiteSpace(view.LocationQuery))
                    {
                        // Stop since there is no valid query
                        EnableControls(true);
                        return;
                    }

                    if (Settings.UsePersonalKey && String.IsNullOrWhiteSpace(Settings.API_KEY) && wm.KeyRequired)
                    {
                        RunOnUiThread(() =>
                        {
                            Toast.MakeText(this.ApplicationContext, Resource.String.werror_invalidkey, ToastLength.Short).Show();
                        });
                        EnableControls(true);
                        return;
                    }

                    ctsToken.ThrowIfCancellationRequested();

                    // Get Weather Data
                    var location = new WeatherData.LocationData(view, mLocation);
                    if (!location.IsValid())
                    {
                        RunOnUiThread(() =>
                        {
                            Toast.MakeText(App.Context, App.Context.GetString(Resource.String.werror_noweather), ToastLength.Short).Show();
                        });
                        EnableControls(true);
                        return;
                    }

                    ctsToken.ThrowIfCancellationRequested();

                    var weather = await Settings.GetWeatherData(location.query);

                    if (weather == null)
                    {
                        ctsToken.ThrowIfCancellationRequested();

                        try
                        {
                            weather = await Task.Run(() => wm.GetWeather(location), ctsToken);
                        }
                        catch (WeatherException wEx)
                        {
                            weather = null;
                            RunOnUiThread(() =>
                            {
                                Toast.MakeText(App.Context, wEx.Message, ToastLength.Short).Show();
                            });
                        }
                    }

                    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 WeatherData.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;

                    // Send data for wearables
                    StartService(new Intent(this, typeof(WearableDataListenerService))
                                 .SetAction(WearableDataListenerService.ACTION_SENDSETTINGSUPDATE));
                    StartService(new Intent(this, typeof(WearableDataListenerService))
                                 .SetAction(WearableDataListenerService.ACTION_SENDLOCATIONUPDATE));
                    StartService(new Intent(this, typeof(WearableDataListenerService))
                                 .SetAction(WearableDataListenerService.ACTION_SENDWEATHERUPDATE));

                    if (mAppWidgetId == AppWidgetManager.InvalidAppwidgetId)
                    {
                        // Start WeatherNow Activity with weather data
                        Intent intent = new Intent(this, typeof(MainActivity));
                        intent.PutExtra("data", location.ToJson());

                        StartActivity(intent);
                        FinishAffinity();
                    }
                    else
                    {
                        // Create return intent
                        Intent resultValue = new Intent();
                        resultValue.PutExtra(AppWidgetManager.ExtraAppwidgetId, mAppWidgetId);
                        resultValue.PutExtra("data", location.ToJson());
                        SetResult(Android.App.Result.Ok, resultValue);
                        Finish();
                    }
                }
                else
                {
                    await UpdateLocation();
                }
            }
            catch (System.OperationCanceledException)
            {
                // Restore controls
                EnableControls(true);
                Settings.FollowGPS     = false;
                Settings.WeatherLoaded = false;
            }
        }
        public async Task FetchGeoLocation()
        {
            RunOnUiThread(() =>
            {
                locationButton.Enabled = false;
            });

            if (mLocation != null)
            {
                LocationQueryViewModel view = null;

                // Cancel other tasks
                cts.Cancel();
                cts = new CancellationTokenSource();
                var ctsToken = cts.Token;

                if (ctsToken.IsCancellationRequested)
                {
                    EnableControls(true);
                    return;
                }

                // Show loading bar
                RunOnUiThread(() =>
                {
                    progressBar.Visibility = ViewStates.Visible;
                });

                await Task.Run(async() =>
                {
                    if (ctsToken.IsCancellationRequested)
                    {
                        EnableControls(true);
                        return;
                    }

                    // Get geo location
                    view = await wm.GetLocation(mLocation);

                    if (String.IsNullOrEmpty(view.LocationQuery))
                    {
                        view = new LocationQueryViewModel();
                    }
                });

                if (String.IsNullOrWhiteSpace(view.LocationQuery))
                {
                    // Stop since there is no valid query
                    EnableControls(true);
                    return;
                }

                if (Settings.UsePersonalKey && String.IsNullOrWhiteSpace(Settings.API_KEY) && wm.KeyRequired)
                {
                    RunOnUiThread(() =>
                    {
                        Toast.MakeText(this.ApplicationContext, Resource.String.werror_invalidkey, ToastLength.Short).Show();
                        EnableControls(true);
                    });
                    return;
                }

                if (ctsToken.IsCancellationRequested)
                {
                    EnableControls(true);
                    return;
                }

                // Get Weather Data
                var location = new WeatherData.LocationData(view, mLocation);
                var weather  = await Settings.GetWeatherData(location.query);

                if (weather == null)
                {
                    try
                    {
                        weather = await wm.GetWeather(location);
                    }
                    catch (WeatherException wEx)
                    {
                        weather = null;
                        RunOnUiThread(() =>
                        {
                            Toast.MakeText(App.Context, wEx.Message, ToastLength.Short).Show();
                        });
                    }
                }

                if (weather == null)
                {
                    EnableControls(true);
                    return;
                }

                // We got our data so disable controls just in case
                EnableControls(false);

                // Save weather data
                Settings.SaveHomeData(location);
                if (wm.SupportsAlerts && weather.weather_alerts != null)
                {
                    await Settings.SaveWeatherAlerts(location, weather.weather_alerts);
                }
                await Settings.SaveWeatherData(weather);

                Settings.FollowGPS     = true;
                Settings.WeatherLoaded = true;

                // Start WeatherNow Activity with weather data
                Intent intent = new Intent(this, typeof(MainActivity));
                intent.PutExtra("data", location.ToJson());

                StartActivity(intent);
                FinishAffinity();
            }
            else
            {
                await UpdateLocation();
            }
        }
        private async Task <bool> UpdateLocation()
        {
            bool locationChanged = false;

            if (Settings.FollowGPS)
            {
                Geoposition newGeoPos = null;
                Geolocator  geolocal  = new Geolocator()
                {
                    DesiredAccuracyInMeters = 5000, ReportInterval = 900000, MovementThreshold = 1600
                };

                try
                {
                    cts.Token.ThrowIfCancellationRequested();
                    newGeoPos = await geolocal.GetGeopositionAsync(TimeSpan.FromMinutes(15), TimeSpan.FromSeconds(10)).AsTask(cts.Token);
                }
                catch (OperationCanceledException)
                {
                    return(locationChanged);
                }
                catch (Exception)
                {
                    var geoStatus = GeolocationAccessStatus.Unspecified;

                    try
                    {
                        cts.Token.ThrowIfCancellationRequested();
                        geoStatus = await Geolocator.RequestAccessAsync().AsTask(cts.Token);
                    }
                    catch (OperationCanceledException)
                    {
                        return(locationChanged);
                    }
                    catch (Exception ex)
                    {
                        Logger.WriteLine(LoggerLevel.Error, ex, "{0}: error requesting location permission", taskName);
                    }
                    finally
                    {
                        if (!cts.IsCancellationRequested && geoStatus == GeolocationAccessStatus.Allowed)
                        {
                            try
                            {
                                newGeoPos = await geolocal.GetGeopositionAsync(TimeSpan.FromMinutes(15), TimeSpan.FromSeconds(10)).AsTask(cts.Token);
                            }
                            catch (Exception ex)
                            {
                                Logger.WriteLine(LoggerLevel.Error, ex, "{0}: GetWeather error", taskName);
                            }
                        }
                    }
                }

                // Access to location granted
                if (newGeoPos != null)
                {
                    var lastGPSLocData = await Settings.GetLastGPSLocData();

                    if (cts.IsCancellationRequested)
                    {
                        return(locationChanged);
                    }

                    // Check previous location difference
                    if (lastGPSLocData.query != null &&
                        Math.Abs(ConversionMethods.CalculateHaversine(lastGPSLocData.latitude, lastGPSLocData.longitude,
                                                                      newGeoPos.Coordinate.Point.Position.Latitude, newGeoPos.Coordinate.Point.Position.Longitude)) < geolocal.MovementThreshold)
                    {
                        return(false);
                    }

                    LocationQueryViewModel view = null;

                    await Task.Run(async() =>
                    {
                        view = await wm.GetLocation(newGeoPos);

                        if (String.IsNullOrEmpty(view.LocationQuery))
                        {
                            view = new LocationQueryViewModel();
                        }
                    }, cts.Token);

                    if (String.IsNullOrWhiteSpace(view.LocationQuery))
                    {
                        // Stop since there is no valid query
                        return(false);
                    }

                    if (cts.IsCancellationRequested)
                    {
                        return(locationChanged);
                    }

                    // Save oldkey
                    string oldkey = lastGPSLocData.query;

                    // Save location as last known
                    lastGPSLocData.SetData(view, newGeoPos);
                    Settings.SaveLastGPSLocData(lastGPSLocData);

                    // Update tile id for location
                    if (oldkey != null && SecondaryTileUtils.Exists(oldkey))
                    {
                        await SecondaryTileUtils.UpdateTileId(oldkey, lastGPSLocData.query);
                    }

                    locationChanged = true;
                }
            }

            return(locationChanged);
        }