Xamarin & Android - crash on exiting from method - android

I don't know what can I tell more.
I have this method:
public async Task<HttpResponseMessage> SendAsyncRequest(string uri, string content, HttpMethod method, bool tryReauthorizeOn401 = true)
{
HttpRequestMessage rm = new HttpRequestMessage(method, uri);
if (!string.IsNullOrWhiteSpace(content))
rm.Content = new StringContent(content, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.SendAsync(rm);
if (response.StatusCode == HttpStatusCode.Unauthorized && tryReauthorizeOn401)
{
var res = await AuthenticateUser();
if(res.user == null)
return response;
return await SendAsyncRequest(uri, content, method, false);
}
return response;
}
Nothing special.
client.SendAsync(rm) is executed, response.StatusCode is Ok.
Application just crashes when exiting from this method.
Output shows me just this assert:
12-16 20:09:22.025 F/ ( 1683): * Assertion at /Users/builder/jenkins/workspace/xamarin-android-d15-9/xamarin-android/external/mono/mono/mini/debugger-agent.c:4957, condition `is_ok (error)' not met, function:set_set_notification_for_wait_completion_flag, Could not execute the method because the containing type is not fully instantiated. assembly:<unknown assembly> type:<unknown type> member:(null)
12-16 20:09:22.025 F/libc ( 1683): Fatal signal 6 (SIGABRT), code -6 in tid 1683 (omerang.Android)
And nothing more.
client is HttpClient.
I have setting in my Android project: HttpClient Implementation set to Android.
Does anyone have any idea what could be wrong?
edit
SendAsyncRequest is used like that:
public async Task<(HttpResponseMessage response, IEnumerable<T> items)> GetListFromRequest<T>(string uri)
{
HttpResponseMessage response = await SendAsyncRequest(uri, null, HttpMethod.Get);
if (!response.IsSuccessStatusCode)
return (response, null);
string content = await response.Content.ReadAsStringAsync();
var items = JsonConvert.DeserializeObject<IEnumerable<T>>(content);
return (response, new List<T>(items));
}

Based on the provided example project code you provided
protected override async void OnStart()
{
Controller c = new Controller();
TodoItem item = await c.GetTodoItem(1);
TodoItem item2 = await c.GetTodoItem(2);
}
You are calling async void fire and forget on startup.
You wont be able to catch any thrown exceptions, which would explain why the App crashes with no warning.
Reference Async/Await - Best Practices in Asynchronous Programming
async void should only be used with event handlers, so I would suggest adding an event and handler.
based on the provided example, it could look like as follows
public partial class App : Application {
public App() {
InitializeComponent();
MainPage = new MainPage();
}
private even EventHander starting = delegate { };
private async void onStarting(object sender, EventArgs args) {
starting -= onStarting;
try {
var controller = new Controller();
TodoItem item = await controller.GetTodoItem(1);
TodoItem item2 = await controller.GetTodoItem(2);
} catch(Exception ex) {
//...handler error here
}
}
protected override void OnStart() {
starting += onStarting;
starting(this, EventArgs.Empty);
}
//...omitted for brevity
}
With that, you should now at least be able to catch the thrown exception to determine what is failing.

try to update your compileSdkVersion to a higher version and check.
also try following
> Go to: File > Invalidate Caches/Restart and select Invalidate and Restart

Related

How to display exceptions from HTTP request on Android screen

I am using a basic Flutter- based get request that is going to a RESTful server. The code for performing this request is below:
Future<List<Description>> getTheInfo() async {
List<Description> result;
try {
http.Response resp = await http.get(theUrl + "/home/devices");
if(resp.statusCode == 200) {
var jsonstr = json.decode(resp.body);
var list = jsonstr["devices"] as List;
result = list.map<Description>((json) => Description.fromJson(json)).toList();
}
else {
print('FAILURE: '+resp.statusCode.toString());
}
} catch(exe) {
print('Socket Failure: '+exe.toString());
throw CustomException("FAILURE: ",exe.toString());
}
return(result);
}
The custom exception is something I grabbed from the Internet below:
class CustomException implements Exception {
final _message;
final _prefix;
CustomException([this._message, this._prefix]);
String toString() {
return "$_prefix$_message";
}
}
My problem is that while I have the ability to print to the console any failures that occur in my development environment, I have no way of seeing what happens on a device. I am seeing failures when testing on my phone that I am not seeing in my development environment.
What I would like to do is have some way of displaying exceptions that are thrown from my GET request on the screen of my emulator (in my development environment) and the screen of my actual phone (when I create an APK to test on my device). Is there some way to do this?
Not sure by what you are trying to accomplish here, but there is an elegant way to display failures and exceptions on to the UI to let the user know about it. This would be a good practice as well in a production app.
What you need is dartz, dartz is a functional programming package.
With dartz you can use the Either type to return either a Future<List<Description>> or a CustomException
here is how it'll fit into your code.
Future<Either<CustomException,List<Description>>> getTheInfo() async {
List<Description> result;
try {
http.Response resp = await http.get(theUrl + "/home/devices");
if(resp.statusCode == 200) {
var jsonstr = json.decode(resp.body);
var list = jsonstr["devices"] as List;
result = list.map<Description>((json) => Description.fromJson(json)).toList();
return right(result);
}
else {
print('FAILURE: '+resp.statusCode.toString());
return left(CustomException("FAILURE: ",exe.toString()));
}
} catch(exe) {
print('Socket Failure: '+exe.toString());
return left(CustomException("FAILURE: ",exe.toString()));
}
}
On the UI side,
...
Widget build(BuildContext context) {
FutureBuilder(
future: getTheInfo(),
builder: (_, AysncSnapshot snapshot) {
if(snapshot.connectionState ==ConnectionStatet.waiting){
return CircularProgressIndicator();
}
snapshot.data.fold(
(l)=> Center(child: Text(l.message), // CustomException message
),
(r)=> Center(child: Text("Success"), // r contains the List<Description>
);
}
}
...
Depending on Success or Failure, you can render an appropriate widget.
edit:
This should work but highly recommend switching to provider or riverpord if not BLoc

httpClient.PostAsync crashes app in Xamarin Android JobService

I have an Android Xamarin app that handles notifications. When a notification is displayed, there are buttons that ask for a response. The app needs to send this response back to a server via an httpClient.PostAsync call. I am using the same http client wrapper in other parts of the code and it is working correctly. However, when I call it from the JobService code, the app crashes. I have enclosed the http call in a try/catch and no exception occurs. There are also no errors in the device log. i would like to know how to debug this. Here is my flow:
I have a class that derives from FirebaseMessagingService with an OnMessageReceived method. That gets called when a notification arrives. I build a local notification via the notification manager and call .Notify. The notification appears with the buttons. I have a BroadcastReceiver with an OnReceive method. That method schedules a job to do the post back of the button click. The job gets started and runs until the point I call the PostAsync. From there it crashes with no exception. Here is the relevant part of the JobWorker:
public override bool OnStartJob(JobParameters jobParams)
{
_backgroundWorker = Task.Run(() => { DoWork(jobParams); });
return true;
}
private void DoWork(JobParameters jobParams)
{
var logger = App.ResolveDependency<ILogger>() as ILogger;
var callActions = App.ResolveDependency<ICallActionsHandler>() as ICallActionsHandler;
var callToken = jobParams.Extras.GetString(JobParameterCallToken);
var subsciberPhoneNumber = jobParams.Extras.GetString(JobParameterSubscriberPhoneNumber);
var action = jobParams.Extras.GetString(JobParametersCallAction);
logger.TraceInfo($"starting {nameof(CallActionService)}: starting job {jobParams.JobId}");
callActions.SendAction(
callToken,
subsciberPhoneNumber,
(CallActions)Enum.Parse(typeof(CallActions), action));
}
The SendAction code calls the http client wrapper. The http client wrapper code looks like this:
public async Task<int> PostAsync(string api, object message)
{
var apiUrl = Constants.DefaultAppApi + api;
var contentText = JsonConvert.SerializeObject(message);
var content = new StringContent(contentText, Encoding.UTF8, "application/json");
var backOff = 10;
var retryCount = 5;
HttpResponseMessage response = null;
for (var attempt = 1; attempt <= retryCount; attempt++)
{
_logger.TraceInfo($"DataServerClient Post message: {message.GetType().Name}, attempt = {attempt}");
try
{
response = await _client.PostAsync(apiUrl, content);
}
catch (Exception ex)
{
if (attempt == retryCount)
_logger.TraceException($"DataServerClient Post failed", ex);
}
if (response != null && response.IsSuccessStatusCode)
{
_logger.TraceInfo($"DataServerClient post was successful at retry count: {attempt}");
break;
}
backOff *= 2;
await Task.Delay(backOff);
}
return (int)response.StatusCode;
}
Can anyone provide clues for why this is failing or how I can gather diagnostics to find out what is happening? As I mentioned, the exception is not caught, the task that I create gets marked as completed, and no message gets posted.

System.Net.Http.HttpClient with AutomaticDecompression and GetAsync (timeout) vs GetStringAsync (working

I have the following code to make requests to a REST API, using Xamarin and an Android device:
public class ApiBase
{
HttpClient m_HttpClient;
public ApiBase(string baseAddress, string username, string password)
{
if (!baseAddress.EndsWith("/"))
{
baseAddress += "/";
}
var handler = new HttpClientHandler();
if (handler.SupportsAutomaticDecompression)
{
handler.AutomaticDecompression = DecompressionMethods.GZip;
}
m_HttpClient = new HttpClient(handler);
m_HttpClient.BaseAddress = new Uri(baseAddress);
var credentialsString = Convert.ToBase64String(Encoding.UTF8.GetBytes(username + ":" + password));
m_HttpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", credentialsString);
m_HttpClient.Timeout = new TimeSpan(0, 0, 30);
}
protected async Task<XElement> HttpGetAsync(string method)
{
try
{
HttpResponseMessage response = await m_HttpClient.GetAsync(method);
if (response.IsSuccessStatusCode)
{
// the request was successful, parse the returned string as xml and return the XElement
var xml = await response.Content.ReadAsAsync<XElement>();
return xml;
}
// the request was not successful -> return null
else
{
return null;
}
}
// some exception occured -> return null
catch (Exception)
{
return null;
}
}
}
If i have it like this, the first and the second call to HttpGetAsync work perfectly, but from the 3rd on the GetAsyncstalls and eventually throws an exception due to the timeout. I send these calls consecutively, there are not 2 of them running simultaneously since the results of the previous call are needed to decide the next call.
I tried using the app Packet Capture to look at the requests and responses to find out if i'm sending an incorrect request. But it looks like the request which fails in the end is never even sent.
Through experimentation i found out that everything works fine if don't set the AutomaticDecompression.
It also works fine if i change the HttpGetAsync method to this:
protected async Task<XElement> HttpGetAsync(string method)
{
try
{
// send the request
var response = await m_HttpClient.GetStringAsync(method);
if (string.IsNullOrEmpty(response))
{
return null;
}
var xml = XElement.Parse(response);
return xml;
}
// some exception occured -> return null
catch (Exception)
{
return null;
}
}
So basically using i'm m_HttpClient.GetStringAsync instead of m_HttpClient.GetAsync and then change the fluff around it to work with the different return type. If i do it like this, everything works without any problems.
Does anyone have an idea why GetAsync doesn't work properly (doesn't seem to send the 3rd request) with AutomaticDecompression, where as GetStringAsync works flawlessly?
There are bug reports about this exact issue:
https://bugzilla.xamarin.com/show_bug.cgi?id=21477
The bug is marked as RESOLVED FIXED and the recomended action is to update to the latest stable build. But there are other (newer) bugreports that indicate the same thing that are still open, ex:
https://bugzilla.xamarin.com/show_bug.cgi?id=34747
I made a workaround by implementing my own HttpHandler like so:
public class DecompressionHttpClientHandler : HttpClientHandler
{
protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
request.Headers.AcceptEncoding.Add(new System.Net.Http.Headers.StringWithQualityHeaderValue("gzip"));
var msg = await base.SendAsync(request, cancellationToken);
if (msg.Content.Headers.ContentEncoding.Contains("gzip"))
{
var compressedStream = await msg.Content.ReadAsStreamAsync();
var uncompresedStream = new System.IO.Compression.GZipStream(compressedStream, System.IO.Compression.CompressionMode.Decompress);
msg.Content = new StreamContent(uncompresedStream);
}
return msg;
}
}
Note that the code above is just an example and not a final solution. For example the request will not be compressed and all headers will be striped from the result. But you get the idea.

Error using MvxMultiPartFormRestRequest to post image/data to API controller

I am building an Android app which has a form that user can post image for an item.
So the post data is an int field and an image.
I use MvvmCross Network plugin to post and got below error. I am a beginner and I do not know where I did wrong: mobile app code or API controller code?
error = {System.Net.WebException: The remote server returned an error: (500) Internal Server Error.
at System.Net.HttpWebRequest.CheckFinalStatus (System.Net.WebAsyncResult result) [0x00000] in <filename unknown>:0
at System.Net.HttpWebRequest.SetResponseData ...
This is mobile app code:
This is select image code:
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
if ((requestCode == PickImageId) && (resultCode == Result.Ok) && (data != null))
{
_imgUri = data.Data;
_imgPath = GetPathToImage(_imgUri);
_contentType = ContentResolver.GetType(_imgUri);
}
}
Then click Submit button
private void btnSubmit_Click(object sender, EventArgs e)
{
MemoryStream stream = new MemoryStream();
ContentResolver.OpenInputStream(_imgUri).CopyTo(stream);
_vm.Submit(_imgPath, _contentType, stream);
}
This is Submit function:
public void Submit(string fileName, string contentType, MemoryStream stream) {
//Post data
int itemId = 1;
List<MvxMultiPartFormRestRequest.IStreamForUpload> streams = new List<MvxMultiPartFormRestRequest.IStreamForUpload>();
streams.Add(new MvxMultiPartFormRestRequest.MemoryStreamForUpload("userFile", fileName, contentType, stream));
var client = Mvx.Resolve<IMvxJsonRestClient>();
var r = new MvxMultiPartFormRestRequest("https://.../api/ItemUserImage");
r.FieldsToSend.Add("itemId", itemId.ToString());
r.StreamsToSend.AddRange(streams);
client.MakeRequestFor<MyResponse>(r, (result) =>
{
Mvx.Resolve<IUserInteraction>().Alert(result.Result.ResponseText, null, TitleInformation);
}, (error) =>
{
//I met error here
});
This is my API controller:
public class ItemUserImageController : ApiController
{
public async Task<HttpResponseMessage> PostFormData()
{
Response response = new Response();
response.ResponseCode = 1;
response.ResponseText = "step0-";
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
response.ResponseText += "step1-";
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
response.ResponseText += "step2-";
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
response.ResponseText += "step3-";
try
{
// Read the form data.
await Request.Content.ReadAsMultipartAsync(provider);
response.ResponseText += "step4-";
foreach (var key in provider.FormData.AllKeys)
{
foreach (var val in provider.FormData.GetValues(key))
{
response.ResponseText += string.Format("{0}: {1}-", key, val);
}
}
response.ResponseText += "step5-";
// This illustrates how to get the file names.
foreach (MultipartFileData file in provider.FileData)
{
response.ResponseText += string.Format("{0} - Server file path: {1}-", file.Headers.ContentDisposition.FileName, file.LocalFileName);
}
return Request.CreateResponse(HttpStatusCode.OK, response);
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, response.ResponseText ,e);
}
}
}
Please help. Thank you.
This "bug" could be lots of things. Really the best way to resolve it is to get in there with some debugging tools, to set breakpoints in both the client and the ASP.Net app and to see what the communication is.
To set breakpoints in the client app, use Visual or Xamarin Studio.
To see the raw HTTP traffic between the client app and the server, use Fiddler - see https://stackoverflow.com/a/25412339/373321 (this assumes you have a 4.4 or later Android device)
To set breakpoints in the server app, use Visual Studio and try exposing the website from your development box beyond localhost using IISExpress settings - see http://johan.driessen.se/posts/Accessing-an-IIS-Express-site-from-a-remote-computer
Once you start debugging this, I'm sure you'll quickly
Beyond that, the only "spider sense tingle" I got looking through your client code was a slight concern that you might need to reset the current position in your MemoryStream back to the start (but I haven't thought this fully through).

unusual callback calling

I have such a problem: on device with Android OS, I am executing action script code. And I have a method, which must to send some data to sever. But!!! Even if I stop my application before sending some data to server - it still somehow sends that data. I don't understand how it can be?? Anyone faced with this problem? Please help me. Thanks.
public class VerifyCommand extends SimpleCommand
{
override public function execute(notification:INotification):void
{
//here is the place, where I put breakpoint and stop the program
trace("here is the place, where I put breakpoint and stop the program");
verify();
}
private function verify():void
{
var tempError:Error = new Error();
var stackTrace:String = tempError.getStackTrace();
trace(stackTrace);
var request : URLRequest = new URLRequest();
request.url = "http://www.somesite.com";
request.method = URLRequestMethod.POST;
request.contentType = "application/x-www-form-urlencoded; charset=utf-8";
request.data = variables;
request.useCache = false;
request.cacheResponse = false;
var call_loader:URLLoader = new URLLoader();
call_loader.dataFormat = URLLoaderDataFormat.TEXT;
call_loader.addEventListener(Event.COMPLETE, onVerificationResult);
call_loader.addEventListener(IOErrorEvent.IO_ERROR, onVerificationError);
call_loader.load(request);
}
private function onVerificationResult(event:Event):void
{
trace("all ok");
}
private function onVerificationError( event:Event):void
{
trace("all failed");
}
}
It was a debugger fault , it doesn't stop exactly where I think it should.

Categories

Resources