Windows Universal (UWP) Geolocation API Permissions - c#

The new API for Geolocation in Windows Universal (Windows 10 apps) has a new way for allowing access to a user's location.
Starting in Windows 10, call the RequestAccessAsync method before accessing the user’s location. At that time, your app must be in the foreground and RequestAccessAsync must be called from the UI thread.
I'm running some very simple code for Geolocation, on the UI thread as shown below, but I get location permission "denied" every time and no prompt to allow location permissions. Has anyone else run into this? How do I get the prompt to allow location permissions for geolocation in a Windows 10 app?
Geolocation method
private async Task<ForecastRequest> GetPositionAsync()
{
try
{
// Request permission to access location
var accessStatus = await Geolocator.RequestAccessAsync();
if (accessStatus == GeolocationAccessStatus.Allowed)
{
// Get cancellation token
_cts = new CancellationTokenSource();
CancellationToken token = _cts.Token;
// If DesiredAccuracy or DesiredAccuracyInMeters are not set (or value is 0), DesiredAccuracy.Default is used.
Geolocator geolocator = new Geolocator { DesiredAccuracyInMeters = _desireAccuracyInMetersValue };
// Carry out the operation
_pos = await geolocator.GetGeopositionAsync().AsTask(token);
return new ForecastRequest()
{
Lat = (float)_pos.Coordinate.Point.Position.Latitude,
Lon = (float)_pos.Coordinate.Point.Position.Longitude,
Unit = Common.Unit.us
};
}
else
throw new Exception("Problem with location permissions or access");
}
catch (TaskCanceledException tce)
{
throw new Exception("Task cancelled" + tce.Message);
}
finally
{
_cts = null;
}
}
Where it's called:
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
ForecastViewModel vm = await ForecastViewModel.BuildViewModelAsync(await GetPositionAsync());
DataContext = vm.Forecast;
uxForecastList.Visibility = Visibility.Visible;
}

You have to set the "Location" capability. You can do this in the appmanifest.
In the screenshot you find where to set the capability:
Find more info here:
https://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.geolocation.geolocator.aspx (Scroll all down to find info on capabilities)

Related

Why I am getting AADSTS50011 error when using Microsoft OneDrive sample with UWP app

On VS2019, when using this OneDrive sample with UWP from Microsoft, I am getting the following error. An online search shows some relevant links (such as this or this or this) but their context are different (as they are using web apps or Python etc.):
AADSTS50011: The reply URL specified in the request does not match the reply URLs configured for the application: '55dbdbc9-xxxxxxxxxxxxx-a24'
I have followed the sample's instructions for Registering and Configuring the app where Redirect URI I have selected is Public client (mobile & desktop), and have set it's value to https://login.microsoftonline.com/common/oauth2/nativeclient
Question: What I may be doing wrong, and how can we resolve the issue?
UPDATE:
Error occurs at line FolderLoaded?.Invoke(this, EventArgs.Empty); of the method shown below. This is line 180 of file OneDriveList.xaml.cs in the sample. And it is not the error OperationCanceledException since error goes to the second catch statement.
private async Task LoadFolderAsync(string id = null)
{
// Cancel any previous operation
_cancellationTokenSource?.Cancel();
_cancellationTokenSource = new CancellationTokenSource();
// Check if session is set
if (AuthenticationService == null) throw new InvalidOperationException($"No {nameof(AuthenticationService)} has been specified");
// Keep a local copy of the token because the source can change while executing this function
var token = _cancellationTokenSource.Token;
// Add an option to the REST API in order to get thumbnails for each file
// https://learn.microsoft.com/en-us/onedrive/developer/rest-api/api/driveitem_list_thumbnails
var options = new[]
{
new QueryOption("$expand", "thumbnails"),
};
// Create the graph request builder for the drive
IDriveRequestBuilder driveRequest = AuthenticationService.GraphClient.Me.Drive;
// If folder id is null, the request refers to the root folder
IDriveItemRequestBuilder driveItemsRequest;
if (id == null)
{
driveItemsRequest = driveRequest.Root;
}
else
{
driveItemsRequest = driveRequest.Items[id];
}
// Raise the loading event
FolderLoading?.Invoke(this, EventArgs.Empty);
try
{
try
{
// Make a API request loading 50 items per time
var page = await driveItemsRequest.Children.Request(options).Top(50).GetAsync(token);
token.ThrowIfCancellationRequested();
// Load each page
await LoadGridItemsAsync(page, token);
token.ThrowIfCancellationRequested();
}
finally
{
// Raise the loaded event
FolderLoaded?.Invoke(this, EventArgs.Empty);
}
}
catch (OperationCanceledException)
{ }
catch (Exception ex)
{
// Raise the error event
LoadingError?.Invoke(this, ex);
}
}

