分享

将 WPF 应用升级到 .NET 7

 兰亭文艺 2023-04-23 发布于加拿大

使用.NET升级助手将 WPF 应用升级到 .NET 7

  • 项目

升级.NET助手是一种命令行工具,可帮助将框架 WPF 应用升级到 .NET.NET 7。 本文将提供:

  • 该工具如何与 WPF 项目配合使用的概述
  • 供你下载和升级的示例应用
  • 故障排除提示

有关如何安装该工具的详细信息,请参阅升级助手概述.NET

提示

升级 .NET 助手正在频繁接收更新。 如果在使用该工具时发现问题,请在工具的 GitHub 存储库中进行报告。

演示应用

可以使用基本 WPF 示例项目来测试通过升级助手进行升级。

分析应用

升级 .NET 助手工具包括一个分析模式,用于执行简化的试运行来升级应用。 它可以提供有关在升级开始之前可能需要进行的更改的见解。 打开终端,导航到目标项目或解决方案所在的文件夹。 运行 upgrade-assistant analyze 命令,传入正在升级的项目或解决方案的名称。

例如,使用基本 WPF 示例应用运行分析模式会产生以下输出,表明在升级之前不会进行任何更改:

控制台
> upgrade-assistant analyze .\WebSiteRatings.sln [15:39:00 INF] Loaded 9 extensions [15:39:02 INF] Using MSBuild from C:\Program Files\dotnet\sdk\7.0.201[15:39:02 INF] Using Visual Studio install from C:\Program Files\Microsoft Visual Studio\2022\Preview [v17] [15:39:05 INF] Writing output to C:\code\migration\AnalysisReport.sarif [15:39:06 INF] Recommending Windows TFM net7.0-windows for project WebSiteRatings.csproj because the project either has Windows-specific dependencies or builds to a WinExe [15:39:06 INF] Marking assembly reference System.Configuration for removal based on package mapping configuration System.Configuration [15:39:06 INF] Adding package System.Configuration.ConfigurationManager based on package mapping configuration System.Configuration [15:39:08 INF] Package EntityFramework, Version=6.2.0 does not support the target(s) net7.0-windows but a newer version (6.4.4) does. [15:39:09 INF] Reference to .NET Upgrade Assistant analyzer package (Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers, version 0.4.410601) needs to be added [15:39:10 INF] Adding Microsoft.Windows.Compatibility 7.0.0 helps with speeding up the upgrade process for Windows-based APIs [15:39:13 INF] Recommending Windows TFM net7.0-windows for project StarVoteControl.csproj because the project either has Windows-specific dependencies or builds to a WinExe [15:39:13 INF] Reference to .NET Upgrade Assistant analyzer package (Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers, version 0.4.410601) needs to be added [15:39:13 INF] Adding Microsoft.Windows.Compatibility 7.0.0 helps with speeding up the upgrade process for Windows-based APIs [15:39:13 INF] Running analyzers on WebSiteRatings [15:39:14 INF] Identified 0 diagnostics in project WebSiteRatings [15:39:14 INF] Running analyzers on StarVoteControl [15:39:15 INF] Identified 0 diagnostics in project StarVoteControl [15:39:15 INF] Analysis Complete, the report is available at C:\code\migration\AnalysisReport.sarif

输出中有很多内部诊断信息,但某些信息非常有用。 请注意,分析模式指示升级建议项目将 net7.0-windows 目标框架名字对象 (TFM) 。 之所以提出此建议,是因为解决方案引用的项目是 WPF 项目,这是一种仅限 Windows 的技术。 控制台应用程序可能会获得直接升级到 TFM net7.0 的建议,除非它使用某些特定于 Windows 的库。

如果报告了任何错误或警告,请在开始升级前处理这些错误或警告。

运行升级助手

打开终端,导航到目标项目或解决方案所在的文件夹。 运行 upgrade-assistant upgrade 命令,传入正在升级的项目或解决方案的名称。

升级包含多个项目的解决方案时,必须选择解决方案中的哪个项目是 入口点。 根据入口点项目,创建一个依赖项关系图,以确定要升级哪些项目以及按何种顺序升级。 如果解决方案包含的项目不属于依赖项关系图,则忽略这些项目,你需要单独升级这些项目。

