dotnet / wpf

WPF is a .NET Core UI framework for building Windows desktop applications.
MIT License
7.08k stars 1.17k forks source link

WPF apps, published with dotnet publish with arguments -p:PublishTrimmed=true or /p:IncludeAllContentInSingleFile=true fails to run #3386

Closed Gigas002 closed 2 years ago

Gigas002 commented 4 years ago

Here's a simple pwsh script to create a sample wpf-app and publish it. Some of apps runs (as expected), but some not, they're noted in sript with comments.

dotnet new wpf -o test
Set-Location test

# Runs correctly

dotnet publish -c Release -r win-x64 -o Publish/5/Simple -f net5.0
dotnet publish -c Release -r win-x64 -o Publish/5/Include -f net5.0 /p:IncludeAllContentInSingleFile=true
dotnet publish -c Release -r win-x64 -o Publish/5/R2R -f net5.0 -p:PublishReadyToRun=true
dotnet publish -c Release -r win-x64 -o Publish/5/R2RSingle -f net5.0 -p:PublishReadyToRun=true -p:PublishSingleFile=true
dotnet publish -c Release -r win-x64 -o Publish/5/R2RSingleSelfC -f net5.0 -p:PublishReadyToRun=true -p:PublishSingleFile=true --self-contained true

# Publishes, but not runs

dotnet publish -c Release -r win-x64 -o Publish/5/Trim -f net5.0 -p:PublishTrimmed=true
dotnet publish -c Release -r win-x64 -o Publish/5/R2RSingleSelfCInclude -f net5.0 -p:PublishReadyToRun=true -p:PublishSingleFile=true --self-contained true /p:IncludeAllContentInSingleFile=true
dotnet publish -c Release -r win-x64 -o Publish/5/R2RSingleSelfCTrim -f net5.0 -p:PublishReadyToRun=true -p:PublishSingleFile=true --self-contained true -p:PublishTrimmed=true

Additional info: I must also say, that I've tested this script for netcoreapp3.0 and netcoreapp3.1 (with adding TargetFrameworks to .csproj and removing of /p:IncludeAllContentInSingleFile=true, since it appeared in net5.0) and the app still fails to run in same cases. I've also tested this for dotnet new console (Hello world) app and it seems to run correctly for all cases.

ryalanms commented 4 years ago

Does this repro with the .NET console template as well?

Gigas002 commented 4 years ago

Hmm. Seems like i've overlooked this. I've run the above script for dotnet new console, and the following published .exe fails to run (the others are fine):

dotnet publish -c Release -r win-x64 -o Publish/5/R2RSingle -f net5.0 -p:PublishReadyToRun=true -p:PublishSingleFile=true
dotnet publish -c Release -r win-x64 -o Publish/5/R2RSingleSelfC -f net5.0 -p:PublishReadyToRun=true -p:PublishSingleFile=true --self-contained true
dotnet publish -c Release -r win-x64 -o Publish/5/R2RSingleSelfCInclude -f net5.0 -p:PublishReadyToRun=true -p:PublishSingleFile=true --self-contained true /p:IncludeAllContentInSingleFile=true
dotnet publish -c Release -r win-x64 -o Publish/5/R2RSingleSelfCTrim -f net5.0 -p:PublishReadyToRun=true -p:PublishSingleFile=true --self-contained true -p:PublishTrimmed=true

Throws the following exception:

A fatal error was encountered. The library 'hostpolicy.dll' required to execute the application was not found in 'C:\Program Files\dotnet'.
Failed to run as a self-contained app.
  - The application was run as a self-contained app because 'D:\Downloads\test\Publish\5\R2RSingleSelfCInclude\test.runtimeconfig.json' was not found.
  - If this should be a framework-dependent app, add the 'D:\Downloads\test\Publish\5\R2RSingleSelfCInclude\test.runtimeconfig.json' file and specify the appropriate framework.
wf-soft commented 4 years ago

