System.BadImageFormatException in UWP with WPF desktop bridge package

3

I''ve fully and detailed described problem and question in this topic System.NullReferenceException in AppServiceResponse and System.BadImageFormatException of UWP with WPF desktop bridge package, but still have no found answer, what can cause this failure.

Topic link to Windows Dev Center above describes assembly, shows all used code with examples, including attempts to fix problem, and other details. So I will put only basic part of task in this stackoverflow topic to avoid text overload in post and focus only on System.BadImageFormatException, which provokes App.Connection null in Windows Application Package Project with connection from UWP to WPF application, created according to UWP with Desktop Extension – Part 3 lesson, (sending of request to desktop extension, read registry key values, and sending of request from desktop extension to UWP, handle requests from desktop code).

I've tried fix it different ways (also described above), but can't find any clue of reason, at least to know where to look for problem, maybe I've missed something, but I can't find related useful answers anywhere in internet

This is the message, but the System.Runtime.WindowsRuntime.dll is already in references:

System.BadImageFormatException HResult=0x80131058 Message=Could not load file or assembly 'System.Runtime.WindowsRuntime, Version=4.0.10.0, Culture=neutral, PublicKeyToken=...' or one of its dependencies. Reference assemblies should not be loaded for execution. They can only be loaded in the Reflection-only loader context. (Exception from HRESULT: 0x80131058) Source=WpfApp1
StackTrace: at WpfApp1.MainWindow.d__4.MoveNext() in C:\Users\User\Desktop\UWP\App\WpfApp1\MainWindow.xaml.cs:line 58 at System.Runtime.CompilerServices.AsyncVoidMethodBuilder.Start[TStateMachine](TStateMachine& stateMachine) at WpfApp1.MainWindow.InitializeAppServiceConnection() at WpfApp1.MainWindow..ctor() in C:\Users\User\Desktop\UWP\App\WpfApp1\MainWindow.xaml.cs:line 37 Inner Exception 1: BadImageFormatException: Cannot load a reference assembly for execution.

Any advice, guide or example would be very helpful

EDIT 1: **************************************************************************************************

I've tried all this combinations below two ways Debug and Release, as well as changed Solution platform "compiler settings", from menu bar of VS target from “Any CPU” to “X86 ” and vice-versa as shown in System.BadImageFormatException: Could not load file or assembly [duplicate], and from Solution->Properties->Configuration Properties->Configuration->Project contexts as well as from Project->Properties->Build->Platform target, but functionality and failure equally occurs in all cases:

Current Configuration Properties:

Console Launcher - AnyCPU
UWP - x86
Package - x86
WPF - AnyCPU
WinForms - AnyCPU

Setup all Solution apps to x86:

Console Launcher - x86
UWP - x86
Package - x86
WPF - x86
WinForms - x86

or x64:

Console Launcher - x64
UWP - x64
Package - x64
WPF - x64
WinForms - x64

executes same results by scenario:

Lessons Part 1 "Run WinForms from UWP" and Part 2 "Passing parameters" works successfully, runs application, sends parameters with loading of WPF or WinForms.

Scenarios from lesson Part 3 results with same failure, InitializeAppServiceConnection(); throws System.BadImageFormatException with direct debug, attempt to run WPF or WinForms from UWP, does nothing with requested application, just shows Console Launcher for a second, without any message, and Invoke desktop code to read reg key throws same System.NullReferenceException

Setup all apps to AnyCPU, except UWP, which bin debug output path, as platform targets drop-down menu from solution or app properties includes only x64, x86, ARM, ARM64:

Console Launcher - AnyCPU
UWP - x86 
Package - AnyCPU
WPF - AnyCPU
WinForms - AnyCPU

throws:

Severity Code Description Project File Line Suppression State Error MSB3270 There was a mismatch between the processor architecture of the project being built "x86" and the processor architecture of the reference "C:\Users\User\Desktop\UWP_BD\UWP_BD\Launcher\bin\Debug\Launcher.exe", "AMD64". This mismatch may cause runtime failures. Please consider changing the targeted processor architecture of your project through the Configuration Manager so as to align the processor architectures between your project and references, or take a dependency on references with a processor architecture that matches the targeted processor architecture of your project. Package C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets 2106

