What Dotnet native directives to use for AsyncAwaitBestPractices.MVVM? - xamarin.forms

I'm using AsyncAwaitBestPractices.MVVM's IAsyncCommand and AsyncCommand in my Xamarin.Forms app. The UWP version of the app is compiled with .NET Native tool chain. When I do SomeAsyncCommand.RaiseCanExecuteChanged(), I get an exception:
System.Reflection.MissingMetadataException: 'This operation cannot be carried out because metadata for the following object was removed for performance reasons:\n\n EETypeRva:0x000976A0\n\nNo further information is available. Rebuild in debug mode for better information.\n\n'
Note that this was a debug build. When I added a local copy of the library, I was able to find the line that triggers the exception:
static bool IsLightweightMethod(this MethodBase method)
{
var typeInfoRTDynamicMethod = typeof(DynamicMethod).GetTypeInfo().GetDeclaredNestedType("RTDynamicMethod");
return ...
}
The exception is triggered by GetDeclaredNestedType("RTDynamicMethod"). So the binaries do include the metadata of DynamicMethod, but not that of it's child type RTDynamicMethod. They have been removed because of .NET Native tool chain.
Now, I read that you can whitelist classes / namespaces / assemblies in project properties -> Default.rd.xml. But I can't seem to get the right element to whitelist the nested class. Here's what I tried:
<Assembly Name="System.Private.CoreLib" Dynamic="Required All" />
<Namespace Name="System.Reflection.Emit" Dynamic="Required All" />
<Type Name="System.Reflection.Emit.DynamicMethod">
<Type Name="RTDynamicMethod" Dynamic="Required All"/>
</Type>
Here System.Private.CoreLib is the assembly of DynamicMethod, System.Reflection.Emit is the namespace of DynamicMethod and RTDynamicMethod. As far as I understand, either of the three should work, yet none of them do. Edit: the type one gives me a warning: Default.rd.xml(35): warning : ILTransform : warning ILT0027: Type 'System.Reflection.Emit.DynamicMethod' could not be found.
I also tried variations using Type Name="System.Reflection.Emit.DynamicMethod+RTDynamicMethod", using <Library>, with or without namespaces in type, etc.

At first, you can try to use the following code in the Default.rd.xml:
<Type Name="System.Reflection.Emit.DynamicMethod" Dynamic="Required All">
<Type Name="System.Reflection.Emit.RTDynamicMethod" Dynamic="Required All">
For more information, you can check the similar case and the issue on the github.
In addition, why did you add the tag .net 6.0? I have checked the package named System.Reflection.Emit, the last update time is 12/4/2019 and it does't support the .net 6.0.

Related

Android.Views.InflateException: 'Binary XML file line #1: Binary XML file line #1: Error inflating class android.support.v7.widget.Toolbar'