Getting location while app is terminated in Xamarin?

I have been working on a location-oriented project that I need to be able to track a user's location while the app is terminated.
I have a background service in my Android project and the Geolocator Plugin.
Just for reference, here are my Geolocator settings:
App.xaml.cs
public static async void StartListening()
{
if (CrossGeolocator.Current.IsListening)
return;
CrossGeolocator.Current.DesiredAccuracy = 10;
await CrossGeolocator.Current.StartListeningAsync(TimeSpan.FromSeconds(LOCATION_PING_SECONDS), 1, true, new Plugin.Geolocator.Abstractions.ListenerSettings
{
AllowBackgroundUpdates = true,
PauseLocationUpdatesAutomatically = false
});
CrossGeolocator.Current.PositionChanged += PositionChanged;
CrossGeolocator.Current.PositionError += PositionError;
}
This + my location service for Android work like a charm while the app is running and backgrounded, but obviously everything stops when the app is terminated.
Android/MainActivity.cs
public void StartLocationService()
{
powerManager = (PowerManager) GetSystemService(PowerService);
wakeLock = powerManager.NewWakeLock(WakeLockFlags.Full, "LocationHelper");
// create a new service connection so we can get a binder to the service
locationServiceConnection = new LocationServiceConnection(null);
// this event will fire when the Service connectin in the OnServiceConnected call
locationServiceConnection.ServiceConnected += (object sender, ServiceConnectedEventArgs e) => {
Console.WriteLine("Service Connected");
};
// Starting a service like this is blocking, so we want to do it on a background thread
new Task(() => {
// Start our main service
Console.WriteLine("App", "Calling StartService");
Android.App.Application.Context.StartService(new Intent(Android.App.Application.Context, typeof(LocationService)));
// bind our service (Android goes and finds the running service by type, and puts a reference
// on the binder to that service)
// The Intent tells the OS where to find our Service (the Context) and the Type of Service
// we're looking for (LocationService)
Intent locationServiceIntent = new Intent(Android.App.Application.Context, typeof(LocationService));
Console.WriteLine("App", "Calling service binding");
// Finally, we can bind to the Service using our Intent and the ServiceConnection we
// created in a previous step.
Android.App.Application.Context.BindService(locationServiceIntent, locationServiceConnection, Bind.AutoCreate);
}).Start();
Console.WriteLine("Aquiring Wake Lock");
wakeLock.Acquire();
}
Does anyone know of any tutorials for getting location updates even when the app is terminated? Is this even possible?
Thanks!
Also, I found this Xamarin forum post... The last post says he is able to get updates while the app is terminated from a service, but I have not been able to get the same outcome.

BackgroundTask geofence triggering