and:

Severity Code Description Project File Line Suppression State Warning The element 'PropertyGroup' in namespace 'http://schemas.microsoft.com/developer/msbuild/2003' has invalid child element 'WapProjPath' in namespace 'http://schemas.microsoft.com/developer/msbuild/2003'. List of possible elements expected: 'Property, VisualStudioVersion, MinimumVisualStudioVersion, AdditionalFileItemNames, AllowUnsafeBlocks, AppConfigForCompiler, ApplicationIcon, ApplicationRevision, ApplicationVersion, AppDesignerFolder, AspNetConfiguration, AspNetCoreHostingModel, AspNetCoreModuleName, AssemblyKeyContainerName, AssemblyKeyProviderName, AssemblyName, AssemblyOriginatorKeyFile, AssemblyOriginatorKeyFileType, AssemblyOriginatorKeyMode, AssemblyType, AutoGenerateBindingRedirects, AutorunEnabled, BaseAddress, BootstrapperComponentsLocation, BootstrapperComponentsUrl, BootstrapperEnabled, CharacterSet, CheckForOverflowUnderflow, CLRSupport, UseDebugLibraries, CodePage, Configuration, ConfigurationName, ConfigurationOverrideFile, CreateDesktopShortcut, CreateWebPageOnPublish, CurrentSolutionConfigurationContents, DebugSecurityZoneURL, DebugSymbols, DebugType, DefaultClientScript, DefaultHTMLPageLayout, DefaultTargetSchema, DefineConstants, DefineDebug, DefineTrace, DelaySign, DisableLangXtns, DisallowUrlActivation, CodeAnalysisAd.... Package C:\Users\User\Desktop\UWP_BD\UWP_BD\Package\Package.wapproj 49

and x64:

Console Launcher - AnyCPU
UWP - x64 
Package - AnyCPU
WPF - AnyCPU
WinForms - AnyCPU

Severity Code Description Project File Line Suppression State Error MSB3270 There was a mismatch between the processor architecture of the project being built "MSIL" and the processor architecture of the reference "C:\Users\User\Desktop\UWP_BD\UWP_BD\UWP_Control\bin\x64\Debug\UWP_Control.exe", "AMD64". This mismatch may cause runtime failures. Please consider changing the targeted processor architecture of your project through the Configuration Manager so as to align the processor architectures between your project and references, or take a dependency on references with a processor architecture that matches the targeted processor architecture of your project. Package C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets 2106

I'm not sure, maybe I should change Minimum Version to Anniversary Edition or to Windows 10 (10.0; Build 10214) with creating of UWP which default is Windows 10 (10.0; Build 10586):

enter image description here

EDIT 2: **************************************************************************************************

I'm using Windows 10 Pro 64-bit OS, x64-basesd processor with Visual Studio 2019 Version 16.1.4, Target Framework: .NET Framework 4.7.2 Version 4.7.03056, Microsoft.NETCore.Universal Windows Platform 6.2.8 Path folder C:\Program Files (x86)\Microsoft SDKs\Windows includes folders: v7.0A, v8.1, v8.1A, v10.0A

in .csproj:

 <TargetPlatformVersion Condition=" '$(TargetPlatformVersion)' == '' ">10.0.14393.0</TargetPlatformVersion>
    <TargetPlatformMinVersion>10.0.14393.0</TargetPlatformMinVersion>
    <MinimumVisualStudioVersion>14</MinimumVisualStudioVersion>

I got the same failure System.BadImageFormatException, if I change Minimum Version to Windows 10 Anniversary Edition (10.0; Build 14393) same as for Target Version, with both previous and new assembly without Part 1 and Part 2 code.

