none
System.NullReferenceException in AppServiceResponse and System.BadImageFormatException of UWP with WPF desktop bridge package RRS feed

  • Question

  • Hello,

    I've followed guide UWP with Desktop Extension and successfully created Part 1"Run WinForms from UWP" and Part 2"Passing parameters", I've checked UWP with both WinForms and WPF in C#, VS19, .NET Framework 4.6.2 on Windows 10 Pro 64-bit OS.

    On this stage I'm trying to implement communication between UWP and WPF or WinForms components in Desktop Bridge package, as it is given in UWP with Desktop Extension – Part 3 lesson, there is a two examples "Scenario 1 – UWP sends request to desktop extension" with read registry key values, and "Scenario 2 – Desktop extension sends request to UWP" to handle requests from desktop code.

    Given example, which is a same to my implementation based on it, consist of WPF side application MainWindow.xaml.cs with MainWindow.xaml and UWP MainPage.xaml.cs with MainPage.xaml and App.xaml, as well as Package.appxmanifest with uap:Extension content in Extensions as shown and adding of System.Runtime.WindowsRuntime.dll and Windows.winmd to WPF and WinForms references. In Package/Applications/ apps WPF  WpfApp1,  launcher Console DesktopExtension and HelloWorld UWP with Set As Entry Point. So, example seems created including all required references and .dll-s, but I can't figure out what causes exception in UWP side MainPage.xaml.cs:

     private async void btnClick_ReadKey(object sender, RoutedEventArgs e)
     {          
          ValueSet request = new ValueSet();
          request.Add("KEY", tbKey.Text);
          AppServiceResponse response = await App.Connection.SendMessageAsync(request);
          tbResult.Text = "";
          foreach (string key in response.Message.Keys)
          {
               tbResult.Text += key + " = " + response.Message[key] + "\r\n";
          }
     }

    with "HKLM\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full" string in MainPage.xaml, which is included into TextBox text:

    <TextBox x:Name="tbKey" Text="HKLM\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full" HorizontalAlignment="Left" Margin="10,10,0,598" Width="306"
     FontSize="10"/>

    or even if I add it as string variable value directly to request.Add("KEY", KeyStr);,   as KeyStr instead of tbKey.Text, anyway, line AppServiceResponse response = await App.Connection.SendMessageAsync(request); throws NullReferenceException:

    Exception User-Unhandled

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

    in Call stack:

       HelloWorld.exe!HelloWorld.MainPage.btnClick_ReadKey(object sender,
     Windows.UI.Xaml.RoutedEventArgs e) Line 148    C# 
        Windows.UI.Xaml.dll![Frames below may be incorrect and/or missing, no
     symbols loaded for Windows.UI.Xaml.dll]    Unknown

    Exception image:

    enter image description here

    My MainPage.xaml:

    <Page
        x:Class="HelloWorld.MainPage"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="using:HelloWorld"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d">
    
        <Grid x:Name="rootGrid" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" Height="640" VerticalAlignment="Top">
            <Button x:Name="btnRegKey" Margin="10,59,0,0" Content="Invoke desktop code to read reg key" IsEnabled="True" Click="btnClick_ReadKey" Height="32" VerticalAlignment="Top"  FontSize="10" Width="306"/>
            <TextBox x:Name="tbKey" Text="HKLM\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full" HorizontalAlignment="Left" Margin="10,10,0,598" Width="306" FontSize="10"/>
            <TextBox x:Name="tbResult" HorizontalAlignment="Left" Margin="10,155,0,453" Text="TextBox" Width="306" AcceptsReturn="True" IsReadOnly="True" FontSize="10" FontFamily="Consolas"/>
            <TextBox x:Name="tbRequests" HorizontalAlignment="Left" Margin="10,107,0,501" Text="Result" Width="306"  AcceptsReturn="True" IsReadOnly="True"/>
        </Grid>
    </Page>

    It looks like, value passed to tbKey.Text, but AppServiceResponse throws exception. I've tried change x:Name="btnRegKey" and x:Name="tbKey" order, as shown in WPF (not UWP) example in answer to What is a NullReferenceException, and how do I fix it?, but result is same. So seems like it is App.Connection problem, not related to the text



    EDIT: ***************************************************************************************************************************

    Here is my UI to better imagine scenario, first I run UWP package with F5, then run WPF or WinForms from UWP, when WPF or WinFroms application runs, requesting to WPF or WinFroms from UWP:

    UI

    Configuration properties:

    Console application launcher DesktopExtension.exe:

     static void Main(string[] args)
        {
            string result = Assembly.GetExecutingAssembly().Location; // determine the package root, based on own location
            int index = result.LastIndexOf("\\");
            string rootPath = $"{result.Substring(0, index)}\\..\\";      
            Process newProcess = null; 
            if (args.Length > 2)
            {              
                switch (args[2])  // launch process based on parameter
                {
                    case "/winforms":
                        newProcess = Process.Start(rootPath + @"WinFormsDesktop\WinFormsDesktop.exe");
                        break;
                    case "/wpf":
                        newProcess = Process.Start(rootPath + @"WpfApp1\WpfApp1.exe");
                        break;
                    case "/parameters":
                        string parameters = ApplicationData.Current.LocalSettings.Values["parameters"] as string;
                        newProcess = Process.Start(rootPath + @"WinFormsDesktop\WinFormsDesktop.exe", parameters);
                        break;
                }
            }
        }

    Packeage.appxmanifest:

    <uap:Extension Category="windows.appService">
      <uap:AppService Name="SampleInteropService" />
    </uap:Extension>
    <deskwindows.fullTrustProcess" Executable="DesktopExtension\DesktopExtension.exe">
      <deskgt;
        <deskWinForms" Parameters="/winforms" />
        <deskWPF" Parameters="/wpf" />
        <deskParameters" Parameters="/parameters" />
      </deskgt;
    </deskgt;

    equal to example App.xaml code:

    public static BackgroundTaskDeferral AppServiceDeferral = null;
    public static AppServiceConnection Connection = null;
    public static event EventHandler AppServiceDisconnected;
    public static event EventHandler<AppServiceTriggerDetails> AppServiceConnected;
    public static bool IsForeground = false;
    
    public App()
    {
        this.InitializeComponent();
        this.Suspending += OnSuspending;
        this.EnteredBackground += App_EnteredBackground;
        this.LeavingBackground += App_LeavingBackground;
    }
    
    private void App_LeavingBackground(object sender, LeavingBackgroundEventArgs e)
    {
        IsForeground = true;
    }
    
    private void App_EnteredBackground(object sender, EnteredBackgroundEventArgs e)
    {
        IsForeground = false;
    }
    
    protected override void OnBackgroundActivated(BackgroundActivatedEventArgs args)
    {
        base.OnBackgroundActivated(args);
    
        if (args.TaskInstance.TriggerDetails is AppServiceTriggerDetails details)
        {
            // only accept connections from callers in the same package
            if (details.CallerPackageFamilyName == Package.Current.Id.FamilyName)
            {
                // connection established from the fulltrust process
                AppServiceDeferral = args.TaskInstance.GetDeferral();
                args.TaskInstance.Canceled += OnTaskCanceled;
    
                Connection = details.AppServiceConnection;
                AppServiceConnected?.Invoke(this, args.TaskInstance.TriggerDetails as AppServiceTriggerDetails);
            }
        }
    }
    
     private void OnTaskCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
    {
        AppServiceDeferral?.Complete();
        AppServiceDeferral = null;
        Connection = null;
        AppServiceDisconnected?.Invoke(this, null);
    }

    Request from UWP to run applications or run with sending of parameters:

    private async void MyButton1_Click_1(object sender, RoutedEventArgs e)
     {
         if (ApiInformation.IsApiContractPresent("Windows.ApplicationModel.FullTrustAppContract", 1, 0))
         {
             await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync("WinForms");
         }
     }
    
    private async void Button_Click_1(object sender, RoutedEventArgs e) // Run Wpf
    {
         if (ApiInformation.IsApiContractPresent("Windows.ApplicationModel.FullTrustAppContract", 1, 0))
         {
              await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync("WPF");
         }
    }
    
    private async void Button_Click(object sender, RoutedEventArgs e) // Pass Params to Wpf
    {
         if (ApiInformation.IsApiContractPresent("Windows.ApplicationModel.FullTrustAppContract", 1, 0))
         {
              ApplicationData.Current.LocalSettings.Values["parameters"] = tbParameters.Text;// store command line parameters in local settings, so the Lancher can retrieve them and pass them on
              await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync("Parameters");
         }
    }
    And getting parameters, GetParameters(); which is same code in WPF and WinForms:
     List<String> parameters = new List<String>();  
        private void GetParameters()
        {
           string[] args = Environment.GetCommandLineArgs();
           if (args.Length > 1)
           {
                 parameters.Clear();
                 for (int i = 1; i < args.Length; i++)
                 {
                    parameters.Add(args[i]);
                 }
           }
           this.textBox1.Text = String.Join(Environment.NewLine, parameters);
        }

    with public class:

    public class ParameterItem
     {
            public string Name { get; set; }
            public string Value { get; set; }
    
            public ParameterItem(string name, string value)
            {
                Name = name;
                Value = value;
            }
     }

    I'm calling from UWP to run WPF or WinForms. Seems like, it is something incorrect in WinForms and WPF:

    WinFroms behavior:

    public Form1()
        {
            InitializeComponent();
            GetParameters();
            // InitializeAppServiceConnection();
        }

    Loads GetParameters(); and successfully receives parameters to the textbox. But does not runs application with InitializeAppServiceConnection(); which direct debug without UWP, throws exception message,

    and I'm not sure, if I should do something with different versions of System.Runtime.WindowsRuntime

    but the System.Runtime.WindowsRuntime.dll from

    C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETCore\v4.5.1\System.Runtime.WindowsRuntime.dll

    is already in apps 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=WinFormsDesktop
      StackTrace:
       at WinFormsDesktop.Form1.<InitializeAppServiceConnection>d__4.MoveNext() in C:\Users\User\Desktop\UWP_B_2\HelloWorld\WinFormsDesktop\Form1.cs:line 46
       at System.Runtime.CompilerServices.AsyncVoidMethodBuilder.Start[TStateMachine](TStateMachine& stateMachine)
       at WinFormsDesktop.Form1.InitializeAppServiceConnection()
       at WinFormsDesktop.Form1..ctor() in C:\Users\User\Desktop\UWP_B_2\HelloWorld\WinFormsDesktop\Form1.cs:line 28
       at WinFormsDesktop.Program.Main() in C:\Users\User\Desktop\UWP_B_2\HelloWorld\WinFormsDesktop\Program.cs:line 19
    Inner Exception 1:
    BadImageFormatException: Cannot load a reference assembly for execution.
    Same WPF behavior:
    public MainWindow()
     {
          InitializeComponent();
          GetParameters();
          //InitializeAppServiceConnection();
     }

    loads application with GetParameters();, receives parameters from UWP.

    With InitializeAppServiceConnection(); I see as console launcher opens and closes, WPF application does not loads. With direct debug, throws same System.BadImageFormatException message:

    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.<InitializeAppServiceConnection>d__4.MoveNext() in C:\Users\User\Desktop\UWP_B_2\HelloWorld\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_B_2\HelloWorld\WpfApp1\MainWindow.xaml.cs:line 37
    Inner Exception 1:
    BadImageFormatException: Cannot load a reference assembly for execution.

    System.BadImageFormatException

    InitializeAppServiceConnection();:

       private async void InitializeAppServiceConnection()
            {
                connection = new AppServiceConnection();
                connection.AppServiceName = "SampleInteropService";
                connection.PackageFamilyName = Package.Current.Id.FamilyName;
                connection.RequestReceived += Connection_RequestReceived;
                connection.ServiceClosed += Connection_ServiceClosed;   
                AppServiceConnectionStatus status = await connection.OpenAsync();
                if (status != AppServiceConnectionStatus.Success)
                {
                    MessageBox.Show(status.ToString());
                    this.IsEnabled = false;
                }
            }

    So, there is no chance to check any desired communication functionality, because AppServiceConnection();

    initialization process works incorrectly.

    I've tried to change target platform in UWP app from default x86 to x64,

    and for all other apps, which is AnyCPU by default, but this produces incompatibility errors.

    Also I've tried Clean projects, as well as build project solution with fresh directory and all included apps from beginning,

    once again, but result is same.

    I'm not sure what I've missed, it is same code from examples.

    Any guide, advice or example would be very helpful











    • Edited by lado_O Thursday, July 11, 2019 12:48 PM
    Saturday, July 6, 2019 2:20 PM

