Async method crashes with an exception on Windows Phone 8.1 - c#

I am using the Map functionality of Windows Phone 8.1 to find a route with the following code:
MapRouteFinderResult routeResult = null;
try
{
if (true == typeOfTransport.Equals(GlobalDeclarations.TypeOfTransport.Walk))
{
routeResult = await MapRouteFinder.GetWalkingRouteAsync(startPoint, endPoint);
}
else
{
routeResult = await MapRouteFinder.GetDrivingRouteAsync(startPoint, endPoint, MapRouteOptimization.Time, MapRouteRestrictions.None, 290);
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
The problem is that despite the try-catch, this MapRouteFinder.GetWalkingRouteAsync method crashes with an exception: Object not set to an instance of an object. Both startPoint and endPoint params are obviously not null, and filled with data. Why is this? And why the whole app crashes instead of catching the exception in the try-catch section?

Related

HttpRequestException is not caught in catch block, xamarin.android , while same code works in UnitTest application

I have a xamarin android project in which I'm calling API from PCL project, so when I call that API without internet connection, it throws HTTPRequestException, so I wrapped the code in try/catch block but the exception is still not caught..
I've run that code in UnitTest application and it works as expected, so I assume the problem is within xamarin.android and its multi-threading, so I wonder if there's any workaround
public override async void OnActivityCreated(Bundle savedInstanceState)
{
base.OnActivityCreated(savedInstanceState);
try
{
progressBar.IsBusy = true;
progressBar.Visibility = ViewStates.Visible;
progressBar.Title = "Loading...";
var items = await ApiClient.Instance.GetAllAsync(); //this is supposed to throw httprequestexception when there is no internet connection.
layoutManager = new GridLayoutManager(Activity, 3, GridLayoutManager.Vertical, false);
onScrollListener = new CoinRecyclerViewScrollListener(layoutManager);
recyclerView.AddOnScrollListener(onScrollListener);
onScrollListener.LoadMoreEvent += OnScrollListener_LoadMoreEvent;
SetAdapterWithAnim(recyclerView);
progressBar.Visibility = ViewStates.Gone;
}
catch (HttpRequestException) //the exception is not caught
{
//some handling
}
}
The problem was caused by the second fragment which was implemented into viewpager, I've forgot to wrap try/catch around it.

AVAudioEngine Xamarin.iOS not catched exception engine required running

I'm using Xamarin.iOS for an application using AVAudioEngine.
Sometimes I get this exception :
AVFoundation_AVAudioPlayerNode_Play
Terminating app due to uncaught exception 'com.apple.coreaudio.avfaudio', reason: 'required condition is false: _engine->IsRunning()'
This point to my code:
private Dictionary<AudioTrack, AVAudioPlayerNode> _dicPlayerNodes;
private void PlayAudio()
{
try
{
NSError err;
if (Engine.StartAndReturnError(out err))
{
foreach (var audioTrack in _dicPlayerNodes)
{
AVAudioPlayerNode node = audioTrack.Value;
node.Play();
}
}
else
{
Messenger.Publish(new AudioErrorMessage(this) { Platform = "IOS", Code = Convert.ToInt32(err.Code), Message = err.LocalizedDescription ?? err.Description });
_exceptionHandlerService.PostHockeyApp(new Exception($"{err.Code} {err.Description}"));
}
}
catch (Exception ex)
{
_exceptionHandlerService.PostExceptionAsync(ex).Forget();
}
}
I don't understand how is it possible to have this exception that engine is not running, because in my code I Start it and get error if it failed to start ... Then play it.
Also I have a try catch that's not working in this case :( so my applicaton just crashed.
Any advices or idea ?
I comes to this thread but it doesn't help me to understand:
https://forums.developer.apple.com/thread/27980
versions:
IOS version : 10.3.3
Device: ipad 2
Xamarin.ios: 11.2.0.11
Thanks

TLSharp Data center (dc) Exception

I am using TLSharp library for implementing a custom Telegram client. when I run the code below:
public async Task<string> SendCodeRequest(string phoneNumber)
{
var completed = false;
TL.AuthSendCodeRequest request = null;
while (!completed)
{
request = new TL.AuthSendCodeRequest(phoneNumber, 5, _apiId, _apiHash, "en");
await _sender.Send(request);
await _sender.Receive(request);
completed = true;
}
// TODO handle other types (such as SMS)
if (request.Result is TL.AuthSentCodeType)
{
var result = (TL.AuthSentCodeType)request.Result;
return result.PhoneCodeHash;
}
else
{
var result = (TL.AuthSentAppCodeType)request.Result;
return result.PhoneCodeHash;
}
}
I gives me the following exception :
Your phone number registered to {dcIdx} dc. Please update settings.
See https://github.com/sochix/TLSharp#i-get-an-error-migrate_x for
details.
The mentioned github page says that TLSharp Handles these exceptions by itself. So I guess something is wrong with the library core because the code should resolve data center IPs by itself not generating an exception.
Any help would be appreciated.
TlSharp Currently doesn't handle this exception you have to catch the exception and get the data center number then Try to reconnect to the Data Center using the ReconnectToDc() Function.
In the MtProtoSender.cs file you can find the following line of code that generates the exception:
throw new InvalidOperationException($"Your phone number registered to {dcIdx} dc. Please update settings. See https://github.com/sochix/TLSharp#i-get-an-error-migrate_x for details.");
Replace it with the following code so that the Exception that is generated has the required Data Center number for connecting to it.
InvalidOperationException exception = new InvalidOperationException($"Your phone number registered to {dcIdx} dc. Please update settings. See https://github.com/sochix/TLSharp#i-get-an-error-migrate_x for details.");
exception.Data.Add("dcId", dcIdx);
throw exception;
Change your code like this:
while (!completed)
{
request = new TL.AuthSendCodeRequest(phoneNumber, 5, _apiId, _apiHash, "en");
try
{
await _sender.Send(request);
await _sender.Receive(request);
completed = true;
}
catch (InvalidOperationException ex)
{
if (ex.Message.StartsWith("Your phone number registered to") && ex.Data["dcId"] != null)
{
await ReconnectToDc((int)ex.Data["dcId"]);
}
else
{
throw;
}
}
}
In the Code above the Data Center number that was attached to the Exception is used for reconnecting to the Data center.
Probably your phone number is not in the format accepted by Telegram.
Phone number must start with plus sign, use country code and phone number without gap, for example: +989333333333

Issue with facebook Login Win10 app

I have added the Facebook.dll and the Facebook.Client.dll, this code works fine on the Windows Phone and Windows 8.1 app however its not working on the Windows 10 application coded in XAML and C#. Is anyone having this issue also?
public async Task<string> LogIntoFacebook()
{
//var session = new Session();
Session FacebookSessionClient = new Session(Constants.FacebookAppId);
try
{
FacebookSessionClient.LoginWithBehavior(_FacebookPermissions, FacebookLoginBehavior.LoginBehaviorAppwithMobileInternetFallback);
await Session.CheckAndExtendTokenIfNeeded();
}
catch (FacebookOAuthException exception)
{
SimpleIoc.Default.GetInstance<IErrorService>().ReportErrorInternalOnly(exception);
return null;
}
catch (InvalidOperationException ex)
{
SimpleIoc.Default.GetInstance<IErrorService>().ReportErrorInternalOnly(ex);
return null;
}
catch (Exception ex)
{
SimpleIoc.Default.GetInstance<IErrorService>().ReportErrorInternalOnly(ex);
return null;
}
return null;
}
This part "await Session.CheckAndExtendTokenIfNeeded();" should be where the login happens but nothing happens.
Here is a link: http://blogs.windows.com/buildingapps/2015/07/14/windows-sdk-for-facebook/
You can find a new Windows SDK for Facebook, it has login it
PS: you can alos look here: https://azure.microsoft.com/en-us/documentation/articles/mobile-services-how-to-register-facebook-authentication/

Connect to server with connect async

Is there any possible that I can ensure that the application does not fall if app can not connect to the server using await socket.ConnectAsync(server) I get this exc:
But the biggest problem is I get this exception only occasionally and randomly. Try and catch completely unresponsive and applications fall. So I need something if I cannot connect firts time dont go to exception but try it again.
My code:
public async Task _connect(string token, string idInstalation, string lang)
{
try
{
if (token != null)
{
socket.SetRequestHeader("Token", token);
socket.SetRequestHeader("Lang", lang);
socket.SetRequestHeader("idInstallation", idInstalation);
}
await socket.ConnectAsync(server);
System.Diagnostics.Debug.WriteLine("Connected");
writer = new DataWriter(socket.OutputStream);
messageNumber = 1;
}
catch (Exception)
{
var dialog = new MessageDialog("Cannot connect to UNIAPPS server", "Error").ShowAsync();
}
}

Categories