Also I've followed Roy Li suggestion in System.NullReferenceException in AppServiceResponse and System.BadImageFormatException of UWP with WPF desktop bridge package on Windows Dev Center, "To create a more simple demo to reproduce the problem". So, I've created new package only with UWP and WPF according only UWP with Desktop Extension – Part 3 with UWP_FullTrust_3.

In previous assembly I have missed SingleInstance.cs in WPF application, but including of this code into previous or new assembly (without "Running app" and "passing parameter"), throws error:

Severity Code Description Project File Line Suppression State Error CS0017 Program has more than one entry point defined. Compile with /main to specify the type that contains the entry point. FullTrust C:\Users\User\Desktop\UWP_BD2\Solution1\FullTrust\SingleInstance.cs 57 Active

on this part of code:

[STAThread]
public static void Main(string[] args)
{
    SingleInstanceManager manager = new SingleInstanceManager();
    manager.Run(args);
} 

EDIT 3: **************************************************************************************************

So, for Windows 10 Pro 64-bit OS, Version 1803 (OS Build 17134.829) suitable Target version should be 17134, I'm not sure about Minimum version:

enter image description here

I've updated Windows just few hours ago. Something goes wrong in Targets menu with creating Windows Application Package Project, or UWP, which does not contains 17134, with higher version, I got this message:

enter image description here

By some reason Target selection menu does not contains 17134 and it is gone for Windows Application Package Project too:

enter image description here

EDIT 4: **************************************************************************************************

I've installed SDK version 17134, and selected 17134 for Target Version with Windows Application Package Project and UWP creation.

I've added code, references, setup, but I got same Error! I'm not sure if I am able to fix it. Maybe complete test project, with actual code will help.

So, here is a full Solution repository UWP_desktop_bridge. It is UWP and Console Launcher to WPF, based on Part 1, Part 2, Part 3 of UWP-FullTrust lesson by Stefan Wick MSFT

Without InitializeAppServiceConnection(); scenarios from Part 1, Part 2 works, but with including InitializeAppServiceConnection(); to WPF InitializeComponent(); to get Part 3 functionality, I got:

System.BadImageFormatException HResult=0x80131058 Message=Could not load file or assembly 'System.Runtime.WindowsRuntime, Version=4.0.10.0, Culture=neutral, PublicKeyToken=...' or one of its dependencies. Reference assemblies should not be loaded for execution. They can only be loaded in the Reflection-only loader context. (Exception from HRESULT: 0x80131058) Source=WpfApp1
StackTrace: at WpfApp1.MainWindow.d__4.MoveNext() in C:\Users\User\Desktop\UWP_desktop-bridge\Solution1\WpfApp1\MainWindow.xaml.cs:line 59 at System.Runtime.CompilerServices.AsyncVoidMethodBuilder.Start[TStateMachine](TStateMachine& stateMachine) at WpfApp1.MainWindow.InitializeAppServiceConnection() at WpfApp1.MainWindow..ctor() in C:\Users\User\Desktop\UWP_desktop-bridge\Solution1\WpfApp1\MainWindow.xaml.cs:line 38 Inner Exception 1: BadImageFormatException: Cannot load a reference assembly for execution.

and same with SingleInstance.cs if using of this part of code:

[STAThread]
public static void Main(string[] args)
{
    SingleInstanceManager manager = new SingleInstanceManager();
    manager.Run(args);
}

Severity Code Description Project File Line Suppression State Error CS0017 Program has more than one entry point defined. Compile with /main to specify the type that contains the entry point.

It is similar functionality and failure as in my previous projects.

EDIT 5: **************************************************************************************************

At this time, I've carefully created copy-paste build, based on ZhuMingHao/AppSerViceTest demo given in answer by Nico Zhu - MSFT on related question Send speech recognition args.Result as parameter in UWP desktop-bridge package:

Debug loads UWP and WPF successfully. With click on the Click button with in UWP AppSerViceTest/AppServiceTest/MainPage.xaml.cs:

I got same exception:

System.NullReferenceException: 'Object reference not set to an instance of an object.

