Geolocator.RequestAccessAsync throws "method called at unexpected time" exception - exception

I have a chunk of code I use to get device location. This is done in a monogame windows uwp project. The following code worked before (I was on VS2015 Community). I recent did a fresh OS and install VS2017 Community. I finally got my project to build and run. The only thing not working is the Geolocator.RequestAccessAsync is throwing a "method called at unexpected time" exception. Any ideas?
public async Task<Vector2> GetDeviceGps()
{
var accessStatus = await Geolocator.RequestAccessAsync();
switch (accessStatus)
{
case GeolocationAccessStatus.Allowed:
// If DesiredAccuracy or DesiredAccuracyInMeters are not set (or value is 0), DesiredAccuracy.Default is used.
Geolocator geolocator = new Geolocator { DesiredAccuracyInMeters = 10 };
// Subscribe to the StatusChanged event to get updates of location status changes.
//geolocator.StatusChanged += OnStatusChanged;
// Carry out the operation.
Geoposition pos = await geolocator.GetGeopositionAsync();
return new Vector2((float)pos.Coordinate.Point.Position.Longitude, (float)pos.Coordinate.Point.Position.Latitude);
case GeolocationAccessStatus.Denied:
//Do something!
break;
case GeolocationAccessStatus.Unspecified:
//Murp
break;
}
return Vector2.Zero;
}
This is invoked and handled like so (called from update method of game):
mapper.GetDeviceGps().ContinueWith(pos =>
{
Vector2 bob = pos.Result;
});

When you run the RequestAccessAsync for the first time in your app, the user will be asked to grant your app the location permission. Therefore the method needs to be executed in the UI thread.

Related

getUser does not work in 4.0.4 master webchat client

I downloaded today the last release (4.0.4, from yesterday) of the webchat client from github and deployed in in my website.
I have detected that Smooch.getUser() returns 'undefined' when a new user is detected until this new user send his first message, but it doesn't happen on returning users.
<script>
Smooch.on('ready', function(){
console.log('the init has completed!');
});
var skPromise = Smooch.init({appId: 'myAppId'});
skPromise.then(
function()
{
var u = Smooch.getUser();
console.log(u._id);
});
);
</script>
smooch_local.html:26 Uncaught (in promise) TypeError: Cannot read property '_id' of undefined
at smooch_local.html:26
at anonymous
But, if i send any message after the promise has resolved, and later I try to recover the userId, the variable gets defined. It didn't happen in this way in previous 3.x.x releases of the Web Messenger chat.
This code returns a valid userId:
<script>
Smooch.on('ready', function(){
console.log('the init has completed!');
});
var skPromise = Smooch.init({appId: 'myAppId'});
skPromise.then(
function()
{
Smooch.sendMessage({type: 'text', text: 'x'}).then(
function(){
var u = Smooch.getUser();
console.log(u._id);
});
}
);
</script>
This is the console ouptut:
12:21:20.165 the init has completed!
12:21:22.947 smooch_local.html:28 1102fdee2b7d3c2abb639cbe
Does anyone knows if it's a bug or a new feature from v4.x releases?
Thanks
This is expected behaviour for Web Messenger 4.x - users are no longer automatically created at init time. Instead, user creation is deferred until after they send a message. This was mentioned in the release notes for v4.0.0
Web Messenger now uses a new optimized initialization sequence. This new sequence alters the timing of key events such as creating a new user or establishing a websocket connection.
Alternatively, you can pre-create a user with a userId before the Web Messenger is initialized, and use the login method to initialize as that user, but this may or may not be appropriate depending on your use case.

How to keep event handlers alive in Actionscript 3