首先升级依赖项,然后升级 入口点 项目。

使用 基本 WPF 示例 应用升级解决方案文件:

控制台
upgrade-assistant upgrade .\WebSiteRatings.sln

该工具运行并显示它将执行的步骤列表。 完成每个步骤后,该工具将提供一组命令,让用户应用或跳过下一步或其他选项,例如:

  • 获取有关此步骤的详细信息。
  • 更改项目。
  • 调整日志记录设置。
  • 停止升级并退出。

Enter 而不选择数字会选择列表中的第一项。

每个步骤初始化后,如果应用该步骤,它可能会提供有关其认为会发生的情况的信息。 下一步是选择要升级的项目。 应该会看到以下输出:

Upgrade Steps 1. [Next step] Select an entrypoint 2. Select project to upgrade Choose a command: 1. Apply next step (Select an entrypoint) 2. Skip next step (Select an entrypoint) 3. See more step details 4. Configure logging 5. Exit

提示

请注意每个步骤的输出,因为它可能包含有关工具无法升级的内容的信息。 根据应用的复杂性,该工具完成后,可能需要执行更多升级工作。

选择要升级的项目

确定入口点后,下一步是选择要升级的项目。 使用 基本 WPF 示例 应用时,该工具首先确定 StarVoteControl 项目,因为 WebSiteRatings 项目依赖于它。 最好遵循建议的升级路径。

[15:45:52 INF] Applying upgrade step Select project to upgrade
Here is the recommended order to upgrade. Select enter to follow this list, or input the project you want to start with.
   1. StarVoteControl
   2. WebSiteRatings

升级项目

选择项目后,会列出该工具执行的升级步骤列表。 选择第一步,即备份项目。 步骤列表类似于以下代码片段:

[15:50:50 INF] Initializing upgrade step Back up project Upgrade Steps Entrypoint: C:\code\migration\WebSiteRatings\WebSiteRatings.csproj Current Project: C:\code\migration\WebSiteRatings\WebSiteRatings.csproj 1. [Next step] Back up project 2. Convert project file to SDK style 3. Clean up NuGet package references a. Duplicate reference analyzer b. Package map reference analyzer c. Target compatibility reference analyzer d. Upgrade assistant reference analyzer e. Windows Compatibility Pack Analyzer f. MyDotAnalyzer reference analyzer g. Newtonsoft.Json reference analyzer h. Windows App SDK package analysis i. Transitive reference analyzer 4. Update TFM 5. Update NuGet Packages a. Duplicate reference analyzer b. Package map reference analyzer c. Target compatibility reference analyzer d. Upgrade assistant reference analyzer e. Windows Compatibility Pack Analyzer f. MyDotAnalyzer reference analyzer g. Newtonsoft.Json reference analyzer h. Windows App SDK package analysis i. Transitive reference analyzer 6. Add template files 7. Update WCF service to CoreWCF (Preview) 8. Upgrade app config files a. Convert Application Settings b. Convert Connection Strings c. Disable unsupported configuration sections 9. Update source code a. Apply fix for UA0002: Types should be upgraded b. Apply fix for UA0012: 'UnsafeDeserialize()' does not exist 10. Move to next project Choose a command: 1. Apply next step (Back up project) 2. Skip next step (Back up project) 3. See more step details 4. Select different project 5. Configure logging 6. Exit

每个步骤首先详细说明要执行的操作,然后提示你执行此操作。 例如,上一个代码片段位于步骤 1 中。[下一步]备份项目。 跳过任何不适用的步骤。 例如,如果该工具处理 7。将 WCF 服务更新到 CoreWCF (预览版) ,但应用未定义 WCF 服务,会跳过它并处理步骤 8。 反过来,如果步骤 8 不适用,也会跳过它。 当该工具尝试查找适用的下一步时,你可能会看到许多步骤被跳过。

完成升级

升级项目后,该工具会提示你选择依赖项关系图中的下一个项目进行升级。 升级所有项目后,工具会执行“完成升级”步骤,从而完成升级

1. [Next step] Finalize upgrade

Choose a command:
   1. Apply next step (Finalize upgrade)
   2. Skip next step (Finalize upgrade)
   3. See more step details
   4. Configure logging
   5. Exit