I am trying to showToast when the phone leaves or enter the geofenced location (which is set elsewhere and passed in). The issue is that when the app is in the background the trigger does not occur and I don't see the showToast message. I am changing the location manually using an emulator on my PC.
Background Tasks> Location is set under the app manifest.
This is the code I am using to build the Geofence and backgroundtask
//Creates Geofence and names it "PetsnikkerVacationFence"
public static async Task SetupGeofence(double lat, double lon)
{
await RegisterBackgroundTasks();
if (IsTaskRegistered())
{
BasicGeoposition position = new BasicGeoposition();
position.Latitude = lat;
position.Longitude = lon;
double radius = 8046.72; //5 miles in meters
Geocircle geocircle = new Geocircle(position, radius);
MonitoredGeofenceStates monitoredStates = MonitoredGeofenceStates.Entered | MonitoredGeofenceStates.Exited;
Geofence geofence = new Geofence("PetsnikkerVacationFence", geocircle, monitoredStates, false);
GeofenceMonitor monitor = GeofenceMonitor.Current;
var existingFence = monitor.Geofences.SingleOrDefault(f => f.Id == "PetsnikkerVacationFence");
if (existingFence != null)
monitor.Geofences.Remove(existingFence);
monitor.Geofences.Add(geofence);
}
}
//Registers the background task with a LocationTrigger
static async Task RegisterBackgroundTasks()
{
var access = await BackgroundExecutionManager.RequestAccessAsync();
if (access == BackgroundAccessStatus.Denied)
{
}
else
{
var taskBuilder = new BackgroundTaskBuilder();
taskBuilder.Name = "PetsnikkerVacationFence";
taskBuilder.AddCondition(new SystemCondition(SystemConditionType.InternetAvailable));
taskBuilder.SetTrigger(new LocationTrigger(LocationTriggerType.Geofence));
taskBuilder.TaskEntryPoint = typeof(Petsnikker.Windows.Background.GeofenceTask).FullName;
var registration = taskBuilder.Register();
registration.Completed += (sender, e) =>
{
try
{
e.CheckResult();
}
catch (Exception error)
{
Debug.WriteLine(error);
}
};
}
}
static bool IsTaskRegistered()
{
var Registered = false;
var entry = BackgroundTaskRegistration.AllTasks.FirstOrDefault(keyval => keyval.Value.Name == "PetsnikkerVacationFence");
if (entry.Value != null)
Registered = true;
return Registered;
}
}
}
This code is where I monitor the state of the geofence.
This is where the Entry point in the appxmanifest is pointing
public sealed class GeofenceTask : IBackgroundTask
{
public void Run(IBackgroundTaskInstance taskInstance)
{
var monitor = GeofenceMonitor.Current;
if (monitor.Geofences.Any())
{
var reports = monitor.ReadReports();
foreach (var report in reports)
{
switch (report.NewState)
{
case GeofenceState.Entered:
{
ShowToast("Approaching Home",":-)");
break;
}
case GeofenceState.Exited:
{
ShowToast("Leaving Home", ":-)");
break;
}
}
}
}
//deferral.Complete();
}
private static void ShowToast(string firstLine, string secondLine)
{
var toastXmlContent =
ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);
var txtNodes = toastXmlContent.GetElementsByTagName("text");
txtNodes[0].AppendChild(toastXmlContent.CreateTextNode(firstLine));
txtNodes[1].AppendChild(toastXmlContent.CreateTextNode(secondLine));
var toast = new ToastNotification(toastXmlContent);
var toastNotifier = ToastNotificationManager.CreateToastNotifier();
toastNotifier.Show(toast);
Debug.WriteLine("Toast: {0} {1}", firstLine, secondLine);
}
}
After looking at your code, it seems that your code is correct.
In order to fire the Geofence Backgroundtask to show the toast information, please make sure the following things:
1) Please make sure that you have done all the necessary configuration in the Package.appxmanifest for registering the BackgroundTask, for example you have set the correct EntryPoint and added the “Location” capabilities.
For the detailed information, you can try to compare your Package.appxmanifest with the official sample Geolocation’s Package.appxmanifest.
Please also check: Create and register a background task and Declare background tasks in the application manifest.
2) Please make sure that you know how to set the location in the Emulator manually for simulating the phone leave or enter the geofenced location. For more information about how to set location in the emulator, please check the following article:
https://msdn.microsoft.com/library/windows/apps/dn629629.aspx#location_and_driving .
3) Please make sure that your second position in your emulator is not really far away from the geofences that you have defined in the first time, because the emulator behaves like a real device, and the device doesn’t expect to suddenly move from New York to Seattle. Or the BackgroundTask will not be fire immediately.
4) Background tasks for geofencing cannot launch more frequently than every 2 minutes. If you test geofences in the background, the emulator is capable of automatically starting background tasks. But for the next subsequent background tasks, you need to wait for more than 2 minutes.
Besides, I will recommend you refer to the following article about how to use the Windows Phone Emulator for testing apps with geofencing:
https://blogs.windows.com/buildingapps/2014/05/28/using-the-windows-phone-emulator-for-testing-apps-with-geofencing/ .
Thanks.