I have a Flex app that connects to a JBoss/MS-SQL back-end. Some of our customers have a proxy server in front of their JBoss with a timeout of 90 seconds. In our application there are searches that can take up to 2-3 minutes for complex criteria. Since the proxy isn't smart enough to recognize AMF's keep alive pings for what they are the proxy sends a 503 to the client, which in Flex land becomes a "Channel Call Failed" event. In searching SO and other places, this seems to be a common problem. We can't do anything about the proxy or lengthen the timeout, the application needs to handle it.
Of course the back-end continues to process and eventually ships the results to the client. But the user gets an ugly error message and assumes the app is broke.
The solution I have settled on is to consume the CCF error and have the client continue to wait. I have managed the first part, but I can't figure out how to keep the client's handlers active to receive the data (and/or consume another timeout if necessary).
Current error handler:
private function handleSearchError(event : FaultEvent) : void {
if (event.fault.faultCode == "Channel.Call.Failed") {
event.stopImmediatePropagation(); // doesn't seem to help
return;
}
if (searchProgress != null) {
PopUpManager.removePopUp(searchProgress);
searchProgress = null;
}
etc...
}
This is the setup:
<mx:Button id="btnSearch" label="
{resourceManager.getString('recon_perspective',
'ReconPerspective.ReconView.search')}" icon="{iconSearch}"
click="handleSearch()" includeIn="search, default"/>
And:
<mx:method name="search" result="event.token.resultHandler(event);"
fault="handleSearchError(event);"/>
Kicking off the call:
var token : AsyncToken = null;
token = sMSrv.search(searchType.toString(), getSearchMode(), criteria,
smartMatchParent.isArchiveMode);
searchProgress = LoadProgress(PopUpManager.createPopUp
(FlexGlobals.topLevelApplication as DisplayObject, LoadProgress, true));
searchProgress.title = resourceManager.getString('matching', 'smartmatch.loading.trans');
searchProgress.token = token;
searchProgress.showCancelButton = true;
PopUpManager.centerPopUp(searchProgress);
token.resultHandler = handleSearchResults;
token.cancelSearch = false;
So my question is how do I keep handleSearch and handleSearchError alive to consume the events from the server?
I verified that the data comes back from the server using WebDeveloper in the browser to watch the network traffic and if you cause the app to refresh that screen, the data gets displayed.
I'm very in experienced but would this help?
private function handleSearchError(event : FaultEvent) : void {
if (event.fault.faultCode == "Channel.Call.Failed") {
event.stopImmediatePropagation(); // doesn't seem to help
if(event.isImmediatePropagationStopped(true)) {
//After stopped do something here?
}
return;
}
if (searchProgress != null) {
PopUpManager.removePopUp(searchProgress);
searchProgress = null;
}
etc...
}

Windows Phone app not receiving push notification from Parse.com

I have followed this tutorial on setting up Parse push notification in a Windows Phone app. This is my code:
public App() {
// Global handler for uncaught exceptions.
UnhandledException += Application_UnhandledException;
// Standard XAML initialization
InitializeComponent();
// Phone-specific initialization
InitializePhoneApplication();
// Language display initialization
InitializeLanguage();
// Show graphics profiling information while debugging.
if (Debugger.IsAttached) {
// Display the current frame rate counters.
Application.Current.Host.Settings.EnableFrameRateCounter = true;
// Show the areas of the app that are being redrawn in each frame.
//Application.Current.Host.Settings.EnableRedrawRegions = true;
// Enable non-production analysis visualization mode,
// which shows areas of a page that are handed off to GPU with a colored overlay.
//Application.Current.Host.Settings.EnableCacheVisualization = true;
// Prevent the screen from turning off while under the debugger by disabling
// the application's idle detection.
// Caution:- Use this under debug mode only. Application that disables user idle detection will continue to run
// and consume battery power when the user is not using the phone.
PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
}
// Initialize the Parse client with your Application ID and .NET Key found on
// your Parse dashboard
ParseClient.Initialize("grpTmrClet8K35yeXg2HQKK8wl59VeC9ijH0I0dn", "os8EfSFq9maPBtDJ91Mq0xnWme8fLANhttTPAqKu");
// After calling ParseClient.Initialize():
this.Startup += async (sender, args) =>
{
// This optional line tracks statistics around app opens, including push effectiveness:
ParseAnalytics.TrackAppOpens(RootFrame);
// By convention, the empty string is considered a "Broadcast" channel
// Note that we had to add "async" to the definition to use the await keyword
await ParsePush.SubscribeAsync("testchannel");
};
}
// Code to execute when the application is launching (eg, from Start)
// This code will not execute when the application is reactivated
private async void Application_Launching(object sender, LaunchingEventArgs e) {
await ParseAnalytics.TrackAppOpenedAsync();
}
When I send a push notification from the Parse dashboard it doesn't get received. I have tried running both on the emulator (Windows Phone 8.0) and device (8.1), with app in foreground, background and closed with the same negative result.
When I use a channel like "testchannel" above and use the segment options, the channel name appears in the dropdown list of options indicating that the app is at least connecting Parse, but it just wont receive the notifications.
Hope someone can help me identify what I am missing. Thanks in advance.
If you are developing a Windows Phone 8.1 app, make sure you've enabled toast notification in the manifest file.
I don't quite understand everything about Parse just yet, but this is what works for me.
In App.xaml.cs:
public App()
{
this.InitializeComponent();
this.Suspending += this.OnSuspending;
ParseClient.Initialize("wSjuNTbtjVLRaedXvOoaf9S5cTbkuQohTulNZ2vS", "nWZMhXRet9Wotlgikb9aUdKf5GFtRiMvduw7w68z");
}
We subscribe and enable analytics OnLaunched:
protected async override void OnLaunched(LaunchActivatedEventArgs e)
//Generated codes go here
await ParsePush.SubscribeAsync("testchannel");
await ParseAnalytics.TrackAppOpenedAsync();
That would simply do the trick. You should modify the code according to your needs. Hope this helps.

