How to post multipartformdata in xamarin ios? - c#

I'm developing mobile app for IOS using Xamarin IOS and when I try to post image to server using xamarin PostAsync() method, unfortunately it raises an exception.
public async Task<string> PostCreatePlatform(Platform new_platform, Byte[] image)
{
new_platform.id = null;
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", String.Format("Token {0}", TokenInit.Token));
var response = await client.PostAsync(b + "platforms/", new StringContent(JsonConvert.SerializeObject(new_platform, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }).ToString(),Encoding.UTF8, "application/json"));
if (response.IsSuccessStatusCode)
{
if (image != null)
{
var TempPlatform = await response.Content.ReadAsStringAsync();
var final = JsonConvert.DeserializeObject<Platform>(TempPlatform);
MultipartFormDataContent form = new MultipartFormDataContent();
new_platform.id = final.id.Value;
form.Add(new ByteArrayContent(image, 0, image.Count()), "file");
var response2 = await client.PostAsync(String.Format(b + "platform/{0}/attachments/upload/", new_platform.id.Value), form);
if (response2.IsSuccessStatusCode)
{
return "success";
}
else
{
return "failed";
}
}
return "success";
}
else
{
return "failed";
}
}
InnerException: System.ObjectDisposedException
System.AggregateException: One or more errors occurred. —-> System.AggregateException: One or more errors occurred. —-> System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'System.Net.Sockets.NetworkStream'.
at System.Net.WebConnectionStream.EndWrite (System.IAsyncResult r) [0x000b2] in /Library/Frameworks/Xamarin.iOS.framework/Versions/10.10.0.33/src/mono/mcs/class/System/System.Net/WebConnectionStream.cs:616
at System.IO.Stream+<>c.<BeginEndWriteAsync>b__53_1 (System.IO.Stream stream, System.IAsyncResult asyncResult) [0x00000] in /Library/Frameworks/Xamarin.iOS.framework/Versions/10.10.0.33/src/mono/mcs/class/referencesource/mscorlib/system/io/stream.cs:729
at at (wrapper delegate-invoke) System.Func`3[System.IO.Stream,System.IAsyncResult,System.Threading.Tasks.VoidTaskResult]:invoke_TResult_T1_T2 (System.IO.Stream,System.IAsyncResult)
at System.Threading.Tasks.TaskFactory`1+FromAsyncTrimPromise`1[TResult,TInstance].Complete (TInstance thisRef, System.Func`3[T1,T2,TResult] endMethod, System.IAsyncResult asyncResult, System.Boolean requiresSynchronization) [0x00000] in /Library/Frameworks/Xamarin.iOS.framework/Versions/10.10.0.33/src/mono/mcs/class/referencesource/mscorlib/system/threading/Tasks/FutureFactory.cs:1441
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Library/Frameworks/Xamarin.iOS.framework/Versions/10.10.0.33/src/mono/mcs/class/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:151
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x00037] in /Library/Frameworks/Xamarin.iOS.framework/Versions/10.10.0.33/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:187
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in /Library/Frameworks/Xamarin.iOS.framework/Versions/10.10.0.33/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:156
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in /Library/Frameworks/Xamarin.iOS.framework/Versions/10.10.0.33/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:128
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable+ConfiguredTaskAwaiter.GetResult () [0x00000] in /Library/Frameworks/Xamarin.iOS.framework/Versions/10.10.0.33/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:447
at System.Net.Http.MultipartContent+<SerializeToStreamAsync>d__8.MoveNext () [0x00265] in <eadf07f9d3724ef0a06ee9064ef34579>:0
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Library/Frameworks/Xamarin.iOS.framework/Versions/10.10.0.33/src/mono/mcs/class/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:151
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x00037] in /Library/Frameworks/Xamarin.iOS.framework/Versions/10.10.0.33/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:187
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in /Library/Frameworks/Xamarin.iOS.framework/Versions/10.10.0.33/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:156
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in /Library/Frameworks/Xamarin.iOS.framework/Versions/10.10.0.33/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:128
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable+ConfiguredTaskAwaiter.GetResult () [0x00000] in
/Library/Frameworks/Xamarin.iOS.framework/Versions/10.10.0.33/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:447
at System.Net.Http.HttpClientHandler+<SendAsync>d__63.MoveNext () [0x0031d] in <eadf07f9d3724ef0a06ee9064ef34579>:0
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Library/Frameworks/Xamarin.iOS.framework/Versions/10.10.0.33/src/mono/mcs/class/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:151
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x00037] in /Library/Frameworks/Xamarin.iOS.framework/Versions/10.10.0.33/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:187
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in /Library/Frameworks/Xamarin.iOS.framework/Versions/10.10.0.33/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:156
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in /Library/Frameworks/Xamarin.iOS.framework/Versions/10.10.0.33/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:128
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1+ConfiguredTaskAwaiter[TResult].GetResult () [0x00000] in /Library/Frameworks/Xamarin.iOS.framework/Versions/10.10.0.33/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:535
at System.Net.Http.HttpClient+<SendAsyncWorker>d__48.MoveNext () [0x000ca] in <eadf07f9d3724ef0a06ee9064ef34579>:0
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Library/Frameworks/Xamarin.iOS.framework/Versions/10.10.0.33/src/mono/mcs/class/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:151
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x00037] in /Library/Frameworks/Xamarin.iOS.framework/Versions/10.10.0.33/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:187
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in /Library/Frameworks/Xamarin.iOS.framework/Versions/10.10.0.33/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:156
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in /Library/Frameworks/Xamarin.iOS.framework/Versions/10.10.0.33/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:128
at System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult () [0x00000] in /Library/Frameworks/Xamarin.iOS.framework/Versions/10.10.0.33/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:357
at FirstApp.ApiInteracting+<PostCreatePlatform>d__7.MoveNext () [0x003e2] in /Users/team1/Downloads/testiOSbayards2-6d24bc43fee6abd445ebcaea12b76c61649468a6/FirstApp/API/ApiInteracting.cs:176
—- End of inner exception stack trace —-
at System.Threading.Tasks.Task.ThrowIfExceptional (System.Boolean includeTaskCanceledExceptions) [0x00011] in /Library/Frameworks/Xamarin.iOS.framework/Versions/10.10.0.33/src/mono/mcs/class/referencesource/mscorlib/system/threading/Tasks/Task.cs:2157
at System.Threading.Tasks.Task`1[TResult].GetResultCore (System.Boolean waitCompletionNotification) [0x0002b] in /Library/Frameworks/Xamarin.iOS.framework/Versions/10.10.0.33/src/mono/mcs/class/referencesource/mscorlib/system/threading/Tasks/Future.cs:562
at System.Threading.Tasks.Task`1[TResult].get_Result () [0x00000] in
/Library/Frameworks/Xamarin.iOS.framework/Versions/10.10.0.33/src/mono/mcs/class/referencesource/mscorlib/system/threading/Tasks/Future.cs:532
at FirstApp.AddPlatformTableViewController+<>c__DisplayClass247_0.<CreatePlatformButtonUpInside>b__0 () [0x00000] in /Users/team1/Downloads/testiOSbayards2-6d24bc43fee6abd445ebcaea12b76c61649468a6/FirstApp/UIClasses/AddPlatformTableViewController.cs:115
at System.Threading.Tasks.Task`1[TResult].InnerInvoke () [0x0000f] in /Library/Frameworks/Xamarin.iOS.framework/Versions/10.10.0.33/src/mono/mcs/class/referencesource/mscorlib/system/threading/Tasks/Future.cs:680
at System.Threading.Tasks.Task.Execute () [0x00010] in /Library/Frameworks/Xamarin.iOS.framework/Versions/10.10.0.33/src/mono/mcs/class/referencesource/mscorlib/system/threading/Tasks/Task.cs:2502
—- End of inner exception stack trace —-
at System.Threading.Tasks.Task.ThrowIfExceptional (System.Boolean includeTaskCanceledExceptions) [0x00011] in /Library/Frameworks/Xamarin.iOS.framework/Versions/10.10.0.33/src/mono/mcs/class/referencesource/mscorlib/system/threading/Tasks/Task.cs:2157
at System.Threading.Tasks.Task`1[TResult].GetResultCore (System.Boolean waitCompletionNotification) [0x0002b] in /Library/Frameworks/Xamarin.iOS.framework/Versions/10.10.0.33/src/mono/mcs/class/referencesource/mscorlib/system/threading/Tasks/Future.cs:562
at System.Threading.Tasks.Task`1[TResult].get_Result () [0x00000] in /Library/Frameworks/Xamarin.iOS.framework/Versions/10.10.0.33/src/mono/mcs/class/referencesource/mscorlib/system/threading/Tasks/Future.cs:532
at FirstApp.AddPlatformTableViewController+<>c__DisplayClass247_1.<CreatePlatformButtonUpInside>b__2 () [0x00001] in /Users/team1/Downloads/testiOSbayards2-6d24bc43fee6abd445ebcaea12b76c61649468a6/FirstApp/UIClasses/AddPlatformTableViewController.cs:119
at Foundation.NSActionDispatcher.Apply () [0x00000] in /Users/builder/data/lanes/4691/3e5ac5ff/source/xamarin-macios/src/Foundation/NSAction.cs:57
at at (wrapper managed-to-native) UIKit.UIApplication:UIApplicationMain (int,string[],intptr,intptr)
at UIKit.UIApplication.Main (System.String[] args, System.IntPtr principal, System.IntPtr delegate) [0x00005] in /Users/builder/data/lanes/4691/3e5ac5ff/source/xamarin-macios/src/UIKit/UIApplication.cs:79
at UIKit.UIApplication.Main (System.String[] args, System.String principalClassName, System.String delegateClassName) [0x00038] in /Users/builder/data/lanes/4691/3e5ac5ff/source/xamarin-macios/src/UIKit/UIApplication.cs:63
at FirstApp.Application.Main (System.String[] args) [0x00001] in /Users/team1/Downloads/testiOSbayards2-6d24bc43fee6abd445ebcaea12b76c61649468a6/FirstApp/Main.cs:12
Moreover, I reproduced this method using .NET C# compiler(not Mono) and manually with web debugging tool(Fiddler) and everything is ok.
Update:
The problem was resolved. Size of image was too big - 18mb.

Try following code. it works for me. Hope it helps.
public class PostImageData
{
public int success { get; private set; }
public async Task postData(string username, string password,string documentid, StreamContent streamContent)
{
UploadPhoto details = new UploadPhoto();
try
{
System.Diagnostics.Debug.WriteLine("uplod done");
var clinet = new HttpClient();
var content = new MultipartFormDataContent();
content.Add(streamContent, "file", "test.jpeg");
System.Net.Http.HttpResponseMessage r =await clinet.PostAsync(YOUR_URL, content);
string json =await r.Content.ReadAsStringAsync();
details = JsonConvert.DeserializeObject<UploadPhoto>(json);
if (details.message == "Upload success")
{
success = 200;
}
success = 200;
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
success = 400;
}
}
public class UploadPhoto
{
public string message { get; set; }
}
}

Related

xamarin forms HttpClient call in a loop

i am new to Xamairin form development, i have list of items value and i want to fetch subitems collections in order to items id , so i looped items and inside the loop just call HttpClient get request to fetch subitems and doing some add to another list to display listview with header template, the issue is when i call httpclient inside loop 1st time it fetch the data and the next time it has thorwn System.Net.Http.HttpRequestException: An error occurred while sending the request
can you any one help me, how od i overcome this
11-06 16:44:32.517 I/MonoDroid(13270): UNHANDLED EXCEPTION:
11-06 16:44:32.522 I/MonoDroid(13270): System.Net.Http.HttpRequestException: An error occurred while sending the request ---> System.Net.WebException: Error: NameResolutionFailure
11-06 16:44:32.522 I/MonoDroid(13270): at System.Net.HttpWebRequest.EndGetResponse (System.IAsyncResult asyncResult) [0x00058] in <5a97d41d36694fb19855c17429527b10>:0
11-06 16:44:32.522 I/MonoDroid(13270): at System.Threading.Tasks.TaskFactory1[TResult].FromAsyncCoreLogic (System.IAsyncResult iar, System.Func2[T,TResult] endFunction, System.Action1[T] endAction, System.Threading.Tasks.Task1[TResult] promise, System.Boolean requiresSynchronization) [0x0000f] in :0
11-06 16:44:32.522 I/MonoDroid(13270): --- End of stack trace from previous location where exception was thrown ---
11-06 16:44:32.522 I/MonoDroid(13270): at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in :0
11-06 16:44:32.522 I/MonoDroid(13270): at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in :0
11-06 16:44:32.522 I/MonoDroid(13270): at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in :0
11-06 16:44:32.522 I/MonoDroid(13270): at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in :0
11-06 16:44:32.522 I/MonoDroid(13270): at System.Runtime.CompilerServices.ConfiguredTaskAwaitable1+ConfiguredTaskAwaiter[TResult].GetResult () [0x00000] in <f32579baafc1404fa37ba3ec1abdc0bd>:0
11-06 16:44:32.522 I/MonoDroid(13270): at System.Net.Http.HttpClientHandler+<SendAsync>d__64.MoveNext () [0x0041d] in <996a681f30a44cd685a4da54e11956e2>:0
11-06 16:44:32.522 I/MonoDroid(13270): --- End of inner exception stack trace ---
11-06 16:44:32.522 I/MonoDroid(13270): at System.Net.Http.HttpClientHandler+<SendAsync>d__64.MoveNext () [0x00478] in <996a681f30a44cd685a4da54e11956e2>:0
11-06 16:44:32.522 I/MonoDroid(13270): --- End of stack trace from previous location where exception was thrown ---
11-06 16:44:32.522 I/MonoDroid(13270): at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <f32579baafc1404fa37ba3ec1abdc0bd>:0
11-06 16:44:32.522 I/MonoDroid(13270): at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in <f32579baafc1404fa37ba3ec1abdc0bd>:0
11-06 16:44:32.522 I/MonoDroid(13270): at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <f32579baafc1404fa37ba3ec1abdc0bd>:0
11-06 16:44:32.522 I/MonoDroid(13270): at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <f32579baafc1404fa37ba3ec1abdc0bd>:0
11-06 16:44:32.522 I/MonoDroid(13270): at System.Runtime.CompilerServices.ConfiguredTaskAwaitable1+ConfiguredTaskAwaiter[TResult].GetResult () [0x00000] in :0
11-06 16:44:32.522 I/MonoDroid(13270): at System.Net.Http.HttpClient+d__49.MoveNext () [0x000ca] in <996a681f30a44cd685a4da54e11956e2>:0
11-06 16:44:32.522 I/MonoDroid(13270): --- End of stack trace from previous location where exception was thrown ---
11-06 16:44:32.522 I/MonoDroid(13270): at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in :0
11-06 16:44:32.522 I/MonoDroid(13270): at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in :0
11-06 16:44:32.522 I/MonoDroid(13270): at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in :0
11-06 16:44:32.523 I/MonoDroid(13270): at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in :0
11-06 16:44:32.523 I/MonoDroid(13270): at System.Runtime.CompilerServices.ConfiguredTaskAwaitable1+ConfiguredTaskAwaiter[TResult].GetResult () [0x00000] in <f32579baafc1404fa37ba3ec1abdc0bd>:0
11-06 16:44:32.523 I/MonoDroid(13270): at Expertential.Services.ActivityTaskListViewModelService+<GetActivityList>d__9.MoveNext () [0x0012b] in E:\RNSTFS\Expertential Mobile\Expertential.Mobile\Expertential\Expertential\Services\ActivityTaskListViewModelService.cs:66
11-06 16:44:32.523 I/MonoDroid(13270): --- End of stack trace from previous location where exception was thrown ---
11-06 16:44:32.523 I/MonoDroid(13270): at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <f32579baafc1404fa37ba3ec1abdc0bd>:0
11-06 16:44:32.523 I/MonoDroid(13270): at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in <f32579baafc1404fa37ba3ec1abdc0bd>:0
11-06 16:44:32.523 I/MonoDroid(13270): at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <f32579baafc1404fa37ba3ec1abdc0bd>:0
11-06 16:44:32.523 I/MonoDroid(13270): at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <f32579baafc1404fa37ba3ec1abdc0bd>:0
11-06 16:44:32.523 I/MonoDroid(13270): at System.Runtime.CompilerServices.TaskAwaiter1[TResult].GetResult () [0x00000] in :0
11-06 16:44:32.523 I/MonoDroid(13270): at Expertential.ViewModels.DashBoardViewModel+d__74.MoveNext () [0x000df] in E:\RNSTFS\Expertential Mobile\Expertential.Mobile\Expertential\Expertential\ViewModels\DashBoardViewModel.cs:325
11-06 16:44:32.523 I/MonoDroid(13270): --- End of stack trace from previous location where exception was thrown ---
11-06 16:44:32.523 I/MonoDroid(13270): at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in :0
11-06 16:44:32.523 I/MonoDroid(13270): at System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.b__6_0 (System.Object state) [0x00000] in :0
11-06 16:44:32.523 I/MonoDroid(13270): at Android.App.SyncContext+<>c__DisplayClass2_0.b__0 () [0x00000] in <263adecfa58f4c449f1ff56156d886fd>:0
11-06 16:44:32.523 I/MonoDroid(13270): at Java.Lang.Thread+RunnableImplementor.Run () [0x00008] in <263adecfa58f4c449f1ff56156d886fd>:0
11-06 16:44:32.523 I/MonoDroid(13270): at Java.Lang.IRunnableInvoker.n_Run (System.IntPtr jnienv, System.IntPtr native__this) [0x00008] in <263adecfa58f4c449f1ff56156d886fd>:0
11-06 16:44:32.523 I/MonoDroid(13270): at (wrapper dynamic-method) System.Object.91b49edf-9891-4d0a-b0ee-998e603a63ec(intptr,intptr)
11-06 16:44:32.537 W/art (13270): JNI RegisterNativeMethods: attempt to register 0 native methods for android.runtime.JavaProxyThrowable
11-06 16:44:32.542 D/Mono (13270): DllImport searching in: '__Internal' ('(null)').
11-06 16:44:32.542 D/Mono (13270): Searching for 'java_interop_jnienv_throw'.
11-06 16:44:32.542 D/Mono (13270): Probing 'java_interop_jnienv_throw'.
11-06 16:44:32.542 D/Mono (13270): Found as 'java_interop_jnienv_throw'.
An unhandled exception occured.
here is my code ViewModel class
public async void GetToday(DateTime filterdate, ObservableCollection<TodaysActivity> TodaysActivityList)
{
var count = 0;
ObservableCollection<TodaysProjectList> ne = new ObservableCollection<TodaysProjectList>();
activityTaskListViewModelService = new ActivityTaskListViewModelService();
foreach(TodaysActivity act in TodaysActivityList)
{
count = count + 1;
TodaysProjectList t = new TodaysProjectList()
{
clientName = act.clientName,
projectNick = act.projectNick,
DashboardActivitys = await activityTaskListViewModelService.GetActivityList(filterdate, act.projectId)
};
ne.Add(t);
// return;
}
Todays = todays;
}
Service class
public async Task<ObservableCollection<DashboardActivity>> GetActivityList(DateTime filterDate, int projectId)
{
if (CrossConnectivity.Current.IsConnected)
{
ObservableCollection<DashboardActivity> activityList = new ObservableCollection<DashboardActivity>();
string token = "";
if (Application.Current.Properties.ContainsKey("TOKEN_AUTH"))
{
token = Application.Current.Properties["TOKEN_AUTH"].ToString();
}
_client = new HttpClient();
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
getUrlActivity = constDomain + getUrlActivity;
var response = await _client.GetAsync(getUrlActivity + filterDate.ToString("MM/dd/yyyy") + "&projectId=" + projectId.ToString()).ConfigureAwait(true); //projectId=8113&activityId=817411
_client.Dispose();
if (response.IsSuccessStatusCode)
{
var str = await response.Content.ReadAsStringAsync();
dynamic attachment = JsonConvert.DeserializeObject(str);
var model = JsonConvert.DeserializeObject<List<DashboardActivity>>(str);
activityList = new ObservableCollection<DashboardActivity>(model);
for(int i=0;i<activityList.Count;i++)
{
var innerObj = attachment[i].attachments;
var obj = innerObj.ToObject<List<Attachments>>();
activityList[i].attachements = obj;
}
return activityList;
}
return null;
}
return null;
}

Getting exception while trying to get gps position through Xam.Location.Geoplugin

I was using this same code without problems before but now I'm not able to get the position and the app crashs with the exception bellow. The unique thing that I changed was the way that I'm calling the GetPosition method, before I was calling it by click event and now I have to call it at application starting.
10-19 00:36:47.648 E/mono (10400): Unhandled Exception:
10-19 00:36:47.648 E/mono (10400): System.Threading.Tasks.TaskCanceledException: A task was canceled.
10-19 00:36:47.648 E/mono (10400): at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x00026] in <43dbbdc147f2482093d8409abb04c233>:0
10-19 00:36:47.648 E/mono (10400): at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <43dbbdc147f2482093d8409abb04c233>:0
10-19 00:36:47.648 E/mono (10400): at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <43dbbdc147f2482093d8409abb04c233>:0
10-19 00:36:47.648 E/mono (10400): at System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult () [0x00000] in <43dbbdc147f2482093d8409abb04c233>:0
10-19 00:36:47.648 E/mono (10400): at Plugin.Geolocator.GeolocatorImplementation+<GetPositionAsync>d__41.MoveNext () [0x004d3] in <e6cb69436f5b455fa0a66dc46ca4b792>:0 Thread started: <Thread Pool> #18
10-19 00:36:47.648 E/mono (10400): --- End of stack trace from previous location where exception was thrown ---
10-19 00:36:47.648 E/mono (10400): at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0001a] in <43dbbdc147f2482093d8409abb04c233>:0 Thread started: <Thread Pool> #19
10-19 00:36:47.648 E/mono (10400): at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <43dbbdc147f2482093d8409abb04c233>:0
Thread started: <Thread Pool> #2010-19 00:36:47.648 E/mono (10400): at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <43dbbdc147f2482093d8409abb04c233>:0
10-19 00:36:47.648 E/mono (10400): at System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult () [0x00000] in <43dbbdc147f2482093d8409abb04c233>:0
10-19 00:36:47.648 E/mono (10400): at BatePapo.MainPage+<GetPosition>d__2.MoveNext () [0x000da] in D:\apps\BatePapo\BatePapo\BatePapo\MainPage.xaml.cs:29
10-19 00:36:47.648 E/mono (10400): --- End of stack trace from previous location where exception was thrown ---
10-19 00:36:47.648 E/mono (10400): at (wrapper dynamic-method) System.Object.75(intptr,intptr)
10-19 00:36:47.678 E/mono-rt (10400): [ERROR] FATAL UNHANDLED EXCEPTION: System.Threading.Tasks.TaskCanceledException: A task was canceled.
10-19 00:36:47.678 E/mono-rt (10400): at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x00026] in <43dbbdc147f2482093d8409abb04c233>:0
10-19 00:36:47.678 E/mono-rt (10400): at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <43dbbdc147f2482093d8409abb04c233>:0
10-19 00:36:47.678 E/mono-rt (10400): at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <43dbbdc147f2482093d8409abb04c233>:0
10-19 00:36:47.678 E/mono-rt (10400): at System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult () [0x00000] in <43dbbdc147f2482093d8409abb04c233>:0
10-19 00:36:47.678 E/mono-rt (10400): at Plugin.Geolocator.GeolocatorImplementation+<GetPositionAsync>d__41.MoveNext () [0x004d3] in <e6cb69436f5b455fa0a66dc46ca4b792>:0
10-19 00:36:47.678 E/mono-rt (10400): --- End of stack trace from previous location where exception was thrown ---
10-19 00:36:47.678 E/mono-rt (10400): at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0001a] in <43dbbdc147f2482093d8409abb04c233>:0
10-19 00:36:47.678 E/mono-rt (10400): at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <43dbbdc147f2482093d8409abb04c233>:0
10-19 00:36:47.678 E/mono-rt (10400): at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <43dbbdc147f2482093d8409abb04c233>:0
10-19 00:36:47.678 E/mono-rt (10400): at System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult () [0x00000] in <43dbbdc147f2482093d8409abb04c233>:0
10-19 00:36:47.678 E/mono-rt (10400): at BatePapo.MainPage+<GetPosition>d__2.MoveNext () [0x000da] in D:\apps\BatePapo\BatePapo\BatePapo\MainPage.xaml.cs:29
10-19 00:36:47.678 E/mono-rt (10400): --- End of stack trace from previous location where exception was thrown ---
10-19 00:36:47.678 E/mono-rt (10400): at (wrapper dynamic-method) System.Object.75(intptr,intptr)
10-19 00:36:47.684 D/ (10400): HostConnection::get() New Host Connection established 0xd09ad500, tid 10400
MainActivity.cs:
using System;
using Android;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Content.PM;
using Android.Util;
using Android.Support.V4.App;
using Android.Support.Design.Widget;
using System.Threading.Tasks;
namespace BatePapo.Droid
{
[Activity(Label = "MyApp", Icon = "#mipmap/icon", Theme = "#style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity, ActivityCompat.IOnRequestPermissionsResultCallback
{
protected async override void OnCreate(Bundle savedInstanceState)
{
await TryToGetPermissions();
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
}
#region RuntimePermissions
async Task TryToGetPermissions()
{
if ((int)Build.VERSION.SdkInt >= 23)
{
await GetPermissionsAsync();
return;
}
}
const int RequestLocationId = 0;
readonly string[] PermissionsGroupLocation =
{
Manifest.Permission.AccessCoarseLocation,
Manifest.Permission.AccessFineLocation,
};
async Task GetPermissionsAsync()
{
const string permission = Manifest.Permission.AccessFineLocation;
if (CheckSelfPermission(permission) == (int)Android.Content.PM.Permission.Granted)
{
//TODO change the message to show the permissions name
Toast.MakeText(this, "Permissões concedidas.", ToastLength.Short).Show();
return;
}
if (ShouldShowRequestPermissionRationale(permission))
{
//set alert for executing the task
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.SetTitle("Permissões necessárias");
alert.SetMessage("Esta aplicação precisa de permissões para continuar.");
alert.SetPositiveButton("Conceder permissões", (senderAlert, args) =>
{
RequestPermissions(PermissionsGroupLocation, RequestLocationId);
});
alert.SetNegativeButton("Cancelar", (senderAlert, args) =>
{
Toast.MakeText(this, "Cancelado!", ToastLength.Short).Show();
});
Dialog dialog = alert.Create();
dialog.Show();
return;
}
RequestPermissions(PermissionsGroupLocation, RequestLocationId);
}
public override async void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
switch (requestCode)
{
case RequestLocationId:
{
if (grantResults[0] == (int)Android.Content.PM.Permission.Granted)
{
Toast.MakeText(this, "Permissões especiais concedidas.", ToastLength.Short).Show();
}
else
{
//Permission Denied :(
Toast.MakeText(this, "Permissões especiais negadas.", ToastLength.Short).Show();
}
}
break;
}
//base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
#endregion
}
}
MainPage.Xaml.Cs
namespace MyApp
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MainPage : TabbedPage
{
public static Position position;
public MainPage()
{
GetPosition();
InitializeComponent();
}
private async void GetPosition()
{
try
{
var locator = CrossGeolocator.Current;
locator.DesiredAccuracy = 50;
position = await locator.GetPositionAsync(TimeSpan.FromSeconds(10));
}
catch (Exception)
{
throw;
}
}
}
}
Can anyone see the problem?
GetPosition is an Asynchronous method, you have to await it and then update the UI. You can't await in a Constructor, so you need to move your logic in to OnAppearing method
private async Task<Position> GetPositionAsync()
{
try
{
var locator = CrossGeolocator.Current;
locator.DesiredAccuracy = 50;
return await locator.GetPositionAsync(TimeSpan.FromSeconds(10));
}
catch (Exception)
{
// handle it properly
throw;
}
}
}
protected override async void OnAppearing()
{
base.OnAppearing();
var position = await GetPositionAsync();
}
Always use Task<T> return type for async methods, except for EventHandlers

HttpClient under Mono throwing an error

I'm attempting to use HttpClient under Mono (runs fine under .NET Framework), but I'm getting error;
04-25 14:07:14.952 I/Choreographer( 3238): Skipped 144 frames! The application may be doing too much work on its main thread.
[0:] An error occurred while sending the request
[0:] at System.Net.Http.HttpClientHandler+<SendAsync>c__async0.MoveNext () [0x0047a] in /Users/builder/data/lanes/4468/f913a78a/source/mono/mcs/class/System.Net.Http/System.Net.Http/HttpClientHandler.cs:383
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Users/builder/data/lanes/4468/f913a78a/source/mono/mcs/class/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:143
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x00047] in /Users/builder/data/lanes/4468/f913a78a/source/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:187
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x0002e] in /Users/builder/data/lanes/4468/f913a78a/source/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:156
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x0000b] in /Users/builder/data/lanes/4468/f913a78a/source/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:128
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1+ConfiguredTaskAwaiter[TResult].GetResult () [0x00000] in /Users/builder/data/lanes/4468/f913a78a/source/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:535
at System.Net.Http.HttpClient+<SendAsyncWorker>c__async0.MoveNext () [0x000a9] in /Users/builder/data/lanes/4468/f913a78a/source/mono/mcs/class/System.Net.Http/System.Net.Http/HttpClient.cs:276
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Users/builder/data/lanes/4468/f913a78a/source/mono/mcs/class/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:143
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x00047] in /Users/builder/data/lanes/4468/f913a78a/source/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:187
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x0002e] in /Users/builder/data/lanes/4468/f913a78a/source/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:156
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x0000b] in /Users/builder/data/lanes/4468/f913a78a/source/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:128
at System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult () [0x00000] in /Users/builder/data/lanes/4468/f913a78a/source/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:357
at MyWebClient+<MakeRequest>d__63.MoveNext () [0x0019b] in <4eeea402c92c428f818fd28bf1ed35bc>:0
My code;
var httpClient = new HttpClient { Timeout = new TimeSpan(0, 0, (int) TimeOut) };
foreach (var header in Headers)
{
httpClient.DefaultRequestHeaders.Add(header.Key, header.Value);
}
// attempting to workaround Xamarin bug
// http://forums.xamarin.com/discussion/17770/length-required-error-in-http-post-since-latest-release
var requestcontent = new HttpRequestMessage(HttpMethod.Post, Url)
{
Content = !string.IsNullOrEmpty(RequestStr)
? new StringContent(RequestStr, Encoding.UTF8, "application/json")
: new ByteArrayContent(new byte[0])
};
using (HttpResponseMessage response = await httpClient.SendAsync(requestcontent))
{
using (HttpContent content = response.Content)
{
ResponseStr = await content.ReadAsStringAsync();
}
}
I've tried to code around the issue (detailed here HttpClientHandler.cs:383), but it still throws error but works perfectly under NET Standard & NET46.
Here the Xamarin package versions;
Xamarin.Android.Support.Animated.Vector.Drawable.23.3.0
Xamarin.Android.Support.Design.23.3.0
Xamarin.Android.Support.v4.23.3.0
Xamarin.Android.Support.v7.AppCompat.23.3.0
Xamarin.Android.Support.v7.CardView.23.3.0
Xamarin.Android.Support.v7.MediaRouter.23.3.0
Xamarin.Android.Support.v7.RecyclerView.23.3.0
Xamarin.Android.Support.Vector.Drawable.23.3.0
Xamarin.Forms.2.3.4.231
The application may be doing too much work on its main thread.
This usually happens when you try to execute HTTP request on a main UI thread.

Xamarin.iOS SQLiteException: Corrupt

I'm building an application with Xamarin.Forms and a Portable Class Library.The app can be used on Android, iOS and UWP.
I've been building a database which now works on both Android and UWP. When I use the same code and run it on iOS it gives me some errors.
This is the exception message:
Unhandled Exception: SQLite.SQLiteException: Corrupt
This is the StackTrace:
at SQLite.PreparedSqlLiteInsertCommand.ExecuteNonQuery (System.Object[] source) [0x00116] in /Users/fak/Dropbox/Projects/sqlite-net/src/SQLite.cs:2480
at SQLite.SQLiteConnection.Insert (System.Object obj, System.String extra, System.Type objType) [0x0010e] in /Users/fak/Dropbox/Projects/sqlite-net/src/SQLite.cs:1381
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Users/builder/data/lanes/3818/ad1cd42d/source/xamarin-macios/_ios-build/Library/Frameworks/Xamarin.iOS.framework/Versions/git/src/mono/mcs/class/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:143
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x00047] in /Users/builder/data/lanes/3818/ad1cd42d/source/xamarin-macios/_ios-build/Library/Frameworks/Xamarin.iOS.framework/Versions/git/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:187
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x0002e] in /Users/builder/data/lanes/3818/ad1cd42d/source/xamarin-macios/_ios-build/Library/Frameworks/Xamarin.iOS.framework/Versions/git/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:156
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x0000b] in /Users/builder/data/lanes/3818/ad1cd42d/source/xamarin-macios/_ios-build/Library/Frameworks/Xamarin.iOS.framework/Versions/git/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:128
at System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult () [0x00000] in /Users/builder/data/lanes/3818/ad1cd42d/source/xamarin-macios/_ios-build/Library/Frameworks/Xamarin.iOS.framework/Versions/git/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:357
at App2.Model.Database.FormDAO+<InsertItem>d__2.MoveNext () [0x00066] in D:\SourceTree\App2\App2\Model\Database\FormDAO.cs:25
This is the code where the unhandled exception is:
public async void InsertItem(Form Form)
{
try
{
var result = await Task.Factory.StartNew(() => database.Insert(Form)); //this line
} catch(Exception e)
{
Debug.WriteLine("e.message" + e.Message + ";;;;" + e.StackTrace);
}
}
The function InsertItem(form) is called about 1000 times from another async method.
Why does this code not work on iOS?
Edit:
Other error I get is:
SQLite.SQLiteException: IOError
StackTrace:
at SQLite.PreparedSqlLiteInsertCommand.ExecuteNonQuery (System.Object[] source) [0x00116] in /Users/fak/Dropbox/Projects/sqlite-net/src/SQLite.cs:2480
at SQLite.SQLiteConnection.Insert (System.Object obj, System.String extra, System.Type objType) [0x0010e] in /Users/fak/Dropbox/Projects/sqlite-net/src/SQLite.cs:1381
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Users/builder/data/lanes/3818/ad1cd42d/source/xamarin-macios/_ios-build/Library/Frameworks/Xamarin.iOS.framework/Versions/git/src/mono/mcs/class/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:143
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x00047] in /Users/builder/data/lanes/3818/ad1cd42d/source/xamarin-macios/_ios-build/Library/Frameworks/Xamarin.iOS.framework/Versions/git/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:187
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x0002e] in /Users/builder/data/lanes/3818/ad1cd42d/source/xamarin-macios/_ios-build/Library/Frameworks/Xamarin.iOS.framework/Versions/git/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:156
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x0000b] in /Users/builder/data/lanes/3818/ad1cd42d/source/xamarin-macios/_ios-build/Library/Frameworks/Xamarin.iOS.framework/Versions/git/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:128
at System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult () [0x00000] in /Users/builder/data/lanes/3818/ad1cd42d/source/xamarin-macios/_ios-build/Library/Frameworks/Xamarin.iOS.framework/Versions/git/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:357
at App2.Model.Database.CourseDAO+<InsertItem>d__2.MoveNext () [0x00055] in D:\SourceTree\App2\App2\Model\Database\CourseDAO.cs:26
This exception is throwed when using almost the same method but then with this line:
var result = await Task.Factory.StartNew(() => database.Insert(Course));
The problem were the async calls to the database as Yuri S and SushiHangover pointed out in the comments.
First I didn't thought that the problem were the async calls to the database because it did work on Android and UWP. But when I made all the calls synchronised the database did work on all the three platforms: UWP, Android, iOS.
Thanks!

Reading mp3 track duration on Android

On Android I am getting this error Java.Lang.IllegalArgumentException:
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000b] in /Users/builder/data/lanes/2058/58099c53/source/mono/mcs/class/corlib/System.Runtime.ExceptionServices/ExceptionDispatchInfo.cs:61
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.m__0 (object) [0x00000] in /Users/builder/data/lanes/2058/58099c53/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/AsyncMethodBuilder.cs:1006
at Android.App.SyncContext/c__AnonStorey0.<>m__0 () [0x00000] in /Users/builder/data/lanes/2058/58099c53/source/monodroid/src/Mono.Android/src/Android.App/SyncContext.cs:18
at Java.Lang.Thread/RunnableImplementor.Run () [0x0000b] in /Users/builder/data/lanes/2058/58099c53/source/monodroid/src/Mono.Android/src/Java.Lang/Thread.cs:36
at Java.Lang.IRunnableInvoker.n_Run (intptr,intptr) [0x00009] in /Users/builder/data/lanes/2058/58099c53/source/monodroid/src/Mono.Android/platforms/android-21/src/generated/Java.Lang.IRunnable.cs:71
at (wrapper dynamic-method) object.7dac782f-30e4-45cb-a248-e0c4c79fbcad (intptr,intptr)
--- End of managed exception stack trace --- java.lang.IllegalArgumentException at
android.media.MediaMetadataRetriever.setDataSource(MediaMetadataRetriever.java:169) at dalvik.system.NativeStart.run(Native Method)
using this code to retrive *.mp3 file duration:
public async Task<string> GetTrackDuration(string pathToFile)
{
MediaMetadataRetriever reader = new MediaMetadataRetriever();
await reader.SetDataSourceAsync (global::Android.App.Application.Context, Android.Net.Uri.Parse (pathToFile));
return reader.ExtractMetadata(MetadataKey.Duration).ToString();
}
where is the problem? I have tried all of the posible constructors

Categories