In .NET 5.0 Preview 8, I had the same problem, and all my nuget packages showed exclamation marks

Fabi commented 4 years ago

WPF apps in the latest preview fail in general for me when I publish them. This issue comes up as soon as you enable single file publish or trimming. Error:

CoreCLR Version: 5.0.20.40711 .NET Version: 5.0.0-preview.8.20407.11 Description: The process was terminated due to an unhandled exception. Exception Info: System.TypeInitializationException: The type initializer for 'System.Windows.Threading.Dispatcher' threw an exception. ---> System.IO.FileNotFoundException: The system cannot find the file specified. (0x80070002) at System.Reflection.RuntimeModule.GetFullyQualifiedName(QCallModule module, StringHandleOnStack retString) at System.Reflection.RuntimeModule.GetFullyQualifiedName() at System.Reflection.RuntimeModule.get_Name() at System.Windows.WpfDllVerifier.VerifyWpfDllSet(String[] additionalDlls) at System.Windows.Threading.Dispatcher..cctor() --- End of inner exception stack trace --- at System.Windows.Threading.Dispatcher.get_CurrentDispatcher() at System.Windows.Threading.DispatcherObject..ctor() at System.Windows.Application..ctor() at Arctium.App.Installer.App..ctor() at Arctium.App.Installer.App.Main()

dpaoliello commented 4 years ago

WPF apps in the latest preview fail in general for me when I publish them. This issue comes up as soon as you enable single file publish or trimming. Error:

CoreCLR Version: 5.0.20.40711 .NET Version: 5.0.0-preview.8.20407.11 Description: The process was terminated due to an unhandled exception. Exception Info: System.TypeInitializationException: The type initializer for 'System.Windows.Threading.Dispatcher' threw an exception. ---> System.IO.FileNotFoundException: The system cannot find the file specified. (0x80070002) at System.Reflection.RuntimeModule.GetFullyQualifiedName(QCallModule module, StringHandleOnStack retString) at System.Reflection.RuntimeModule.GetFullyQualifiedName() at System.Reflection.RuntimeModule.get_Name() at System.Windows.WpfDllVerifier.VerifyWpfDllSet(String[] additionalDlls) at System.Windows.Threading.Dispatcher..cctor() --- End of inner exception stack trace --- at System.Windows.Threading.Dispatcher.get_CurrentDispatcher() at System.Windows.Threading.DispatcherObject..ctor() at System.Windows.Application..ctor() at Arctium.App.Installer.App..ctor() at Arctium.App.Installer.App.Main()

@Fabi Looks like an instance of #3322

dotMorten commented 4 years ago

I'm seeing the same thing with RC1: image

Fabi commented 4 years ago

I'm seeing the same thing with RC1: image

It wasnt merged at the release of RC1. Try https://dotnetcli.blob.core.windows.net/dotnet/Sdk/release/5.0.1xx/dotnet-sdk-latest-win-x64.exe or any other later version than RC1

hez2010 commented 4 years ago

On .NET 5 RC2, PublishTrimmed also leads to crash on startup:

Unhandled exception. System.Windows.Markup.XamlParseException: The type initializer for 'System.Windows.Window' threw an exception.
 ---> System.TypeInitializationException: The type initializer for 'System.Windows.FrameworkElement' threw an exception.
 ---> System.TypeInitializationException: The type initializer for 'System.Windows.Documents.TextElement' threw an exception.
 ---> System.TypeInitializationException: The type initializer for 'System.Windows.Documents.Typography' threw an exception.
 ---> System.IO.FileNotFoundException: Could not load file or assembly 'System.Runtime, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. Cannot find specified file.