App Doesn't Crash While Debugging, but Does When Running Normally

System Information
Windows 10 Technical Preview (build 9926)
Visual Studio Community 2013Attempting to debug on:
[AT&T] Lumia 635 (Windows 10 Technical Preview for phones build 9941 w/ Lumia Cyan)
[AT&T] Lumia 1520 (Windows Phone 8.1 with Lumia Denim and PfD)
[Unlocked] BLU Win Jr (Windows Phone 8.1 with PfD)
[Verizon] Lumia Icon (Windows Phone 8.1 with Lumia Denim and PfD)
I trying to get location services working in my app. Previously, I had Visual Studio throw the error. It was an ArgumentException with the message "Use of undefined keyword value 1 for event TaskScheduled in async". Googling didn't turn up any solutions.
Here is the code:
Geolocator Locator = new Geolocator();
Geoposition Position = await Locator.GetGeopositionAsync();
Geocoordinate Coordinate = Position.Coordinate;
When I could get the error to be thrown, the exception was thrown on the 2nd or 3rd line in the sample above.
I simplified the original code to try and fix it, but this is the original:
Geolocator Locator = new Geolocator();
Geocoordinate Coordinate = (await Locator.GetGeopositionAsync()).Position.Coordinate;
The entire app works when debugging, but crashes almost instantaneously otherwise.
This is a Windows 8.1 Universal project, focusing on the phone project.
Thanks in advance
EDIT: As requested, here is the full method:
private static bool CheckConnection()
{
ConnectionProfile connections = NetworkInformation.GetInternetConnectionProfile();
bool internet = connections != null && connections.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess;
return internet;
}
public static async Task<double> GetTemperature(bool Force)
{
if (CheckConnection() || Force)
{
Geolocator Locator = new Geolocator();
await Task.Yield(); //Error occurs here
Geoposition Position = await Locator.GetGeopositionAsync();
Geocoordinate Coordinate = Position.Coordinate;
HttpClient Client = new HttpClient();
double Temperature;
Uri u = new Uri(string.Format("http://api.worldweatheronline.com/free/v1/weather.ashx?q={0},{1}&format=xml&num_of_days=1&date=today&cc=yes&key={2}",
Coordinate.Point.Position.Latitude,
Coordinate.Point.Position.Longitude,
"API KEY"),
UriKind.Absolute);
string Raw = await Client.GetStringAsync(u);
XElement main = XElement.Parse(Raw), current_condition, temp_c;
current_condition = main.Element("current_condition");
temp_c = current_condition.Element("temp_C");
Temperature = Convert.ToDouble(temp_c.Value);
switch (Memory.TempUnit)
{
case 0:
Temperature = Convertions.Temperature.CelsiusToFahrenheit(Temperature);
break;
case 2:
Temperature = Convertions.Temperature.CelsiusToKelvin(Temperature);
break;
}
return Temperature;
}
else
{
throw new InvalidOperationException("Cannot connect to the weather server.");
}
}
EDIT 2: I've asked for help on Twitter, and received a reply asking for a repro project. I recreated the major portion of the original app, but I could not get the error. However, errors may occur for you so here's the project.
EDIT 3: If it helps at all, here are the exception details:
System.ArgumentException occurred
_HResult=-2147024809
_message=Use of undefined keyword value 1 for event TaskScheduled.
HResult=-2147024809
IsTransient=false
Message=Use of undefined keyword value 1 for event TaskScheduled.
Source=mscorlib
StackTrace:
at System.Diagnostics.Tracing.ManifestBuilder.GetKeywords(UInt64 keywords, String eventName)
InnerException:
Having checked this and this, I believe this is a bug in .NET async/await infrastructure for WinRT. I couldn't repro it, but I encourage you to try the following workaround, see if it works for you.
Factor out all asynchronous awaitable calls from OnNavigatedTo into a separate async Task method, e.g. ContinueAsync:
async Task ContinueAsync()
{
Geolocator Locator = new Geolocator();
Geoposition Position = await Locator.GetGeopositionAsync();
Geocoordinate Coordinate = Position.Coordinate;
// ...
var messageDialog = new Windows.UI.Popups.MessageDialog("Hello");
await messageDialog.ShowAsync();
// ...
}
Remove async modifier from OnNavigatedTo and call ContinueAsync from OnNavigatedTo like this:
var scheduler = TaskScheduler.FromCurrentSynchronizationContext();
Task.Factory.StartNew(
() => ContinueAsync(),
CancellationToken.None, TaskCreationOptions.None, scheduler).
Unwrap().
ContinueWith(t =>
{
try
{
t.GetAwaiter().GetResult();
}
catch (Exception ex)
{
Debug.WriteLine(ex);
throw; // re-throw or handle somehow
}
},
CancellationToken.None,
TaskContinuationOptions.NotOnRanToCompletion,
scheduler);
Let us know if it helps :)
Updated, apparently, the bug is somewhere in the TPL logging provider, TplEtwProvider. You can see it's getting created if you add the below code. So far, I couldn't find a way to disable this event source (either directly or via Reflection):
internal class MyEventListener : EventListener
{
protected override void OnEventSourceCreated(EventSource eventSource)
{
base.OnEventSourceCreated(eventSource);
if (eventSource.Name == "System.Threading.Tasks.TplEventSource")
{
var enabled = eventSource.IsEnabled();
// trying to disable - unsupported command :(
System.Diagnostics.Tracing.EventSource.SendCommand(
eventSource, EventCommand.Disable, new System.Collections.Generic.Dictionary<string, string>());
}
}
}
// ...
public sealed partial class App : Application
{
static MyEventListener listener = new MyEventListener();
}