升级完成后,迁移的 WPF 项目将类似于以下 XML:

XML
<Project Sdk='Microsoft.NET.Sdk'> <PropertyGroup> <TargetFramework>net7.0-windows</TargetFramework> <OutputType>WinExe</OutputType> <GenerateAssemblyInfo>false</GenerateAssemblyInfo> <UseWPF>true</UseWPF> <ImportWindowsDesktopTargets>true</ImportWindowsDesktopTargets> </PropertyGroup> <ItemGroup> <None Update='sqlite.db'> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </None> </ItemGroup> <ItemGroup> <ProjectReference Include='..\StarVoteControl\StarVoteControl.csproj' /> </ItemGroup> <ItemGroup> <PackageReference Include='System.Data.DataSetExtensions' Version='4.5.0' /> <PackageReference Include='System.Configuration.ConfigurationManager' Version='5.0.0' /> <PackageReference Include='Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers' Version='0.4.410601'> <PrivateAssets>all</PrivateAssets> </PackageReference> <PackageReference Include='EntityFramework' Version='6.4.4' /> </ItemGroup> <ItemGroup> <Service Include='{508349B6-6B84-4DF5-91F0-309BEEBAD82D}' /> </ItemGroup> <ItemGroup> <PackageReference Include='MahApps.Metro' Version='2.4.9' /> <PackageReference Include='Microsoft.Data.Sqlite' Version='1.0.0' /> <PackageReference Include='SQLite' Version='3.12.3' /> </ItemGroup> <ItemGroup> <Content Include='appsettings.json' /> </ItemGroup> </Project>

请注意, .NET 升级助手还会向项目添加分析器,以帮助继续升级过程,例如 Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers NuGet 包。

升级后

升级项目后,需要对其进行编译和测试。 很可能还有更多工作要做才能完成升级。 应用的框架版本可能包含 .NET 项目实际未使用的库引用。 分析每个引用并确定是否需要它。 该工具可能还添加或升级了对错误版本的 NuGet 包引用。

本文发布时,需要以下更新才能完成示例项目的升级:

  • System.Configuration.ConfigurationManager NuGet 包升级到版本 7.0.0

    升级工具选择了错误的版本 (5.0.0):

    XML
    <PackageReference Include='System.Configuration.ConfigurationManager' Version='7.0.0' />
    
  • Microsoft.Data.Sqlite NuGet 包升级到版本 7.0.3

    不需要升级此包。 但是,已选择版本 1.0.0 ,这是直接支持 .NET 框架的最后一个版本,并支持 .NET Standard 1.3。 此包依赖于包 SQLite ,并且当前已弃用。 如果 Microsoft.Data.Sqlite 升级到 7.0.3,则会删除该依赖项,并且项目使用的是受支持的包版本。

    Microsoft.Data.Sqlite 升级到 7.0.3 后,可以从项目中删除包 SQLite

现代化:appsettings.json

.NET 框架使用 App.config 文件加载应用的设置,例如连接字符串和日志记录提供程序。 .NET 现在将 appsettings.json 文件用于应用设置。 升级工具会尽力将设置和连接字符串从 App.config 文件迁移到 appsettings.json 文件,但请确保对其进行比较并验证一切是否正确。

尽管 appsettings.json 是存储和检索设置和连接字符串的新式方式,但代码未使用它,并且仍依赖于 App.config 文件。 App.config文件通过 System.Configuration.ConfigurationManager NuGet 包在 中.NET受支持,NuGet 包提供对 appsettings.json 的支持Microsoft.Extensions.Configuration

当其他库升级到 .NET时,它们通过支持 appsettings.json 而不是 App.config进行现代化。例如,已针对 6+ 升级的.NET框架中的.NET日志记录提供程序不再将App.config用于设置。 你最好遵循其方向,同时避免使用 App.config。

将 appsettings.json 与 WPF 示例应用配合使用