Windows phone 8 notification hub unregister

Can someone show me or tell some example how to unregister from notification hub in windows phone 8. I tried on this way but it doesn't work.
public void registerForNotifications(string[] tags)
{
var channel = HttpNotificationChannel.Find("xxx");
if (channel == null)
{
channel = new HttpNotificationChannel("xxx");
channel.Open();
channel.BindToShellToast();
}
string[] tagsToSubscribeTo = tags;
channel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(async (o, args) =>
{
var hub = new NotificationHub("xxx", "xxx");
await hub.RegisterNativeAsync(args.ChannelUri.ToString(), tagsToSubscribeTo);
});
}
public async void unregisterFromNotifications()
{
var channel = HttpNotificationChannel.Find("xxx");
var hub = new NotificationHub("xxx", "xxx");
await hub.UnregisterAllAsync(channel.ChannelUri.ToString());
}
You didn't say what "it didn't work" means. Did you get an error message? Did it report success but actually fail? In your questions, it really helps more if you share those things. But I'll take a stab at this anyway.
I suspect that you might be using the DefaultListenSharedAccessSignature endpoint from your Windows Phone 8 app.
According to http://msdn.microsoft.com/en-us/library/dn495373.aspx, the Listen access level grants permission to:
Create/Update registration.
Read registration.
Read all registrations for a handle.
Delete registration.
Reading that last one, I wonder if the UnregisterAllAsync method might require a higher access level to delete all registrations, rather than just one.
But rather than use the DefaultFullSharedAccessSignature endpoint, I would rather just try the UnregisterAsync method instead of UnregisterAllAsync.
Disclaimer: I have not tried this out. It may not help at all.

Occasional (and recurrent) problems with FacebookMobile.init()

Seems this API is broken and/or abandoned because in some days, this API call always fails during a few hours. Today is happening again, but it's taking more time than previous times.
I don't know what to do. I have 2 Air apps and they aren't working today.
Any solution on this?
Here is a simple piece of code:
FacebookMobile.init(APP_ID, onInit);
private function onInit(fbSession:Object, fail:Object):void
{
if (fbSession){
trace(fbSession.accessToken);
}
else{
traceV2(fail); // it's a "deep" trace
// other API methods related to login
}
}
In FacebookMobile.init(), we have to expect for an session object (containing FB acess token), or a "fail" object.
The fail object is returning this to me:
[Object]
| [error:Object]
| code = 190
| message = Malformed access token AAAEWSUA8XjUBAJo4JuO5hUMwSnKC95LNRr1nHHIU8rwPGzxvHIuhUcDziZA9ZC3xDf4ZBwYcqjVU1ir5wf5jlEsJ5zwyMhnnWGyWxXeKQZDZD,AAAEWSUA8XjUBAJo4JuO5hUMwSnKC95LNRr1nHHIU8rwPGzxvHIuhUcDziZA9ZC3xDf4ZBwYcqjVU1ir5wf5jlEsJ5zwyMhnnWGyWxXeKQZDZD
| type = OAuthException
Thanks in advance!
Problem fixed.
The solution to this specific problem is at at com.facebook.graph.FacebookMobile:560, inside the handleLogin() function.
protected function handleLogin(result:Object, fail:Object):void {
loginWindow.loginCallback = null;
if (fail) {
loginCallback(null, fail);
return;
}
// ---------------||--------------------//
// ---------------\/--------------------//
// This line below solves this problem
result.access_token = String(result.access_token).split(',')[0];
// ---------------/\-------------------//
// ---------------||-------------------//
session = new FacebookSession();
session.accessToken = result.access_token;
session.expireDate = (result.expires_in == 0) ? null : FacebookDataUtils.stringToDate(result.expires_in) ;
if (_manageSession) {
var so:SharedObject = SharedObject.getLocal(SO_NAME);
so.data.accessToken = session.accessToken;
so.data.expireDate = session.expireDate;
so.flush();
}
verifyAccessToken();
}
Seems like its a bug with Facebook returning the Access token as an Array:
http://developers.facebook.com/bugs/276418065796236?browse=search_5034a345a2cb15e92344737
I would try edit the String that is returned by removing the second access token value in it. (Everything after the comma) and signing that to your local sessions access token variable. It might resolve the issue