After updating my app from FormsApplicationActivity to FormsAppCompatActivity, I get the following exception thrown in base.OnCreate(bundle):
Android.Views.InflateException: 'Binary XML file line #1: Binary XML file line #1: Error inflating class android.support.v7.widget.Toolbar'
This seems to come from my layout/Toolbar.xml file, which I have not changed from the default.
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
The funny thing is, if I create a new project, it works. As far as I can tell, everything is exactly the same between my old upgraded project and the brand new one.
Things I've tried:
Add Theme = "#style/MainTheme" to the [Activity] attribute
Add android:theme="#style/MainTheme" to the <application> tag of AndroidManifest.xml
Add
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
to OnCreate()
Copy styles.xml, colors.xml, Toolbar.xml, Tabbar.xml from the working project into the old project
Clean solution + delete bin/obj folders + rebuild
Doing a diff between the .csproj files and replacing almost everything from the working file into the bad file
Completely uninstall Xamarin Forms and all AndroidX dependencies, then reinstall from NuGet. The AndroidX dependencies were not readded, which matches the newly created project
None of it worked. How do I fix this?
It seems the exception is actually harmless. It appears to be caught inside base.OnCreate() and handled, not bubbled up to my code.
You can stop the debugger from breaking by going to Debug --> Windows --> Exception Settings, and unchecking Common Language Runtime Exceptions --> <All Common Runtime Language Exceptions not in this list
Unfortunately, unlike normal C# development, Xamarin seems to have no option for "only break on unhandled exceptions" :(
[Edit] In VS 2022 there is a bug causing exceptions to break even when you tell it not to. I'm not aware of any workaround. Sigh.
I also just came across this issue when upgrading from FormsApplicationActivity to FormsAppCompatActivity
The fix for me was adding Droid/Resources/values/styles.xml from the blank template app:
<?xml version="1.0" encoding="utf-8" ?>
<resources>
<style name="MainTheme" parent="MainTheme.Base">
<!-- can be empty in this tag, or have your project config -->
</style>
</resources>
This was added as a transform file in the csproj:
<TransformFile Include="Resources\values\styles.xml" />
I then had to update my main activity attribute
[Activity(
...
Theme = "#style/MainTheme",
...)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity

webforms dependency injection CS7036: There is no argument given that corresponds to the required formal parameter

I've followed this blog post describing how to integrate dependency injection using the Microsoft container in my web forms project but I'm getting:
Compiler Error Message: CS7036: There is no argument given that corresponds to the required formal parameter 'myService' of 'MyUserControl.MyUserControl(IMyService)'
Source Error:
Line 165:
Line 166: [System.Diagnostics.DebuggerNonUserCodeAttribute()]
Line 167: public calls_new_mycontrol_ascx() {
Line 168: ((global::MyCompany.Web.MyUserControl)(this)).AppRelativeVirtualPath = "~/MyUserControl.ascx";
Line 169: if ((global::ASP.calls_new_mycontrol_ascx.#__initialized == false)) {
I've forked the sample and it works with a user control. I can't seem to figure out what is different between the two projects.
I've upgraded my project to 4.8 Framework
I've added a nuget reference to Microsoft.CodeDom.Providers.DotNetCompilerPlatform 2.0.1
I met the same problem and my solution was to add a default constructor in my class
In your case
public MyUserControl(){}
would solve the problem.
In web.config add <httpRuntime targetFramework="4.7.2"/>.
<configuration>
<system.web>
<!--Use Dependency Injection In WebForms Application-->
<httpRuntime targetFramework="4.7.2"/>
</system.web>
</configuration>
Source: ASP.NET Blog Post on DI in Webforms

Xamarin.Forms + Xamarin.ios Entityframework Core 2.1.1 build error

I'm working on Xamarin.ios application with Microsoft.EntityframeworkCore.Sqlite version 2.1.1 with Xamarin.forms .NetStandard 2.0 version. I'm unable to build the application on iPhone, getting the below error:
MTOUCH: Error MT3001: Could not AOT the assembly 'project_name/iOS/obj/iPhone/Debug/device-builds/iphone10.2-11.0.2/mtouch-cache/Build/Microsoft.EntityFrameworkCore.dll' (MT3001) (project_name.iOS)
Could any one please help me to get through the error, I tried to downgrade the entityframework version to 2.0.0 and also downgrade the Microsoft.extension.* version to 2.0.0.
Linker behavior : Don't Link/ Link SDK only
SDK Version: 11.0
I had a similar error when implementing EntityFrameworkCore in the project I am working on. The solution for me was to add a file to my iOS project, and have these contents. Also, I am running Microsoft.EntityFrameworkCore.Sqlite version 2.0.2 currently with no problems.
<?xml version="1.0" encoding="utf-8" ?>
<linker>
<!-- LinkDescription.xml. File added to iOS project by #cwrea for adaptation to EF Core.
Prevents runtime errors when reflection is used for certain types that are not otherwise referenced
directly in the project, and that would be removed by the Xamarin linker.
These kinds of runtime errors do occur in particular when using Entity Framework Core on iOS. EF Core's
query parser does reference certain .NET methods _only_ via reflection, and it is those reflection-only
instances that we need to guard against by ensuring the linker includes them. For the curious, search
for mentions of "GetRuntimeMethod" at https://github.com/aspnet/EntityFramework. Use of EF Core more
advanced than this sample may require additional types/methods added to those below.
Include the following in the project build settings under "Additional mtouch arguments":
[hyphen][hyphen]xml=${ProjectDir}/LinkDescription.xml
There is supposed to be a "LinkDescription" build action for this linker config file so the step above
shouldn't be necessary, but at time of writing Visual Studio 2017 for PC doesn't show that build action
in iOS projects, even though it is an option within iOS projects on Visual Studio 2017 for Mac.
-->
<assembly fullname="mscorlib">
<type fullname="System.String">
<method name="Compare"></method>
<method name="CompareTo"></method>
<method name="ToUpper"></method>
<method name="ToLower"></method>
</type>
</assembly>
<assembly fullname="System.Core">
<type fullname="System.Linq.Expressions.Expression`1"></type>
<type fullname="System.Linq.Queryable"></type>
</assembly>
</linker>
You will also need to set that files Build Action to LinkDescription. Also, you don't need to copy that file to the output directory. It is only used during the build.
In your project settings for the iOS project, you will need to put --xml=${ProjectDir}/LinkDescription.xml in the Additional mtouch arguments section in iOS Build.
Hope this helps!

Precompiled Views and CompilationCallback

I've defined a compilation callback for my MVC views like
var mvc = services.AddMvc();
mvc.AddRazorOptions(razorSetup => {
razorSetup.CompilationCallback = context => {
// context.Compilation = context.Compilation.AddReferences(...)
};
});
This works great - and while debugging, there's no problem - but when the build-tools are precompiling the views (and as of asp.net core 2, precompiling is the default behavior), the compilation callback is just not used anymore.
While this makes perfect sense to me (after a bit of struggling), I wan't to know how/where I can configure the precompilation task.
I finally found a solution...
.net core 2
In .net core 2 you can add a --configure-compilation-type=-Option to the respone file used during compilation. The value should be a fully qualified type that implements Microsoft.AspNetCore.Mvc.IDesignTimeMvcBuilderConfiguration (not sure if it's necessarry or if it's sufficient to have a Configure-method here)
Adding can be done via
<Target Name="_AddMvzRazorPrecompileOptions" AfterTargets="_CreateResponseFileForMvcRazorPrecompile">
<Error Condition="!Exists($(_MvcRazorResponseFilePath))" Text="File $(_MvcRazorResponseFilePath) does not exist" />
<ItemGroup>
<_Option Include="--configure-compilation-type=KlugeSoftware.Web.ViewTranslator.PrecompileFactory, KlugeSoftware.Web.ViewTranslator" />
</ItemGroup>
<WriteLinesToFile File="$(_MvcRazorResponseFilePath)" Lines="#(_Option)" Overwrite="false" />
</Target>
.net core 3
Not that easy (at least I didn't find anything so far). But you can use a similar way to get your code between razor generation (creation of *.g.cs - files) and compiling them.
<Target Name="_DoSomethingSpecial" AfterTargets="PrepareForRazorCompile" BeforeTargets="RazorCoreCompile">
<!-- ... -->
</Target>
At this point, you can use a custom msbuild task to inspect or modify the generated code (and/or the source code).
Source files are stored in #(RazorCompile), dependencies in #(RazorReferencePath)....

Wix setup failing with error 1603

I have written a .NET 4 desktop application and when trying to run the Setup.exe I am getting the following error in the log file.
I am using Visual Studio 2012 with Wix 3.7.
MSI (s) (E8:1C) [16:51:54:890]: Invoking remote custom action. DLL: C:\windows\Installer\MSIFECD.tmp, Entrypoint: EncryptConfig
SFXCA: Extracting custom action to temporary directory: C:\windows\Installer\MSIFECD.tmp-\
SFXCA: Binding to CLR version v4.0.30319
Calling custom action SecureConfig!SecureConfig.CustomActions.EncryptConfig
EncryptConfig: Begin
An error occurred creating the configuration section handler for security: Could not load file or assembly 'Order.Configuration.Net' or one of its dependencies. The system cannot find the file specified. (C:\Program Files (x86)\Orbit Order System\Orbit Order System.exe.config line 6)
CustomAction EncryptConfigurationFile returned actual error code 1603 (note this may not be 100% accurate if translation happened inside sandbox)
Action ended 16:51:55: InstallFinalize. Return value 3.
I can confirm that `Order.Configuration.Net.dll' exists in the target folder as does the application config file.
This is the app.config file:
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="backup"
type="OrderConfiguration.BackupConfig, Order.Configuration.Net"/>
<section name="general"
type="OrderConfiguration.GeneralConfig, Order.Configuration.Net"/>
<section name="security"
type="OrderConfiguration.SecurityConfig, Order.Configuration.Net"/>
<-- ** THIS IS LINE 6 **
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
</startup>
<backup configSource="config\backup.config"/>
<general configSource="config\general.config"/>
<security configSource="config\security.config"/>
<connectionStrings>
<clear/>
<add name="OrderDb"
connectionString="Data Source=(local);Initial Catalog=OrbitOrder;
User Id=User;Password=Pass;MultipleActiveResultSets=true;"/>
</connectionStrings>
</configuration>
I also confirm that config\security.config exists in the target folder.
I have spent three hours trying to figure out what the error means as all files actually exist in the target folder. I actually copied the WIX set up from a prior solution that I worked on a year ago and that one works fine without any issues.
The custom action that is failing is trying to encrypt the security configuration section.
I am at a loss to explain why MSI is throwing a 1603 error when there doesn't appear to be anything amiss.
I managed to resolve this after adding the following code to the Wix custom action:
AppDomain.CurrentDomain.AssemblyResolve += ( sender, args ) =>
{
return Assembly.LoadFrom( string.Format( #"{0}Order.Configuration.Net.dll", installFolder ) );
};
This basically says to load the assembly when it encounters a reference that needs resolving.
As per the log, the error is returned by the custom action written by you, so please debug the custom action dll during installation. Easiest method of debugging custom action is to add a message box in the code (begin of custom action) and attach to process in visual studio when the message box is displayed. other way is to use MsiBreak environment variable as described in http://msdn.microsoft.com/en-us/library/aa368264%28v=vs.85%29.aspx

Resources