All replies

  • Hello,

    Is I see from your screenshot App.Connection is null, and it is not related to text. For the first you need to configure connection.


    Make the community better together


    Saturday, July 6, 2019 3:06 PM
  • Is I see from your screenshot App.Connection is null, and it is not related to text. For the first you need to configure connection.

    Hello,

    Thank you for your feedback, please specify, what you mean with "configure connection", I think I have completed all the steps of UWP with Desktop Extension – Part 3 lesson. The listed are equal to example code, I've added WPF side application as in MainWindow.xaml.cs with MainWindow.xaml UI and UWP MainPage.xaml.cs with MainPage.xaml, which is equal to this examples. System.Runtime.WindowsRuntime.dll and Windows.winmd added to WPF references. In Package/Applications contains WpfApp1 WPF, HelloWorld UWP with Set As Entry Point Package.appxmanifest includes:

            <desktop:Extension Category="windows.fullTrustProcess" Executable="DesktopExtension\DesktopExtension.exe">

              <desktop:FullTrustProcess>
                <desktop:ParameterGroup GroupId="WinForms" Parameters="/winforms" />
                <desktop:ParameterGroup GroupId="WPF" Parameters="/wpf" />
                <desktop:ParameterGroup GroupId="Parameters" Parameters="/parameters" />
              </desktop:FullTrustProcess>
            </desktop:Extension>

    I'm not sure what I've missed

    • Edited by lado_O Sunday, July 7, 2019 7:54 AM
    Saturday, July 6, 2019 3:26 PM
  • After UWP app started you need to make sure that WPF app is started and connected to UWP app, which ensure  that App.Connection is not null 

    Make the community better together

    Saturday, July 6, 2019 3:48 PM
  • After UWP app started you need to make sure that WPF app is started and connected to UWP app, which ensure  that App.Connection is not null

    I've added EDIT to my question with details and description of running first WPF and WinFroms application from UWP and then request from UWP to WPF or WinFroms. It seems like problem with InitializeAppServiceConnection();, and System.NullReferenceException appears because something goes wrong way with initialization, it is System.BadImageFormatException, but I can't figure out what exactly and how to fix this

    • Edited by lado_O Sunday, July 7, 2019 7:54 AM
    Saturday, July 6, 2019 7:23 PM
  • Hi,

    I'd suggest you to create a more simple demo to reproduce the problem. Could you please create a new blank UWP app and a new WPF app first? Then try to establish app service connection between them like the Stefen's sample. Make sure the basic connection is correct. After that, try to add the codes about passing parameter like the blog said. It should be more clear to locate the problem in this way.

    Best regards,

    Roy


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    Monday, July 8, 2019 5:48 AM
    Moderator
  • I'd suggest you to create a more simple demo to reproduce the problem. Could you please create a new blank UWP app and a new WPF app first? Then try to establish app service connection between them like the Stefen's sample. Make sure the basic connection is correct. After that, try to add the codes about passing parameter like the blog said. It should be more clear to locate the problem in this way.

    Hello,

    I've created new package only with UWP and WPF according only UWP with Desktop Extension – Part 3 with UWP_FullTrust_3.but to check any functionality of this build I have to add code of parameters

    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") as you've suggested, 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);
    } 

    The comment by Stefan Wick MSFT on my question System.BadImageFormatException in UWP with WPF desktop bridge package on  stackoverflow, says:

    "Minimum version needs to be at least 14393 (aka Windows 10 Anniversary Update 1607), Your Target version should match that."

    Default  Minimum Version is Windows 10 (10.0; Build 10586):

    enter image description here

    I'm using Windows 10 Pro 64-bit OS, Version 1803 (OS Build 17134.829), 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 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


    • Edited by lado_O Wednesday, July 10, 2019 10:27 AM
    Tuesday, July 9, 2019 12:03 AM
  • Hi,

    Well, what's your OS version of the device? Could you please change the target version and the min version higher than 14393? 

    Also, I made a sample here myself following the blog. All is working well in my side. I'm targeting 18362 in my project.

    Best regards,

    Roy


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, July 10, 2019 8:04 AM
    Moderator
  • Well, what's your OS version of the device? Could you please change the target version and the min version higher than 14393? 

    Also, I made a sample here myself following the blog. All is working well in my side. I'm targeting 18362 in my project.

    Hi,

    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:

    Targets

    Then 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.







    • Edited by lado_O Thursday, July 11, 2019 12:56 PM
    Wednesday, July 10, 2019 11:41 AM
  • Hi,

    Do you have a sample that could reproduce this? Could you please provide me a simple demo which contains the appservice between UWP app and WPF app inside the demo? Please keep the demo as clean as possible which mean it just contains the appservice communication function in it.

    Best regards,

    Roy


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, July 12, 2019 2:21 AM
    Moderator
  • Do you have a sample that could reproduce this? Could you please provide me a simple demo which contains the appservice between UWP app and WPF app inside the demo? Please keep the demo as clean as possible which mean it just contains the appservice communication function in it.

    Hello,

    In last comment I've added complete project link, which is sample that reproduces described functionality and failure, it is mostly same code, I've provided in this post, but if you're asking for complete test project with actual code as it is, please check UWP_desktop_bridge and appservice connection between UWP app and WPF app inside the demo it is  UWP_desktop_bridge/UWP/App.xaml.cs and UWP_desktop_bridge/UWP/MainPage.xaml.cs  pages in UWP, and  UWP_desktop_bridge/WpfApp1/MainWindow.xaml.cs in WPF, where uncomment of line 38, which is // InitializeAppServiceConnection(); will show you failure

    Thank you







    • Edited by lado_O Friday, July 12, 2019 10:11 AM
    Friday, July 12, 2019 8:26 AM
  • Hi,

    From the sample to see, you are trying to launch a launcher from the UWP app, then the launcher will launch the WPF app.  So it looks like UWP-> Launcher-> WPF and you want to create a appservice directly between UWP and WPF. But the problem is that WPF app is not the fulltrust app that declared in the mainfest. This might cause unknown problems. The best practice for your scenario is to that establish an appservice between UWP and the launcher and then use another way to establish connection between the launcher and WPF. Just keep it the same mode as how you launch them.

    Best regards,

    Roy


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, July 15, 2019 7:41 AM
    Moderator
  • Hello,

    Thank you for your attentive support and sorry for late replay

    Problem with UWP and WPF/WinForms app connection was related to incorrect .dll references in my project. 

    Solution answer given by Stefan Wick MSFT to question described also on on stackoverflow question System.BadImageFormatException in UWP with WPF desktop bridge package on 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




    • Edited by lado_O 5 hours 37 minutes ago
    6 hours 15 minutes ago