Error when trying to get my current location using Bing Maps in a Windows Store App

I'm developing a Windows Store App where I'm using the Bing Maps control. I created a method that use the Geolocator and GeoPosition to get the users current position.
Also, I enabled the location capability from the manifiest file.
However, everytime when I run the App, the first time I click on the button to get the position I got the following error message: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)).
When I click the second time in the same button to perform the same action, now the error messages disappear and the Bing Maps work properly showing me my current position. But, I'm a little concerned why I got the error messages always the firsr time I try to get the location.
Here are the two methods I execute to get the position:
private async Task SetMyLocation()
{
var position = await GetCurrentPosition();
if (position != null)
{
this.DataContext = position;
this.myLocation = new Location(position.Latitude, position.Longitude);
this.myMap.Center = this.myLocation;
//this.myMap.ZoomLevel = 20;
this.myMap.SetView(myLocation, 12, MapAnimationDuration.Default);
this.AddMyLocationPushpin();
}
}
private async Task<Position> GetCurrentPosition()
{
try
{
Geolocator geolocator = new Geolocator();
geolocator.DesiredAccuracy = PositionAccuracy.High;
geolocator.MovementThreshold = 0;
Geoposition location = await geolocator.GetGeopositionAsync(
maximumAge: TimeSpan.FromMinutes(5),
timeout: TimeSpan.FromSeconds(10)
);
var postion = new Position
{
Latitude = location.Coordinate.Latitude,
Longitude = location.Coordinate.Longitude
};
return postion;
}
catch (Exception ex)
{
. . .
return null;
}
}
Any suggestion, comment why I am getting the above error message? Any clue and/or solution would be OK?
Regards!
Ensure that you have allowed your app to access the user location. Open the Package manifest and go to the capabilities tab. Make sure the Location option is checked. Re-run your app, you will be prompted to allow the app to access your location, allow it. It should then work for you. You can find a blog post example on this here: http://www.bing.com/blogs/site_blogs/b/maps/archive/2012/11/05/getting-started-with-bing-maps-windows-store-apps-native.aspx

Categories