例如,升级 WPF 示例应用后,请删除本地 System.Configuration.ConfigurationManager 数据库使用的连接字符串的依赖项,并转到 appsettings.json

  1. 删除 System.Configuration.ConfigurationManager NuGet 包。

  2. 添加 Microsoft.Extensions.Configuration.Json NuGet 包。

  3. 从项目中删除 App.config 文件。

    在示例应用中,此文件仅包含单个连接字符串,该字符串已由升级工具迁移到 appsettings.json 文件。

  4. 将 appsettings.json 文件设置为复制到输出目录。

    使用“属性”窗格通过 Visual Studio 设置此选项,或直接编辑项目并添加以下 ItemGroup

    XML
    <ItemGroup> <Content Include='appsettings.json'> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> </ItemGroup>
  5. 编辑 App.xaml.cs 文件,设置加载 appsettings.json 文件的配置对象,添加的行突出显示:

    C#
    using System.Windows;
    using Microsoft.Extensions.Configuration;
    
    namespace WebSiteRatings
    {
        /// <summary>
        /// Interaction logic for App.xaml
        /// </summary>
        public partial class App : Application
        {
            public static IConfiguration Config { get; private set; }
    
            public App()
            {
                Config = new ConfigurationBuilder()
                    .AddJsonFile('appsettings.json')
                    .Build();
            }
        }
    }
    
  6. 在 .\Models\Database.cs 文件中,更改 OpenConnection 方法以使用新的 App.Config 属性。 这需要导入 Microsoft.Extensions.Configuration 命名空间:

    C#
    using Microsoft.Data.Sqlite; using System.Collections.Generic; using Microsoft.Extensions.Configuration; namespace WebSiteRatings.Models { internal class Database { public static SqliteConnection OpenConnection() => new SqliteConnection(App.Config.GetConnectionString('database')); // More code below...

    GetConnectionStringMicrosoft.Extensions.Configuration 命名空间提供的扩展方法。

现代化:Web 浏览器控件

WebBrowserWPF 示例应用引用的控件基于 Internet Explorer,它已过期。 WPF 包含 .NET 基于 Microsoft Edge 的新浏览器控件。 完成以下步骤以升级到新的 WebView2 Web 浏览器控件:

  1. 添加 Microsoft.Web.WebView2 NuGet 包。

  2. 在 MainWindow.xaml 文件中:

    1. 将控件导入根元素中的 wpfControls 命名空间:

      XAML
      <mah:MetroWindow x:Class='WebSiteRatings.MainWindow'
              xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
              xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
              xmlns:d='http://schemas.microsoft.com/expression/blend/2008'
              xmlns:mc='http://schemas./markup-compatibility/2006'
              xmlns:mah='clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro'
              xmlns:local='clr-namespace:WebSiteRatings'
              xmlns:vm='clr-namespace:WebSiteRatings.ViewModels'
              xmlns:VoteControl='clr-namespace:StarVoteControl;assembly=StarVoteControl'
              xmlns:wpfControls='clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf'
              Loaded='MetroWindow_Loaded'
              mc:Ignorable='d'
              Title='My Sites' Height='650' Width='1000'>
      
    2. 在声明 <Border> 元素的位置下,删除 WebBrowser 控件并将其替换为 wpfControls:WebView2 控件:

      XAML
      <Border Grid.Row='2' Grid.Column='1' Grid.ColumnSpan='2' BorderThickness='1' BorderBrush='Black' Margin='5'> <wpfControls:WebView2 x:Name='browser' ScrollViewer.CanContentScroll='True' /> </Border>
  3. 编辑 MainWindow.xaml.cs 代码隐藏文件。 更新 ListBox_SelectionChanged 方法以将 browser.Source 属性设置为有效的 Uri。 此代码以前作为字符串传入网站 URL,但控件 WebView2 需要 Uri

    C#
    private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var siteCollection = (ViewModels.SiteCollection)DataContext;
    
        if (siteCollection.SelectedSite != null)
            browser.Source = new Uri(siteCollection.SelectedSite.Url);
        else
            browser.NavigateToString('<body></body>');
    }
    

根据你的应用的用户运行的 Windows 版本,他们可能需要安装 WebView2 运行时。 有关详细信息,请参阅 WPF 应用中的 WebView2 入门

Visual Basic 项目

如果使用 Visual Basic 对项目进行编码,升级助手可能包含额外的步骤,例如迁移 My 命名空间。 当你的项目使用这些功能时,你应该只会看到添加的这些步骤。

7. Update Visual Basic project a. Update vbproj to support 'My.' namespace

另请参阅

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多