My application closes without throwing any exceptions when I try to use Xamarin.Essentials' FilePicker class.
What did I do:
added:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
And the code:
async Task<FileResult> PickAndShow(PickOptions options)
{
try
{
var result = await FilePicker.PickAsync();
if (result != null)
{
Text = $"File Name: {result.FileName}";
if (result.FileName.EndsWith("jpg", StringComparison.OrdinalIgnoreCase) ||
result.FileName.EndsWith("png", StringComparison.OrdinalIgnoreCase))
{
var stream = await result.OpenReadAsync();
Image = ImageSource.FromStream(() => stream);
}
}
}
catch (Exception ex)
{
// The user canceled or something went wrong
}
}
I am using VS for MacOS.
Video of closing the app:
https://drive.google.com/file/d/1H1488amryi_p7mkg7JdmhcGAE569KON4/view?usp=sharing
Please help me to see what I'm missing?
Edit:
line that the error occurs
var result = await FilePicker.PickAsync();
Exception:
No exception is thrown;
application exit:
[Mono] Requesting loading reference 5 (of 8) of Xamarin.Essentials.dll
[Mono] Loading reference 5 of Xamarin.Essentials.dll asmctx DEFAULT, looking for System.Core, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e
[Mono] Assembly Ref addref Xamarin.Essentials[0x7ddc93de80] -> System.Core[0x7d850f7880]: 10
[Choreographer] Skipped 711 frames! The application may be doing too much work on its main thread.
[OpenGLRenderer] Davey! duration=12935ms; Flags=0, IntendedVsync=24578200518089, Vsync=24591127790687, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=24591131789208, AnimationStart=24591131799939, PerformTraversalsStart=24591132369131, DrawStart=24591132532323, SyncQueued=24591132572054, SyncStart=24591133134246, IssueDrawCommandsStart=24591133217554, SwapBuffers=24591134886554, FrameCompleted=24591136679054, DequeueBufferDuration=219000, QueueBufferDuration=280000,
[mali_winsys] EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, EGLBoolean) returns 0x3000
[libEGL] EGLNativeWindowType 0x7de100a210 disconnect failed
[Mono] Requesting loading reference 12 (of 22) of Xamarin.Forms.Platform.Android.dll
[Mono] Loading reference 12 of Xamarin.Forms.Platform.Android.dll asmctx DEFAULT, looking for System.Runtime.Serialization, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e
[Mono] Assembly Ref addref Xamarin.Forms.Platform.Android[0x7d852aa080] -> System.Runtime.Serialization[0x7d77336a00]: 3
[Mono] Requesting loading reference 21 (of 22) of Xamarin.Forms.Platform.Android.dll
[Mono] Loading reference 21 of Xamarin.Forms.Platform.Android.dll asmctx DEFAULT, looking for System.Xml, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e
[Mono] Assembly Ref addref Xamarin.Forms.Platform.Android[0x7d852aa080] -> System.Xml[0x7d7769b100]: 6
[libEGL] EGLNativeWindowType 0x7d5d049310 disconnect failed
And Log For Device:
Image Log
I thank everyone and apologize for the inconvenience. The culprit is me for the bad behavior. There was no exception because there really wasn't one. The problem is that the application is launched in the background when you open the files, and in my code I have:
public static void Background()
{
activity.MoveTaskToBack(true);
}
I had forgotten. I still need this in another situation, so I resolved this way:
public static void Background()
{
if (App.Current.importClicked) App.Current.importClicked = false;
else activity.MoveTaskToBack(true);
}
Once again I apologize.
Related
I have two questions about Android Callable Wrappers which I hope you guys could answer.
Question 1. Xamarin auto-generates the following constructor in the ACW of a class:
public ConsumerService (java.lang.String p0, android.content.Context p1)
{
super (p0, p1);
if (getClass () == ConsumerService.class)
mono.android .TypeManager.Activate ("Test.Tizen.Droid.ConsumerService, Test.Tizen.Droid", "System.String, mscorlib:Android.Content.Context, Mono.Android ", this, new java.lang.Object[] { p0, p1 });
}
But then throws following exception on startup of the app: System.TypeLoadException: Could not load type '.mscorlib' from assembly 'Mono.Android , Version=0.0.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065'.
Which references to this part in the constructor: mscorlib:Android.Content.Context. Removing the "mscorlib:" fixes the exception, but my question is, why does it throw an exception in the first place since Xamarin auto-generates this?
Question 2. Can anyone tell me why Xamarin only takes the base class into account when generating the ACW of a derived class, and doesn't take the constructors of the derived class into account?
I get the following error while executing my Xamarin Android app in release mode. I suppose something is missing in LinkerPleaseInclude.cs, but the error message is not very helpful.
09-25 16:17:38.140 W/art ( 1082): JNI RegisterNativeMethods: attempt to register 0 native methods for mvvmcross.binding.droid.views.MvxRadioGroup
[0:] MvxBind:Error: 2,89 Exception thrown during the view binding ArgumentNullException: missing source event info in MvxWeakEventSubscription
Parameter name: sourceEventInfo
at MvvmCross.Platform.WeakSubscription.MvxWeakEventSubscription`2[TSource,TEventArgs]..ctor (Android.Widget.TextView source, System.Reflection.EventInfo sourceEventInfo, System.EventHandler`1[TEventArgs] targetEventHandler) [0x00017] in <54d9eb77c4d448d4bc5e7c7a5cdd0a97>:0
at MvvmCross.Platform.WeakSubscription.MvxWeakEventSubscription`2[TSource,TEventArgs]..ctor (Android.Widget.TextView source, System.String sourceEventName, System.EventHandler`1[TEventArgs] targetEventHandler) [0x00012] in <54d9eb77c4d448d4bc5e7c7a5cdd0a97>:0
at MvvmCross.Platform.WeakSubscription.MvxWeakSubscriptionExtensionMethods.WeakSubscribe[TSource,TEventArgs] (TSource source, System.String eventName, System.EventHandler`1[TEventArgs] eventHandler) [0x00000] in <54d9eb77c4d448d4bc5e7c7a5cdd0a97>:0
at MvvmCross.Binding.Droid.Target.MvxTextViewTextTargetBinding.SubscribeToEvents () [0x0000b] in <cc9453c0f5794d529a8b1975bb62dd40>:0
at MvvmCross.Binding.Bindings.MvxFullBinding.CreateTargetBinding (System.Object target) [0x00057] in <5d9349f2d9c240e38eaeca40fe71d977>:0
at MvvmCross.Binding.Bindings.MvxFullBinding..ctor (MvvmCross.Binding.MvxBindingRequest bindingRequest) [0x0002f] in <5d9349f2d9c240e38eaeca40fe71d977>:0
at MvvmCross.Binding.Binders.MvxFromTextBinder.BindSingle (MvvmCross.Binding.MvxBindingRequest bindingRequest) [0x00000] in <5d9349f2d9c240e38eaeca40fe71d977>:0
at MvvmCross.Binding.Binders.MvxFromTextBinder+<>c__DisplayClass2_0.<Bind>b__0 (MvvmCross.Binding.Bindings.MvxBindingDescription description) [0x00018] in <5d9349f2d9c240e38eaeca40fe71d977>:0
at System.Linq.Utilities+<>c__DisplayClass2_0`3[TSource,TMiddle,TResult].<CombineSelectors>b__0 (TSource x) [0x00012] in <9ecdeee51aa740839577d6db9550e95f>:0
at System.Linq.Utilities+<>c__DisplayClass2_0`3[TSource,TMiddle,TResult].<CombineSelectors>b__0 (TSource x) [0x00000] in <9ecdeee51aa740839577d6db9550e95f>:0
at (wrapper delegate-invoke) System.Func`2[System.Collections.Generic.KeyValuePair`2[System.String,MvvmCross.Binding.Parse.Binding.MvxSerializableBindingDescription],System.Collections.Generic.KeyValuePair`2[System.Object,MvvmCross.Binding.Bindings.IMvxUpdateableBinding]]:invoke_TResult_T (System.Collections.Generic.KeyValuePair`2<string, MvvmCross.Binding.Parse.Binding.MvxSerializableBindingDescription>)
at System.Linq.Enumerable+SelectEnumerableIterator`2[TSource,TResult].MoveNext () [0x00048] in <9ecdeee51aa740839577d6db9550e95f>:0
at System.Collections.Generic.List`1[T].InsertRange (System.Int32 index, System.Collections.Generic.IEnumerable`1[T] collection) [0x000ea] in <b2855d13f99e445b95990a59348d98e8>:0
at System.Collections.Generic.List`1[T].AddRange (System.Collections.Generic.IEnumerable`1[T] collection) [0x00000] in <b2855d13f99e445b95990a59348d98e8>:0
at MvvmCross.Binding.Droid.Binders.MvxAndroidViewBinder.StoreBindings (Android.Views.View view, System.Collections.Generic.IEnumerable`1[T] newBindings) [0x00028] in <cc9453c0f5794d529a8b1975bb62dd40>:0
at MvvmCross.Binding.Droid.Binders.MvxAndroidViewBinder.ApplyBindingsFromAttribute (Android.Views.View view, Android.Content.Res.TypedArray typedArray, System.Int32 attributeId) [0x0001c] in <cc9453c0f5794d529a8b1975bb62dd40>:0
I see, something is missing with MvxRadioGroup. How do I find out what to add in LinkerPleaseInclude?
My binding for MvxRadioGroup is the following:
<MvxRadioGroup
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginTop="6dp"
local:MvxBind="ItemsSource GenderAnswers; SelectedItem GenderAnswer"
local:MvxItemTemplate="#layout/radioitem_enum" />
and my LinkerPleaseInclude is still empty.
Here's the defintiion of the properties in view model:
public IEnumerable<GenderQuestionAnswers> GenderAnswers => Enum.GetValues(typeof(GenderQuestionAnswers)).Cast<GenderQuestionAnswers>();
public GenderQuestionAnswers? GenderAnswer
{
get => _genderAnswer;
set => SetProperty(ref _genderAnswer, value);
}
[edit 2017-09-27]: added code for MvxRadioGroup binding
[edit 2017-09-27]: added snippet for properties in view model
I ended up adding theses lines to LinkerPleaseInclude in addition to the file mentioned by #york-shen-msft
public void Include(RadioButton radioButton)
{
radioButton.CheckedChange += (sender, args) => radioButton.Checked = args.IsChecked
}
Well, that doesn't really answer my question as I wanted to know how to find the correct solution without searching the whole internet for lines others included before and do trial and error, but it solves my actual problem for the moment.
I have Xamarin Forms PCL application and I am trying to inherit from HttpContent in attempt to follow this reference. I would like to implement progress bar for image upload. Here is my implementation which contains minimum code to implement HttpContent:
public class ProgressableStreamContent : HttpContent
{
public ProgressableStreamContent()
{ }
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
return Task.Run(async () =>
{
});
}
protected override bool TryComputeLength(out long length)
{
length = 0;
return true;
}
}
and I have procedure that is using this ProgressableStreamContent:
public async void UseProgressableStreamContent()
{
var progressableContent = new ProgressableStreamContent();
}
Problem is that this code produces exception:
UNHANDLED EXCEPTION: System.TypeLoadException: Could not load type 'MyApp.Classes.ProgressableStreamContent' from assembly 'MyApp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
When I comment out line "var progressableContent = new ProgressableStreamContent();" - everything works good.
When I comment out inheritance ": HttpContent" (and override keywords) - everything works good.
Should I install some package? What else could be a problem?
I resolved issue by changing profile from 259 to 7. Changing profile includes deleting all NuGet packages and installing them again after profile change.
I am trying to integrate a windows phone 8 app game with AdMob but am having some difficultly (I am using the latest ad mob widows sdk - 6.5.11).
I can load and display AdMob Banners no problem, but get errors when I try to load an interstitial advert.
Basically, when the ad is loaded I get the following exceptions:
An exception of type 'System.SystemException' occurred in Microsoft.Phone.Interop.ni.dll and wasn't handled before a managed/native boundary
An exception of type 'System.SystemException' occurred in Microsoft.Phone.Interop.ni.dll and wasn't handled before a managed/native boundary
Failed to receive int ad with error NoFill
SO when I try to show the add I obviously get further exceptions:
An exception of type 'System.SystemException' occurred in Microsoft.Phone.Interop.ni.dll and wasn't handled before a managed/native boundary
GoogleAds.InterstitialAd
'TaskHost.exe' (CLR C:\windows\system32\coreclr.dll: Silverlight AppDomain): Loaded 'C:\windows\system32\en-US\mscorlib.debug.resources.dll'. Module was built without symbols.
A first chance exception of type 'System.NullReferenceException' occurred in GoogleAds.DLL
Here is my code for loading:
public static void LoadAdverts()
{
runInUIThread(
() =>
{
LoadGoogleInterstitialAd();
});
}
private static void LoadGoogleInterstitialAd()
{
// Initialize the ad
mGoogleInterstitialAd = new InterstitialAd(mGoogleInterstitialAdUnitID);
// Attach the interstitial event handlers.
mGoogleInterstitialAd.ReceivedAd += OnGoogleInterstitialAdReceived;
mGoogleInterstitialAd.FailedToReceiveAd += OnFailedToReceiveGoogleInterstitialAd;
mGoogleInterstitialAd.DismissingOverlay += OnDismissingGoogleOverlay;
AdRequest mGoogleInterstitialAdRequest = new AdRequest();
mGoogleInterstitialAdRequest.ForceTesting = true;
mGoogleInterstitialAd.LoadAd(mGoogleInterstitialAdRequest);
}
The LoadAd() method is the one that generates the initial System exceptions.
Then to show the ad:
public static void DisplayOverlayAdvert()
{
// Check that the overlay ad is not already displayed.
if (!mIsGoogleInterstitialAdActive)
{
runInUIThread(
() =>
{
DisplayGoogleInterstitialAd();
});
}
}
/// <summary>
/// This method displays an advert in the advert container grid.
/// </summary>
private static void DisplayGoogleInterstitialAd()
{
mGoogleInterstitialAd.ShowAd();
// Set the flag to true as the ad is displayed.
mIsGoogleInterstitialAdActive = true;
}
ANy help will be greatly appreciated.
I would hazard a guess that DisplayGoogleInterstitialAd is being called before LoadGoogleInterstitialAd.
Please help me with this one, I've been writing a console applicaiton using the AsyncCtpLibrary and the C#5 ctp compiler. First time I got to actually running a code which awaits, I got this:
System.BadImageFormatException was unhandled
Message=An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)
Source=AsyncCtpLibrary
StackTrace:
Server stack trace:
at [...].<Execute>d__1c.MoveNext()
at [...].Execute()
at [...].<Move>d__1d.MoveNext() in[..]:line 266
Exception rethrown at [0]:
at System.Runtime.CompilerServices.AsyncVoidMethodBuilder.<SetException>b__1(Object state)
at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
InnerException:
Am I missing a dll to be referenced?
important new stuff
My failing method looks like this:
public async override Task<bool> Execute()
{
//do stuff
await stuff;
//do other stuff
await base.Execute()
//do other stuff
return true;
}
I've followed Jon Skeet's advice trying to recreate the mistake little by little, and now I can tell that the await base.Execute() line is the killer! If I comment that line out, everything runs, if I leave it in, calling my method fails IMMEDIATELY (not when reaching the base.Execute()). So I assume the ctp compiler does something freaky. Why? What should I never do? How big is the bug?
old stuff:
EDIT:
As for 32bit/64bit issue, my system is 32bit (inside a virtual machine, mind you), and as far as I know AsyncCtpLibrary.dll doesn't contain unmanaged code. All my projects (class libraries and single console app) all have build tabs like this:
What can possibly be still wrong?
EDIT:
I also checked the Fusion log viewer, the AsyncCtpLibrary is loaded without any error:
*** Assembly Binder Log Entry (6/10/2011 # 9:04:11 PM) ***
The operation was successful.
Bind result: hr = 0x0. The operation completed successfully.
Assembly manager loaded from: C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll
Running under executable C:\Users\Daver\Documents\Visual Studio 2010\Projects\[...]\bin\Debug\MyApp.exe
--- A detailed error log follows.
=== Pre-bind state information ===
LOG: User = WIN-N74LV38NLV3\Daver
LOG: DisplayName = AsyncCtpLibrary, Version=1.0.4107.18181, Culture=neutral, PublicKeyToken=31bf3856ad364e35
(Fully-specified)
LOG: Appbase = file:///C:/Users/Daver/Documents/Visual Studio 2010/Projects/[...]/bin/Debug/
LOG: Initial PrivatePath = NULL
LOG: Dynamic Base = NULL
LOG: Cache Base = NULL
LOG: AppName = MyApp.exe
Calling assembly : MyLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null.
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: C:\Users\Daver\Documents\Visual Studio 2010\Projects\[...]\bin\Debug\MyApp.exe.Config
LOG: Using host configuration file:
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Post-policy reference: AsyncCtpLibrary, Version=1.0.4107.18181, Culture=neutral, PublicKeyToken=31bf3856ad364e35
LOG: GAC Lookup was unsuccessful.
LOG: Attempting download of new URL file:///C:/Users/Daver/Documents/Visual Studio 2010/Projects/[...]/bin/Debug/AsyncCtpLibrary.DLL.
LOG: Assembly download was successful. Attempting setup of file: C:\Users\Daver\Documents\Visual Studio 2010\Projects\[...]\bin\Debug\AsyncCtpLibrary.dll
LOG: Entering run-from-source setup phase.
LOG: Assembly Name is: AsyncCtpLibrary, Version=1.0.4107.18181, Culture=neutral, PublicKeyToken=31bf3856ad364e35
LOG: Binding succeeds. Returns assembly from C:\Users\Daver\Documents\Visual Studio 2010\Projects\[...]\bin\Debug\AsyncCtpLibrary.dll.
LOG: Assembly is loaded in default load context.
I also checked the IL code of the <Execute>d__1c compiler-generated class' MoveNext() method, and the only assemblies it references ([assemblyName]) are mscorlib, System.Core, and AsyncCtpLibrary.
I checked the manifest of both my dll and AsyncCtpLibrary, mine said .corflags 0x00000003 // ILONLY 32BITREQUIRED, AsyncCtpLibrary said .corflags 0x00000009 // ILONLY, I'm unsure if this can be the problem.
Please help, I'm out of ideas!
EDIT: I've heard back from the compiler team, who have confirmed it as a bug. It had already been fixed in their codebase, so hopefully we'll see that fix in the next release / beta / CTP. The fix isn't going to be back-ported to "normal" VS2010 as it's a pretty unusual set of circumstances, at least before async.
EDIT: Okay, I've now got a really short but complete program which demonstrates the problem. I believe it's a mixture of generics and calling a base method:
using System;
using System.Threading.Tasks;
public abstract class AsyncAction<T>
{
public virtual Task<T> Execute()
{
// We never get this far
Console.WriteLine("Execute called");
return null;
}
}
public class BoolAction : AsyncAction<bool>
{
public async override Task<bool> Execute()
{
return await base.Execute();
}
}
class Test
{
static void Main()
{
BoolAction b = new BoolAction();
b.Execute();
}
}
EDIT: Okay, I've come up with a workaround. Basically, to call the base class method non-virtually, the compiler creates a synthetic method in BoolAction. It gets that slightly wrong, but we can get it right:
public class BoolAction : AsyncAction<bool>
{
public async override Task<bool> Execute()
{
return await BaseExecute();
}
private Task<bool> BaseExecute()
{
return base.Execute();
}
}
So whenever you were writing base.Execute, write BaseExecute and insert that extra method. It's not too bad a workaround, until the team fix the bug.
EDIT: I've simplified the example a bit - you don't need any overrides, and in particular you don't need the base class to expose a Task<T>. A call to any virtual base.Foo method will do it:
public abstract class AsyncAction<T>
{
public virtual T GetT()
{
return default(T);
}
}
public class BoolAction : AsyncAction<bool>
{
#pragma warning disable 1998 // We're not awaiting anything
public async void Execute()
{
base.GetT();
}
#pragma warning restore 1998
}
class Test
{
static void Main()
{
BoolAction b = new BoolAction();
b.Execute();
}
}
EDIT: Contrary to my previous thoughts, this does affect iterators as well. No async CTP required...
public abstract class Base<T>
{
public virtual T GetT()
{
return default(T);
}
}
public class Derived : Base<bool>
{
public System.Collections.IEnumerator Foo()
{
base.GetT();
yield break;
}
}
class Test
{
static void Main()
{
Derived d = new Derived();
d.Foo().MoveNext();
}
}
EDIT: And it affects anonymous functions too...
using System;
public abstract class Base<T>
{
public virtual T GetT()
{
return default(T);
}
}
public class Derived : Base<bool>
{
public void Foo()
{
Action x = () => base.GetT();
x();
}
}
class Test
{
static void Main()
{
Derived d = new Derived();
d.Foo();
}
}
You are hitting known VS 2010 bug
https://connect.microsoft.com/VisualStudio/feedback/details/626550/badimageformatexception-on-simple-program-using-generics-and-lambdas
This exception often occurs when you try and load a 32 bit DLL in a 64 bit environment.
If you are running on a 64 bit OS try changing your projects settings to compile directly for x86 (rather than AnyCPU).
(This might sound backwards, but it's because if you are loading an external 32 bit DLL you need to force your whole project to be 32 bit.)