With click on WPF Send Message button, it is just closes WPF app, UWP StatusBlock and InfoBlock shows nothing.

Direct debug of WPF and click Send message button, throws a different content of the same System.BadImageFormatException:

System.BadImageFormatException HResult=0x80131058 Message=Could not load file or assembly 'System.Runtime.WindowsRuntime, Version=4.0.10.0, Culture=neutral, PublicKeyToken=...' or one of its dependencies. Reference assemblies should not be loaded for execution. They can only be loaded in the Reflection-only loader context. (Exception from HRESULT: 0x80131058) Source=WpfApp1 StackTrace:
at WpfApp1.MainWindow.<Button_Click_1>d__5.MoveNext() in C:\Users\User\Desktop\UWP\UWP_DB_SR\WpfApp1\MainWindow.xaml.cs:line 91 at System.Runtime.CompilerServices.AsyncVoidMethodBuilder.Start[TStateMachine](TStateMachine& stateMachine) at WpfApp1.MainWindow.Button_Click_1(Object sender, RoutedEventArgs e) at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs) at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised) at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args) at System.Windows.UIElement.RaiseEvent(RoutedEventArgs e) at System.Windows.Controls.Primitives.ButtonBase.OnClick() at System.Windows.Controls.Button.OnClick() at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e) at System.Windows.UIElement.OnMouseLeftButtonUpThunk(Object sender, MouseButtonEventArgs e) at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget) at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target) at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs) at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised) at System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent) at System.Windows.UIElement.OnMouseUpThunk(Object sender, MouseButtonEventArgs e) at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget) at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target) at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs) at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised) at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args) at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args) at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted) at System.Windows.Input.InputManager.ProcessStagingArea() at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input) at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport) at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel) at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o) at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs) at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler) at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs) at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam) at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg) at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame) at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
at System.Windows.Application.RunDispatcher(Object ignore) at System.Windows.Application.RunInternal(Window window) at System.Windows.Application.Run(Window window) at System.Windows.Application.Run() at WpfApp1.App.Main() Inner Exception 1: BadImageFormatException: Cannot load a reference assembly for execution.

SOLUTION: **************************************************************************************************

Solution answer given by Stefan Wick MSFT to question described also on WDC topic System.NullReferenceException in AppServiceResponse and System.BadImageFormatException of UWP with WPF desktop bridge package on System.BadImageFormatException with particular UWP desktop-bridge app communication project, based on UWP with Desktop Extension – Part 3 example UWP-FullTrust/UWP_FullTrust_3/ as well as solver my copy of Nico Zhu - MSFT solution ZhuMingHao/AppSerViceTest:

My incorrect:

  • Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETCore\v4.5.1\System.Runtime.WindowsRuntime.dll
  • Program Files (x86)\Windows Kits\10\UnionMetadata\Windows.winmd

Must be correct references setup:

  • ProgramFiles(x86)%\Reference Assemblies\Microsoft\Framework.NETCore\v4.5\System.Runtime.WindowsRuntime.dll
  • ProgramFiles(x86)%\Windows Kits\10\UnionMetadata\10.0.17134.0\Windows.winmd
c#
wpf
uwp
desktop-bridge
badimageformatexception
asked on Stack Overflow Jul 7, 2019 by iose936 • edited Jan 7, 2021 by iose936

1 Answer

2

This exception occurs when referencing the Windows Runtime libraries incorrectly from the non-UWP project (WPF, Winforms, Console, etc.). Be sure to reference them as follows

  1. In the "Add Reference …" dialog click "Browse …" and set the filter to "All Files (*.*)"
  2. Navigate to "%ProgramFiles(x86)%\Reference Assemblies\Microsoft\Framework.NETCore\v4.5\System.Runtime.WindowsRuntime.dll"
  3. Navigate to "%ProgramFiles(x86)%\Windows Kits\10\UnionMetadata\{TargetVersion}\Windows.winmd"
answered on Stack Overflow Jul 13, 2019 by Stefan Wick MSFT

User contributions licensed under CC BY-SA 3.0