File name: 'System.Runtime, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
   at System.Windows.Media.TextFormatting.TextRunTypographyProperties.OnPropertiesChanged()
   at MS.Internal.Text.TypographyProperties.ResetProperties()
   at MS.Internal.Text.TypographyProperties..ctor()
   at System.Windows.Documents.Typography..cctor()
   --- End of inner exception stack trace ---
   at System.Windows.Documents.TextElement..cctor()
   --- End of inner exception stack trace ---
   at System.Windows.FrameworkElement..cctor()
   --- End of inner exception stack trace ---
   at System.Windows.Window..cctor()
   --- End of inner exception stack trace ---
   at System.Windows.Markup.XamlReader.RewrapException(Exception e, IXamlLineInfo lineInfo, Uri baseUri)
   at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
   at System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri)
   at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
   at System.Windows.Application.LoadBamlStreamWithSyncInfo(Stream stream, ParserContext pc)
   at System.Windows.Application.LoadComponent(Uri resourceLocator, Boolean bSkipJournaledProperties)
   at System.Windows.Application.DoStartup()
   at System.Windows.Application.<.ctor>b__1_0(Object unused)
   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.WrappedInvoke(Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.DispatcherOperation.InvokeImpl()
   at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
   at MS.Internal.CulturePreservingExecutionContext.CallbackWrapper(Object obj)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at MS.Internal.CulturePreservingExecutionContext.Run(CulturePreservingExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Windows.Threading.DispatcherOperation.Invoke()
   at System.Windows.Threading.Dispatcher.ProcessQueue()
   at System.Windows.Threading.Dispatcher.WndProcHook(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.WrappedInvoke(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 System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority priority, Delegate method, Object arg)
   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.Threading.Dispatcher.Run()
   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 TrimTest.App.Main()
Fabi commented 4 years ago

On .NET 5 RC2, PublishTrimmed also leads to crash on startup:

Unhandled exception. System.Windows.Markup.XamlParseException: The type initializer for 'System.Windows.Window' threw an exception.
 ---> System.TypeInitializationException: The type initializer for 'System.Windows.FrameworkElement' threw an exception.
 ---> System.TypeInitializationException: The type initializer for 'System.Windows.Documents.TextElement' threw an exception.
 ---> System.TypeInitializationException: The type initializer for 'System.Windows.Documents.Typography' threw an exception.
 ---> System.IO.FileNotFoundException: Could not load file or assembly 'System.Runtime, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. Cannot find specified file.
File name: 'System.Runtime, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
   at System.Windows.Media.TextFormatting.TextRunTypographyProperties.OnPropertiesChanged()
   at MS.Internal.Text.TypographyProperties.ResetProperties()
   at MS.Internal.Text.TypographyProperties..ctor()
   at System.Windows.Documents.Typography..cctor()
   --- End of inner exception stack trace ---
   at System.Windows.Documents.TextElement..cctor()
   --- End of inner exception stack trace ---
   at System.Windows.FrameworkElement..cctor()
   --- End of inner exception stack trace ---
   at System.Windows.Window..cctor()
   --- End of inner exception stack trace ---
   at System.Windows.Markup.XamlReader.RewrapException(Exception e, IXamlLineInfo lineInfo, Uri baseUri)
   at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
   at System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri)
   at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
   at System.Windows.Application.LoadBamlStreamWithSyncInfo(Stream stream, ParserContext pc)
   at System.Windows.Application.LoadComponent(Uri resourceLocator, Boolean bSkipJournaledProperties)
   at System.Windows.Application.DoStartup()
   at System.Windows.Application.<.ctor>b__1_0(Object unused)
   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.WrappedInvoke(Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.DispatcherOperation.InvokeImpl()
   at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
   at MS.Internal.CulturePreservingExecutionContext.CallbackWrapper(Object obj)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at MS.Internal.CulturePreservingExecutionContext.Run(CulturePreservingExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Windows.Threading.DispatcherOperation.Invoke()
   at System.Windows.Threading.Dispatcher.ProcessQueue()
   at System.Windows.Threading.Dispatcher.WndProcHook(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.WrappedInvoke(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 System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority priority, Delegate method, Object arg)
   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.Threading.Dispatcher.Run()
   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 TrimTest.App.Main()

You have to exclude that file from being trimmed.

Wolfteam commented 3 years ago

I got the same problem, my app uses the following in the constructor of the App.xaml.cs file:

    public App()
    {
        ProfileOptimization.SetProfileRoot("TheBasePath");
        ProfileOptimization.StartProfile("Startup.Profile");
    }

ProfileOptimization is inside System.Runtime and for some reason executing the following command: dotnet publish Desktop.csproj -c Release -r win-x64 -p:PublishTrimmed=true removes the System.Runtime dll from the publish folder.

I tried to preserve it by using this attribute [DynamicDependency(DynamicallyAccessedMemberTypes.All, typeof(ProfileOptimization))] but nothing, then I tried using an xml file with the following content:

`

`

and still nothing...

Is there any way I can preserve this thing ? (Disabling trimming is not an option)

Fabi commented 3 years ago

I got the same problem, my app uses the following in the constructor of the App.xaml.cs file:

    public App()
    {
        ProfileOptimization.SetProfileRoot("TheBasePath");
        ProfileOptimization.StartProfile("Startup.Profile");
    }

ProfileOptimization is inside System.Runtime and for some reason executing the following command: dotnet publish Desktop.csproj -c Release -r win-x64 -p:PublishTrimmed=true removes the System.Runtime dll from the publish folder.

I tried to preserve it by using this attribute [DynamicDependency(DynamicallyAccessedMemberTypes.All, typeof(ProfileOptimization))] but nothing, then I tried using an xml file with the following content:

<linker> <assembly fullname="System.Runtime" preserve="all" /> </linker>

and still nothing...

Is there any way I can preserve this thing ? (Disabling trimming is not an option)

as base you use System.Runtime usually but it doesnt hurt do add these 2 others.

    <ItemGroup>
        <TrimmerRootAssembly Include="System.Runtime" />
        <TrimmerRootAssembly Include="System.Diagnostics.Debug" />
        <TrimmerRootAssembly Include="System.Runtime.Extensions" />
    </ItemGroup>

this will make most normal WPF apps to work

ryalanms commented 3 years ago

WPF hasn't done any work to enable trimming. It is not yet supported.

/cc @dotnet/wpf-developers

csujedihy commented 3 years ago

I am hitting exactly the same issue and adding "System.Runtime" to TrimmerRootAssembly didn't work for me.

dotnet --list-sdks 5.0.201 [C:\Program Files\dotnet\sdk]

tapika commented 3 years ago

I have also configured trim like this:

  <Target Name="EnsureAllAssembliesAreLinked" BeforeTargets="PrepareForILLink">
    <ItemGroup>
      <ManagedAssemblyToLink>
        <TrimMode>link</TrimMode>
      </ManagedAssemblyToLink>

      <TrimmerRootAssembly Include="System.Runtime" />
      <TrimmerRootAssembly Include="System.Diagnostics.Debug" />
      <TrimmerRootAssembly Include="System.Runtime.Extensions" />
    </ItemGroup>
  </Target>

but this does not seems to work - removing generic <TrimMode>link</TrimMode> seems to fix the issue.

martin-braun commented 3 years ago

Yes, I can confirm these issues. I had to uncheck trimming in the publishing profile to get rid of these exceptions when launching my published release build.

Screen Shot 2021-11-01 at 20 53 32
singhashish-wpf commented 2 years ago

Trimming support is disabled for wpf apps. See Docs

Fabi commented 2 years ago

Trimming support is disabled for wpf apps. See Docs

Sadly yes. Even tho you are able to get many apps much smaller and running with trimming. Disabling it fully is a no go and prevents us form experimenting with it without hacking around build targets etc.

martin-braun commented 2 years ago

@singhashish-wpf Then disable this option on WPF projects so people don't fall into pits. Thanks.