diff --git a/website/docs/doc/GeneralUpdate.Bowl.md b/website/docs/doc/GeneralUpdate.Bowl.md index 6cfe08b..de44ec6 100644 --- a/website/docs/doc/GeneralUpdate.Bowl.md +++ b/website/docs/doc/GeneralUpdate.Bowl.md @@ -2,73 +2,223 @@ sidebar_position: 3 --- -### Definition +# GeneralUpdate.Bowl -Namespace: GeneralUpdate.Bowl +## 组件概览 -Assembly: GeneralUpdate.Bowl.dll +**GeneralUpdate.Bowl** 是一个独立的进程监控组件,在升级流程结束前启动,负责启动主客户端应用程序并监控其运行状态。该组件提供了完整的崩溃监控和诊断能力,当被监控的应用程序发生异常时,会自动导出Dump文件、驱动信息、系统信息和事件日志,帮助开发者快速定位问题。 -This component is an independent process launched before the end of the upgrade process. It starts the main client application and monitors its normal operation before the process ends. +**命名空间:** `GeneralUpdate.Bowl` +**程序集:** `GeneralUpdate.Bowl.dll` -```c# +```csharp public sealed class Bowl ``` +--- + +## 核心特性 + +### 1. 进程监控 +- 实时监控目标应用程序的运行状态 +- 自动检测进程崩溃和异常退出 + +### 2. 崩溃诊断 +- 自动生成Dump文件(.dmp)用于崩溃分析 +- 导出详细的系统和驱动信息 +- 收集Windows系统事件日志 + +### 3. 版本化管理 +- 按版本号分类存储故障信息 +- 支持升级和正常两种工作模式 + +--- +## 快速开始 -### Example +### 安装 -The following example defines a method that includes the use of Bowl. +通过 NuGet 安装 GeneralUpdate.Bowl: + +```bash +dotnet add package GeneralUpdate.Bowl +``` + +### 初始化与使用 + +以下示例展示了如何使用 Bowl 组件监控应用程序: + +```csharp +using GeneralUpdate.Bowl; +using GeneralUpdate.Bowl.Strategys; -```c# var installPath = AppDomain.CurrentDomain.BaseDirectory; var lastVersion = "1.0.0.3"; var processInfo = new MonitorParameter { - ProcessNameOrId = "JsonTest.exe", + ProcessNameOrId = "YourApp.exe", DumpFileName = $"{lastVersion}_fail.dmp", FailFileName = $"{lastVersion}_fail.json", TargetPath = installPath, FailDirectory = Path.Combine(installPath, "fail", lastVersion), BackupDirectory = Path.Combine(installPath, lastVersion), - WorkModel = "Normal" + WorkModel = "Normal" // 使用 Normal 模式独立监控 }; Bowl.Launch(processInfo); ``` -### Capture +--- + +## 核心 API 参考 + +### Launch 方法 + +启动进程监控功能。 + +**方法签名:** + +```csharp +public static void Launch(MonitorParameter? monitorParameter = null) +``` + +**参数:** + +#### MonitorParameter 类 -If a crash is detected, the following files will be generated in the running directory: +```csharp +public class MonitorParameter +{ + /// + /// 被监控的目录 + /// + public string TargetPath { get; set; } + + /// + /// 导出异常信息的目录 + /// + public string FailDirectory { get; set; } + + /// + /// 备份目录 + /// + public string BackupDirectory { get; set; } + + /// + /// 被监控进程的名称或ID + /// + public string ProcessNameOrId { get; set; } + + /// + /// Dump 文件名 + /// + public string DumpFileName { get; set; } + + /// + /// 升级包版本信息(.json)文件名 + /// + public string FailFileName { get; set; } -- 📒 Dump file (1.0.0.*_fail.dmp) -- 📒 Upgrade package version information (1.0.0.*_fail.json) -- 📒 Driver information (driverInfo.txt) -- 📒 Operating system/hardware information (systeminfo.txt) -- 📒 System event log (systemlog.evtx) + /// + /// 工作模式: + /// - Upgrade: 升级模式,主要用于与 GeneralUpdate 配合使用,内部逻辑处理,默认模式启动时请勿随意修改 + /// - Normal: 正常模式,可独立使用监控单个程序,程序崩溃时导出崩溃信息 + /// + public string WorkModel { get; set; } = "Upgrade"; +} +``` -These will be exported to the "fail" directory, categorized by version number. +--- -![](imgs\crash.jpg) +## 实际使用示例 -#### (1) x.0.0.*_fail.dmp +### 示例 1:独立模式监控应用 -![](imgs\dump.png) +```csharp +using GeneralUpdate.Bowl; +using GeneralUpdate.Bowl.Strategys; -#### (2) x.0.0.*_fail.json +// 配置监控参数 +var installPath = AppDomain.CurrentDomain.BaseDirectory; +var currentVersion = "1.0.0.5"; + +var monitorConfig = new MonitorParameter +{ + ProcessNameOrId = "MyApplication.exe", + DumpFileName = $"{currentVersion}_crash.dmp", + FailFileName = $"{currentVersion}_crash.json", + TargetPath = installPath, + FailDirectory = Path.Combine(installPath, "crash_reports", currentVersion), + BackupDirectory = Path.Combine(installPath, "backups", currentVersion), + WorkModel = "Normal" // 独立监控模式 +}; + +// 启动监控 +Bowl.Launch(monitorConfig); +``` + +### 示例 2:结合 GeneralUpdate 使用 + +```csharp +using GeneralUpdate.Bowl; +using GeneralUpdate.Bowl.Strategys; + +// 在升级完成后启动 Bowl 监控 +var installPath = AppDomain.CurrentDomain.BaseDirectory; +var upgradedVersion = "2.0.0.1"; + +var upgradeMonitor = new MonitorParameter +{ + ProcessNameOrId = "UpdatedApp.exe", + DumpFileName = $"{upgradedVersion}_fail.dmp", + FailFileName = $"{upgradedVersion}_fail.json", + TargetPath = installPath, + FailDirectory = Path.Combine(installPath, "fail", upgradedVersion), + BackupDirectory = Path.Combine(installPath, upgradedVersion), + WorkModel = "Upgrade" // 升级模式 +}; + +Bowl.Launch(upgradeMonitor); +``` + +--- + +## 崩溃信息捕获 + +当检测到崩溃时,以下文件将在运行目录中生成: + +- 📒 **Dump 文件** (`x.0.0.*_fail.dmp`) +- 📒 **升级包版本信息** (`x.0.0.*_fail.json`) +- 📒 **驱动信息** (`driverInfo.txt`) +- 📒 **操作系统/硬件信息** (`systeminfo.txt`) +- 📒 **系统事件日志** (`systemlog.evtx`) + +这些文件将按版本号分类导出到 "fail" 目录中。 + +![崩溃文件](imgs/crash.jpg) + +### 1. Dump 文件 + +Dump 文件包含崩溃时刻的内存快照,可用于调试分析: + +![Dump文件](imgs/dump.png) + +### 2. 版本信息文件 + +JSON 格式的详细崩溃报告,包含参数配置和 ProcDump 输出: ```json { - "Parameter": { - "TargetPath": "D:\\github_project\\GeneralUpdate\\src\\c#\\Generalupdate.CatBowl\\bin\\Debug\\net9.0\\", - "FailDirectory": "D:\\github_project\\GeneralUpdate\\src\\c#\\Generalupdate.CatBowl\\bin\\Debug\\net9.0\\fail\\1.0.0.3", - "BackupDirectory": "D:\\github_project\\GeneralUpdate\\src\\c#\\Generalupdate.CatBowl\\bin\\Debug\\net9.0\\1.0.0.3", - "ProcessNameOrId": "JsonTest.exe", - "DumpFileName": "1.0.0.3_fail.dmp", - "FailFileName": "1.0.0.3_fail.json", - "WorkModel": "Normal", - "ExtendedField": null - }, - "ProcdumpOutPutLines": [ +"Parameter": { +"TargetPath": "D:\\github_project\\GeneralUpdate\\src\\c#\\Generalupdate.CatBowl\\bin\\Debug\\net9.0\\", +"FailDirectory": "D:\\github_project\\GeneralUpdate\\src\\c#\\Generalupdate.CatBowl\\bin\\Debug\\net9.0\\fail\\1.0.0.3", +"BackupDirectory": "D:\\github_project\\GeneralUpdate\\src\\c#\\Generalupdate.CatBowl\\bin\\Debug\\net9.0\\1.0.0.3", +"ProcessNameOrId": "JsonTest.exe", +"DumpFileName": "1.0.0.3_fail.dmp", +"FailFileName": "1.0.0.3_fail.json", +"WorkModel": "Normal", +"ExtendedField": null +}, +"ProcdumpOutPutLines": [ "ProcDump v11.0 - Sysinternals process dump utility", "Copyright (C) 2009-2022 Mark Russinovich and Andrew Richards", "Sysinternals - www.sysinternals.com", @@ -96,147 +246,83 @@ These will be exported to the "fail" directory, categorized by version number. } ``` -#### (3) driverInfo.txt +### 3. 驱动信息文件 -```json -Module Name Display Name Description Driver Type Start Mode State Status Accept Stop Accept Pause Paged Pool Code(Bytes) BSS(Bytes) Link Date Path Init(Bytes) -============ ====================== ====================== ============= ========== ========== ========== =========== ============ ========== ========== ======= ====================== ================================================ ========== -360AntiAttac 360Safe Anti Attack Se 360Safe Anti Attack Se Kernel System Running OK TRUE FALSE 4,096 36,864 0 9/29/2022 3:45:03 PM C:\Windows\system32\Drivers\360AntiAttack64.sys 4,096 -360AntiHacke 360Safe Anti Hacker Se 360Safe Anti Hacker Se Kernel System Running OK TRUE FALSE 4,096 139,264 0 11/27/2023 3:43:37 PM C:\Windows\system32\Drivers\360AntiHacker64.sys 8,192 -360AntiHijac 360Safe Anti Hijack Se 360Safe Anti Hijack Se Kernel System Running OK TRUE FALSE 4,096 73,728 0 5/8/2024 12:19:52 PM C:\Windows\system32\Drivers\360AntiHijack64.sys 4,096 -360AntiSteal 360Safe Anti Steal Fil 360Safe Anti Steal Fil Kernel System Running OK TRUE FALSE 4,096 20,480 0 4/18/2024 3:58:04 PM C:\Windows\system32\Drivers\360AntiSteal64.sys 8,192 -360Box64 360Box mini-filter dri 360Box mini-filter dri File System System Running OK TRUE FALSE 0 225,280 0 8/7/2024 11:50:19 AM C:\Windows\system32\DRIVERS\360Box64.sys 12,288 - -//... +包含系统中所有驱动程序的详细信息: + +```text +Module Name Display Name Description Driver Type Start Mode State Status +============ ====================== ====================== ============= ========== ========== ========== +360AntiAttac 360Safe Anti Attack Se 360Safe Anti Attack Se Kernel System Running OK +360AntiHacke 360Safe Anti Hacker Se 360Safe Anti Hacker Se Kernel System Running OK +// ...更多驱动信息 ``` -#### (4) systeminfo.txt +### 4. 系统信息文件 -```json +完整的操作系统和硬件配置信息: + +```text Host Name: **** -OS Name: Microsoft Windows 11 Pro -OS Version: 10.0.2*** Build 22*** -OS Manufacturer: Microsoft Corporation -OS Configuration: Standalone Workstation -OS Build Type: Multiprocessor Free -Registered Owner: ****@outlook.com -Registered Organization: -Product ID: ****-80000-***00-A**** -Original Install Date: 11/16/2023, 9:56:28 PM -System Boot Time: 11/26/2024, 9:37:51 PM -System Manufacturer: ASUS -System Model: System Product Name -System Type: x64-based PC -Processor(s): Installed 1 Processor(s). - [01]: Intel** Family * Model *** Stepping * GenuineIntel ~**** Mhz -BIOS Version: American Megatrends Inc. 1402, 4/1/2022 -Windows Directory: C:\Windows -System Directory: C:\Windows\system32 -Boot Device: \Device\Ha*****olume1 -System Locale: zh-cn;Chinese (China) -Input Locale: zh-cn;Chinese (China) -Time Zone: (UTC+08:00) **,**,*******,**** -Total Physical Memory: 16,194 MB -Available Physical Memory: 1,795 MB -Virtual Memory: Max Size: 25,410 MB -Virtual Memory: Available: 9,438 MB -Virtual Memory: In Use: 15,972 MB -Page File Location(s): D:\****file.sys -Domain: WORKGROUP -Logon Server: \\**** -Hotfix(s):: 6 Hotfix(s) Installed. - [01]: KB504**** - [02]: KB502**** - [03]: KB503**** - [04]: KB503**** - [05]: KB504**** - [06]: KB504**** -Network Card(s): 3 NIC(s) Installed. - [01]: Intel(R) Ethernet Connection (**) I***-V - Connection Name: Ethernet - DHCP Enabled: Yes - DHCP Server: 192.168.**.** - IP Address - [01]: 192.168.**.** - [02]: ***::2640:***:****:**** - [02]: VMware Virtual Ethernet Adapter for VMnet1 - Connection Name: VMware Network Adapter VMnet1 - DHCP Enabled: Yes - DHCP Server: 192.168.**.** - IP Address - [01]: 192.168.**.** - [02]: ***::9b3:***,***:**** - [03]: VMware Virtual Ethernet Adapter for VMnet8 - Connection Name: VMware Network Adapter VMnet8 - DHCP Enabled: Yes - DHCP Server: 192.168.**.** - IP Address - [01]: 192.***,***:**** - [02]: fe80::***:***:***:**** -Hyper-V Requirements: A hypervisor has been detected. Features required for Hyper-V will not be displayed. - -//... +OS Name: Microsoft Windows 11 Pro +OS Version: 10.0.*** Build 22*** +System Manufacturer: ASUS +System Model: System Product Name +Processor(s): Intel** Family * Model *** +Total Physical Memory: 16,194 MB +// ...更多系统信息 ``` -#### (5) systemlog.evtx +### 5. 系统事件日志 -![](imgs\evtx.png) +Windows 事件查看器格式的系统日志(.evtx 文件): -### Notes +![系统事件日志](imgs/evtx.png) -Bowl provides runtime monitoring capabilities and exports relevant error information. +--- -#### Methods +## 注意事项与警告 -| Method | Description | -| -------- | ---------------- | -| Launch() | Start monitoring | +### ⚠️ 重要提示 -### 🌼Launch() +1. **工作模式选择** + - `Upgrade` 模式:专门用于与 GeneralUpdate 框架集成,包含内部逻辑处理 + - `Normal` 模式:可独立使用,适合监控任何 .NET 应用程序 -**Launch Function** +2. **权限要求** + - Bowl 需要足够的权限来生成 Dump 文件和读取系统信息 + - 建议以管理员权限运行需要监控的应用程序 -```c# -Launch(MonitorParameter? monitorParameter = null); -``` +3. **磁盘空间** + - Dump 文件可能占用大量磁盘空间(通常 50-200 MB) + - 确保 FailDirectory 所在磁盘有足够的可用空间 -**Parameters** +4. **依赖项** + - Bowl 使用 ProcDump 工具生成 Dump 文件,该工具已内置在组件中 + - 无需额外安装依赖项 -```c# -public class MonitorParameter -{ - // Directory being monitored - public string TargetPath { get; set; } - - // Directory where captured exception information is exported - public string FailDirectory { get; set; } - - // Backup directory - public string BackupDirectory { get; set; } - - // Name or ID of the process being monitored - public string ProcessNameOrId { get; set; } - - // Dump file name - public string DumpFileName { get; set; } - - // Upgrade package version information (.json) file name - public string FailFileName { get; set; } +### 💡 最佳实践 - /// - /// Upgrade: upgrade mode. This mode is primarily used in conjunction with GeneralUpdate for internal use. Please do not modify it arbitrarily when the default mode is activated. - /// Normal: Normal mode, This mode can be used independently to monitor a single program. If the program crashes, it will export the crash information. - /// - public string WorkModel { get; set; } = "Upgrade"; -} -``` +- **版本号管理**:为每个版本使用独立的故障目录,便于问题追踪 +- **日志清理**:定期清理旧版本的故障信息,避免磁盘空间耗尽 +- **测试验证**:在生产环境部署前,在测试环境验证监控功能 + +--- + +## 适用平台 + +| 产品 | 版本 | +| --------------- | ----------------- | +| .NET | 5, 6, 7, 8, 9 | +| .NET Framework | 4.6.1 | +| .NET Standard | 2.0 | +| .NET Core | 2.0 | +| ASP.NET | Any | + +--- -### Applicable To +## 相关资源 -| Product | Version | -| -------------- | ------------- | -| .NET | 5, 6, 7, 8, 9 | -| .NET Framework | 4.6.1 | -| .NET Standard | 2.0 | -| .NET Core | 2.0 | -| ASP.NET | Any | \ No newline at end of file +- **示例代码**:[查看 GitHub 示例](https://github.com/GeneralLibrary/GeneralUpdate-Samples/tree/main/src/Bowl) +- **视频教程**:[观看 Bilibili 教程](https://www.bilibili.com/video/BV1c8iyYZE7P) +- **主仓库**:[GeneralUpdate 项目](https://github.com/GeneralLibrary/GeneralUpdate) diff --git a/website/docs/doc/GeneralUpdate.ClientCore.md b/website/docs/doc/GeneralUpdate.ClientCore.md index 5a9a29f..deb4ec3 100644 --- a/website/docs/doc/GeneralUpdate.ClientCore.md +++ b/website/docs/doc/GeneralUpdate.ClientCore.md @@ -2,129 +2,603 @@ sidebar_position: 4 --- -### Definition +# GeneralUpdate.ClientCore -Namespace: GeneralUpdate.ClientCore +## 组件概览 -Assembly: GeneralUpdate.ClientCore.dll +**GeneralUpdate.ClientCore** 是 GeneralUpdate 框架的核心组件之一,提供了丰富的客户端更新功能。该组件运行在主应用程序中,负责检查更新、下载更新包、验证完整性,并在完成后启动升级助手(GeneralUpdate.Core)来执行实际的文件替换操作。ClientCore 的设计理念是让主程序能够安全地检查和准备更新,而不影响当前运行状态。 +**命名空间:** `GeneralUpdate.ClientCore` +**程序集:** `GeneralUpdate.ClientCore.dll` +```csharp +public class GeneralClientBootstrap : AbstractBootstrap +``` + +--- -GeneralUpdate.ClientCore is one of the core components, offering a wide range of primary functionalities. Its essence is similar to Core, but it has a different role: ClientCore is used in the main program, where it assists in updates and upgrades and then closes the main program to launch the upgrade assistant. +## 核心特性 -```c# -public class GeneralClientBootstrap : AbstractBootstrap +### 1. 多版本下载管理 +- 支持同时下载多个版本的更新包 +- 断点续传和下载速度限制 +- 实时下载进度和统计信息 + +### 2. 灵活的配置选项 +- 黑名单机制(文件、格式、目录) +- 自定义更新策略和操作 +- 支持二进制差异更新和全量更新 + +### 3. 完整的事件通知 +- 下载进度、完成、错误事件 +- 支持用户自定义跳过更新选项 +- 异常和错误全程监控 + +### 4. 多平台支持 +- Windows、Linux、macOS 平台支持 +- 自动平台检测和策略选择 + +![Multi Download](imgs/muti_donwload.png) + +--- + +## 快速开始 + +### 安装 + +通过 NuGet 安装 GeneralUpdate.ClientCore: + +```bash +dotnet add package GeneralUpdate.ClientCore +``` + +### 初始化与使用 + +以下示例展示了如何在主程序中配置和启动更新检查: + +```csharp +using System.Text; +using GeneralUpdate.ClientCore; +using GeneralUpdate.Common.Download; +using GeneralUpdate.Common.Internal; +using GeneralUpdate.Common.Internal.Bootstrap; +using GeneralUpdate.Common.Shared.Object; + +try +{ + Console.WriteLine($"主程序初始化,{DateTime.Now}!"); + + // 配置更新参数 + var configinfo = new Configinfo + { + // 更新验证 API 地址 + UpdateUrl = "http://127.0.0.1:5000/Upgrade/Verification", + // 更新报告 API 地址 + ReportUrl = "http://127.0.0.1:5000/Upgrade/Report", + // 主应用程序名称 + MainAppName = "ClientSample.exe", + // 升级程序名称 + AppName = "UpgradeSample.exe", + // 当前客户端版本 + ClientVersion = "1.0.0.0", + // 升级端版本 + UpgradeClientVersion = "1.0.0.0", + // 安装路径 + InstallPath = Thread.GetDomain().BaseDirectory, + // 产品 ID(用于多产品分支管理) + ProductId = "2d974e2a-31e6-4887-9bb1-b4689e98c77a", + // 应用密钥(用于服务器验证) + AppSecretKey = "dfeb5833-975e-4afb-88f1-6278ee9aeff6" + }; + + // 启动更新流程 + await new GeneralClientBootstrap() + // 监听下载统计信息 + .AddListenerMultiDownloadStatistics(OnMultiDownloadStatistics) + // 监听单个下载完成 + .AddListenerMultiDownloadCompleted(OnMultiDownloadCompleted) + // 监听所有下载完成 + .AddListenerMultiAllDownloadCompleted(OnMultiAllDownloadCompleted) + // 监听下载错误 + .AddListenerMultiDownloadError(OnMultiDownloadError) + // 监听异常 + .AddListenerException(OnException) + // 设置配置 + .SetConfig(configinfo) + // 设置选项 + .Option(UpdateOption.DownloadTimeOut, 60) + .Option(UpdateOption.Encoding, Encoding.Default) + // 启动异步更新 + .LaunchAsync(); + + Console.WriteLine($"主程序已启动,{DateTime.Now}!"); +} +catch (Exception e) +{ + Console.WriteLine(e.Message + "\n" + e.StackTrace); +} + +// 事件处理方法 +void OnMultiDownloadStatistics(object arg1, MultiDownloadStatisticsEventArgs arg2) +{ + var version = arg2.Version as VersionInfo; + Console.WriteLine($"下载版本:{version.Version},速度:{arg2.Speed}," + + $"剩余时间:{arg2.Remaining},进度:{arg2.ProgressPercentage}%"); +} + +void OnMultiDownloadCompleted(object arg1, MultiDownloadCompletedEventArgs arg2) +{ + var version = arg2.Version as VersionInfo; + Console.WriteLine(arg2.IsComplated ? + $"版本 {version.Version} 下载完成!" : + $"版本 {version.Version} 下载失败!"); +} + +void OnMultiAllDownloadCompleted(object arg1, MultiAllDownloadCompletedEventArgs arg2) +{ + Console.WriteLine(arg2.IsAllDownloadCompleted ? + "所有下载任务已完成!" : + $"下载任务失败!失败数量:{arg2.FailedVersions.Count}"); +} + +void OnMultiDownloadError(object arg1, MultiDownloadErrorEventArgs arg2) +{ + var version = arg2.Version as VersionInfo; + Console.WriteLine($"版本 {version.Version} 下载错误:{arg2.Exception}"); +} + +void OnException(object arg1, ExceptionEventArgs arg2) +{ + Console.WriteLine($"更新异常:{arg2.Exception}"); +} +``` + +--- + +## 核心 API 参考 + +### GeneralClientBootstrap 类方法 + +#### LaunchAsync 方法 + +异步启动更新流程。 + +```csharp +public async Task LaunchAsync() +``` + +#### SetConfig 方法 + +设置更新配置信息。 + +```csharp +public GeneralClientBootstrap SetConfig(Configinfo configinfo) +``` + +#### Option 方法 + +设置更新选项。 + +```csharp +public GeneralClientBootstrap Option(UpdateOption option, object value) +``` + +#### SetBlacklist 方法 + +设置更新黑名单,指定不需要更新的文件。 + +```csharp +public GeneralClientBootstrap SetBlacklist(List blackFiles = null, + List blackFormats = null) +``` + +#### AddListenerMultiDownloadStatistics 方法 + +监听下载统计信息(速度、进度、剩余时间等)。 + +```csharp +public GeneralClientBootstrap AddListenerMultiDownloadStatistics( + Action callbackAction) +``` + +#### AddListenerMultiDownloadCompleted 方法 + +监听单个更新包下载完成事件。 + +```csharp +public GeneralClientBootstrap AddListenerMultiDownloadCompleted( + Action callbackAction) ``` +#### AddListenerMultiAllDownloadCompleted 方法 +监听所有下载任务完成事件。 -### Example +```csharp +public GeneralClientBootstrap AddListenerMultiAllDownloadCompleted( + Action callbackAction) +``` + +#### AddListenerMultiDownloadError 方法 -GeneralClientBootstrap uses code examples [[View]](https://github.com/GeneralLibrary/GeneralUpdate-Samples/blob/main/src/Client/Program.cs)。 +监听下载错误事件。 -![](imgs/muti_donwload.png) +```csharp +public GeneralClientBootstrap AddListenerMultiDownloadError( + Action callbackAction) +``` + +#### AddListenerException 方法 + +监听更新过程中的所有异常。 + +```csharp +public GeneralClientBootstrap AddListenerException( + Action callbackAction) +``` + +#### AddCustomOption 方法 + +添加自定义异步操作,可在更新前后执行自定义逻辑。 + +```csharp +public GeneralClientBootstrap AddCustomOption(Func customFunc) +``` + +#### SetCustomSkipOption 方法 + +设置自定义跳过选项,允许用户决定是否继续更新。 + +```csharp +public GeneralClientBootstrap SetCustomSkipOption(Func customSkipFunc) +``` + +--- + +## 配置类详解 + +### Configinfo 类 + +```csharp +public class Configinfo +{ + /// + /// 更新检查 API 地址 + /// + public string UpdateUrl { get; set; } + + /// + /// 更新状态报告 API 地址 + /// + public string ReportUrl { get; set; } + + /// + /// 需要启动的应用程序名称(升级程序) + /// + public string AppName { get; set; } + + /// + /// 需要启动的主应用程序名称 + /// + public string MainAppName { get; set; } + + /// + /// 更新日志网页地址 + /// + public string UpdateLogUrl { get; set; } + + /// + /// 应用密钥,与服务器约定用于身份验证和产品分支 + /// + public string AppSecretKey { get; set; } + + /// + /// 当前客户端版本号 + /// + public string ClientVersion { get; set; } + + /// + /// 当前升级客户端版本号 + /// + public string UpgradeClientVersion { get; set; } + + /// + /// 安装路径(用于更新文件逻辑) + /// + public string InstallPath { get; set; } + + /// + /// 黑名单文件列表,这些文件在更新时会被跳过 + /// + public List BlackFiles { get; set; } + + /// + /// 黑名单文件格式列表,这些格式的文件在更新时会被跳过 + /// + public List BlackFormats { get; set; } + + /// + /// 需要跳过的目录路径列表,这些目录不需要更新 + /// + public List SkipDirectorys { get; set; } + + /// + /// 当前产品分支的唯一 ID + /// + public string ProductId { get; set; } + + /// + /// Bowl 监控进程路径,更新完成后启动 Bowl 检查客户端是否正常启动 + /// + public string Bowl { get; set; } + + /// + /// HTTP 请求中用于传递 token 的 Scheme(如 Bearer) + /// + public string Scheme { get; set; } + + /// + /// HTTP 请求中用于身份验证的 Token + /// + public string Token { get; set; } + + /// + /// Linux 平台下的脚本,用于在更新完成后为文件分配权限 + /// + public string Script { get; set; } +} +``` + +### UpdateOption 枚举 + +```csharp +public enum UpdateOption +{ + /// + /// 更新包文件格式(默认为 Zip) + /// + Format, + + /// + /// 压缩编码格式 + /// + Encoding, + + /// + /// 下载超时时间(秒)。如果不指定,默认超时时间为 30 秒 + /// + DownloadTimeOut, + + /// + /// 是否启用二进制差异更新功能,默认启用;设置为 false 则执行全量覆盖安装 + /// + Patch, + + /// + /// 是否在更新前启用备份功能,默认启用;设置为 false 则不进行备份 + /// + BackUp +} +``` + +--- + +## 实际使用示例 + +### 示例 1:基本更新流程 + +```csharp +using GeneralUpdate.ClientCore; +using GeneralUpdate.Common.Internal; + +var config = new Configinfo +{ + UpdateUrl = "http://your-server.com/api/update/check", + ReportUrl = "http://your-server.com/api/update/report", + MainAppName = "MyApp.exe", + AppName = "Updater.exe", + ClientVersion = "1.0.0.0", + UpgradeClientVersion = "1.0.0.0", + InstallPath = AppDomain.CurrentDomain.BaseDirectory, + ProductId = "your-product-id", + AppSecretKey = "your-secret-key" +}; + +await new GeneralClientBootstrap() + .SetConfig(config) + .AddListenerException((sender, args) => + { + Console.WriteLine($"更新异常: {args.Exception.Message}"); + }) + .LaunchAsync(); +``` + +### 示例 2:带黑名单的更新 + +```csharp +using GeneralUpdate.ClientCore; +using GeneralUpdate.Common.Internal; + +var config = new Configinfo +{ + UpdateUrl = "http://your-server.com/api/update/check", + ClientVersion = "1.0.0.0", + InstallPath = AppDomain.CurrentDomain.BaseDirectory, + // 黑名单配置 + BlackFiles = new List { "config.json", "userdata.db" }, + BlackFormats = new List { ".log", ".cache" }, + SkipDirectorys = new List { "logs", "temp" } +}; + +await new GeneralClientBootstrap() + .SetConfig(config) + .LaunchAsync(); +``` + +### 示例 3:自定义更新选项 + +```csharp +using System.Text; +using GeneralUpdate.ClientCore; +using GeneralUpdate.Common.Internal; +using GeneralUpdate.Common.Internal.Bootstrap; + +var config = new Configinfo +{ + UpdateUrl = "http://your-server.com/api/update/check", + ClientVersion = "1.0.0.0", + InstallPath = AppDomain.CurrentDomain.BaseDirectory +}; + +await new GeneralClientBootstrap() + .SetConfig(config) + // 设置下载超时 + .Option(UpdateOption.DownloadTimeOut, 120) + // 设置编码格式 + .Option(UpdateOption.Encoding, Encoding.UTF8) + // 启用二进制差异更新 + .Option(UpdateOption.Patch, true) + // 启用备份 + .Option(UpdateOption.BackUp, true) + .LaunchAsync(); +``` + +### 示例 4:完整的事件监听 + +```csharp +using GeneralUpdate.ClientCore; +using GeneralUpdate.Common.Download; +using GeneralUpdate.Common.Internal; +using GeneralUpdate.Common.Shared.Object; + +var config = new Configinfo +{ + UpdateUrl = "http://your-server.com/api/update/check", + ClientVersion = "1.0.0.0", + InstallPath = AppDomain.CurrentDomain.BaseDirectory +}; + +await new GeneralClientBootstrap() + .SetConfig(config) + // 下载统计 + .AddListenerMultiDownloadStatistics((sender, args) => + { + var version = args.Version as VersionInfo; + Console.WriteLine($"[{version.Version}] 进度: {args.ProgressPercentage}% | " + + $"速度: {args.Speed} | 剩余: {args.Remaining}"); + }) + // 单个下载完成 + .AddListenerMultiDownloadCompleted((sender, args) => + { + var version = args.Version as VersionInfo; + if (args.IsComplated) + Console.WriteLine($"✓ 版本 {version.Version} 下载成功"); + else + Console.WriteLine($"✗ 版本 {version.Version} 下载失败"); + }) + // 所有下载完成 + .AddListenerMultiAllDownloadCompleted((sender, args) => + { + if (args.IsAllDownloadCompleted) + Console.WriteLine("✓ 所有更新包下载完成,准备安装..."); + else + Console.WriteLine($"✗ 下载失败,共 {args.FailedVersions.Count} 个版本失败"); + }) + // 下载错误 + .AddListenerMultiDownloadError((sender, args) => + { + var version = args.Version as VersionInfo; + Console.WriteLine($"✗ 版本 {version.Version} 下载错误: {args.Exception.Message}"); + }) + // 异常处理 + .AddListenerException((sender, args) => + { + Console.WriteLine($"⚠ 更新异常: {args.Exception.Message}\n{args.Exception.StackTrace}"); + }) + .LaunchAsync(); +``` + +### 示例 5:自定义操作和跳过选项 + +```csharp +using GeneralUpdate.ClientCore; +using GeneralUpdate.Common.Internal; + +var config = new Configinfo +{ + UpdateUrl = "http://your-server.com/api/update/check", + ClientVersion = "1.0.0.0", + InstallPath = AppDomain.CurrentDomain.BaseDirectory +}; + +await new GeneralClientBootstrap() + .SetConfig(config) + // 添加自定义操作(更新前检查环境) + .AddCustomOption(async () => + { + Console.WriteLine("正在检查运行环境..."); + await Task.Delay(1000); + // 检查磁盘空间、依赖项等 + Console.WriteLine("环境检查完成"); + }) + // 设置用户跳过选项 + .SetCustomSkipOption(() => + { + Console.WriteLine("发现新版本,是否更新?(y/n)"); + var input = Console.ReadLine(); + return input?.ToLower() == "y"; + }) + .LaunchAsync(); +``` + +--- + +## 注意事项与警告 + +### ⚠️ 重要提示 + +1. **版本号格式** + - 版本号必须遵循语义化版本规范(如 1.0.0.0) + - 确保客户端和服务器端版本号格式一致 + +2. **网络连接** + - 确保更新服务器地址可访问 + - 建议实现重试机制处理网络波动 + +3. **进程管理** + - 更新过程会关闭主程序并启动升级助手 + - 确保保存所有用户数据后再执行更新 + +4. **权限要求** + - 在 Windows 上可能需要管理员权限来替换文件 + - 在 Linux/macOS 上需要适当的文件系统权限 + +5. **黑名单使用** + - 黑名单中的文件和目录不会被更新 + - 常用于保护配置文件、用户数据等 + +### 💡 最佳实践 + +- **备份策略**:始终启用 BackUp 选项,以便更新失败时可以回滚 +- **差异更新**:启用 Patch 选项以减少下载量和更新时间 +- **错误处理**:实现完整的异常监听和错误处理逻辑 +- **用户体验**:在更新前提示用户并允许选择更新时机 +- **测试验证**:在生产环境部署前充分测试更新流程 + +--- + +## 适用平台 + +| 产品 | 版本 | +| ------------------ | -------------------- | +| .NET | 5, 6, 7, 8, 9, 10 | +| .NET Framework | 4.6.1 | +| .NET Standard | 2.0 | +| .NET Core | 2.0 | + +--- +## 相关资源 - -### Annotations - -GeneralClientBootstrap provides the following capabilities. - -#### Properties - -| Properties | Description | -| ------------ | ------------------------------------------------------------ | -| UpdateOption | Enum for update operation configuration settings | -| Configinfo | Client-related parameter class (fields like AppType, AppName, AppSecretKey, etc.) | - -#### Methods - -| Method | Description | -| -------------------------------------- | ------------------------------------------------------------ | -| LaunchTaskAsync() | Task-based asynchronous update launch | -| LaunchAsync() | Launch update | -| SetBlacklist() | Set blacklist for update files; pass in if certain files should not be updated. | -| Option() | Set update configuration. | -| Config() | Configure update-related parameters, such as server URL and port, appSecretKey for client identification and product branching. | -| GetOption() | Get update configuration. | -| SetCustomSkipOption() | Allow users to decide whether to proceed with an update in non-mandatory update scenarios. | -| AddCustomOption() | Add an asynchronous custom operation. In theory, any custom operation can be completed. It's recommended to register environment check methods to ensure dependencies and environment are intact after the update. | -| AddListenerMultiAllDownloadCompleted() | Notification for the completion of all download tasks. | -| AddListenerMultiDownloadCompleted() | Event for the completion of single or multiple update package downloads. | -| AddListenerMultiDownloadError() | Listen for errors during each version download | -| AddListenerMultiDownloadStatistics() | Notification for download speed, remaining download time, and current download version info. | -| AddListenerException() | Notification for any issues during the entire update process. | - -### 🌴Packet - -| Property | -| ------------------------------------------------------------ | -| **MainUpdateUrl** string Main update check API address. | -| **AppType** int 1:ClientApp 2:UpdateApp | -| **UpdateUrl** string Update check API address. | -| **AppName** string Name of the application to be launched. | -| **MainAppName** string Name of the main application to be launched. | -| **Format** string Update package file format (default is Zip). | -| **IsUpgradeUpdate** bool Indicates if the update is needed to upgrade the application. | -| **IsMainUpdate** bool Indicates if the main application needs an update. | -| **UpdateLogUrl** string URL for the update log webpage. | -| **UpdateVersions** List Version information that needs updating. | -| **Encoding** Encoding File operation encoding format. | -| **DownloadTimeOut** int Download timeout duration. | -| **AppSecretKey** string Application secret key, agreed upon with the server. | -| **ClientVersion** string Current client version. | -| **LastVersion** string Latest version. | -| **InstallPath** string Installation path (used for update file logic). | -| **TempPath** string Temporary storage path for downloaded files (used for update file logic). | -| **ProcessBase64** string Configuration parameters for the upgrade terminal program. | -| **Platform** string Platform to which the current strategy belongs (Windows\Linux\Mac). | -| **BlackFiles** List Files in the blacklist will be skipped during updates. | -| **BlackFormats** File formats in the blacklist will be skipped during updates. | -| **DriveEnabled** bool Indicates if the driver upgrade feature is enabled. | - - - -### 🌴Configinfo - -Certainly! Here's the translated content: - -| **Attribute** | Type | Notes | -| -------------------- | ------ | ------------------------------------------------------------ | -| UpdateUrl | string | API address for update checks. | -| ReportUrl | string | API address for reporting update status. | -| AppName | string | Name of the application that needs to be launched. | -| MainAppName | string | Name of the main application that needs to be launched. | -| UpdateLogUrl | string | Web address for the update log. | -| AppSecretKey | string | Application secret key, agreed upon with the server for authentication and branching. | -| ClientVersion | string | Current version number of the client. | -| UpgradeClientVersion | string | Current version number of the upgrade client. | -| InstallPath | string | Installation path (used for update file logic). | -| BlackFiles | List | Files in the blacklist will be skipped during updates. | -| BlackFormats | List | File formats in the blacklist will be skipped during updates. | -| SkipDirectorys | List | Directory paths to be skipped that do not require updates. | -| ProductId | string | Unique ID of the current product branch. | -| Bowl | string | Path to the Bowl monitoring process, which starts after updates to check if the Bowl client starts normally. If an exception occurs after starting, the exception information will be captured. | -| Scheme | string | Used for passing a token in HTTP requests for authentication. | -| Token | string | Token used in HTTP requests for authentication. | -| Script | string | This script assigns permissions to files and is executed on the Linux platform after the update is completed. If permissions need to be assigned before the update, this can be injected via the `GeneralClientBootstrap.AddCustomOption` function in the bootstrap startup class, and the function will be executed prior to the update. | - -### 🍵UpdateOption - -| Enum | -| ------------------------------------------------------------ | -| **Format** File format of the update package. | -| **Encoding** Compression encoding. | -| **DownloadTimeOut** Timeout duration (in seconds). If not specified, the default timeout is 30 seconds. | -| **Patch** Whether to enable the binary differential update function, which is enabled by default; if set to `false`, a full overwrite installation will be performed instead. | -| **BackUp** Whether to enable the backup function before update, which is enabled by default; no backup will be performed if set to `false`. | - - - -### Applicable To - -| Product | Version | -| -------------- | ---------------- | -| .NET | 5, 6, 7, 8, 9,10 | -| .NET Framework | 4.6.1 | -| .NET Standard | 2.0 | -| .NET Core | 2.0 | +- **示例代码**:[查看 GitHub 示例](https://github.com/GeneralLibrary/GeneralUpdate-Samples/blob/main/src/Client/Program.cs) +- **主仓库**:[GeneralUpdate 项目](https://github.com/GeneralLibrary/GeneralUpdate) diff --git a/website/docs/doc/GeneralUpdate.Core.md b/website/docs/doc/GeneralUpdate.Core.md index a8e0bc5..7e60681 100644 --- a/website/docs/doc/GeneralUpdate.Core.md +++ b/website/docs/doc/GeneralUpdate.Core.md @@ -2,75 +2,564 @@ sidebar_position: 5 --- -### Definition +# GeneralUpdate.Core -Namespace: GeneralUpdate.Core +## 组件概览 -Assembly: GeneralUpdate.Core.dll +**GeneralUpdate.Core** 是 GeneralUpdate 框架最核心的组件之一,提供了完整的升级执行能力。与 ClientCore 不同,Core 组件作为独立的升级助手程序运行,负责在主程序关闭后执行实际的文件替换、版本升级和系统更新操作。通过进程启动和参数传递的方式,Core 接收来自 ClientCore 的更新指令,并安全地完成主程序的升级任务。 +**命名空间:** `GeneralUpdate.Core` +**程序集:** `GeneralUpdate.Core.dll` +```csharp +public class GeneralUpdateBootstrap : AbstractBootstrap +``` + +--- -GeneralUpdate.Core is one of the most essential components, providing a wide range of primary functionalities. Once the main program upgrade operation is completed, this component is invoked through process startup and parameter passing to complete the main program upgrade operation. (Main responsibility is updating the main program) +## 核心特性 -```c# -public class GeneralUpdateBootstrap : AbstractBootstrap +### 1. 文件替换与版本管理 +- 安全的文件替换机制,避免文件占用问题 +- 支持多版本增量升级 +- 自动处理文件依赖关系 + +### 2. 驱动升级支持 +- 可选的驱动程序升级功能 +- 字段映射表配置 +- 安全的驱动安装流程 + +### 3. 完整的事件通知 +- 下载进度实时监控 +- 多版本下载管理 +- 异常和错误完整捕获 + +### 4. 跨平台支持 +- Windows、Linux、macOS 平台全支持 +- 自动平台检测和策略适配 + +![Multi Download](imgs/muti_donwload.png) + +--- + +## 快速开始 + +### 安装 + +通过 NuGet 安装 GeneralUpdate.Core: + +```bash +dotnet add package GeneralUpdate.Core +``` + +### 初始化与使用 + +以下示例展示了如何在升级助手程序中配置和启动升级流程: + +```csharp +using GeneralUpdate.Common.Download; +using GeneralUpdate.Common.Internal; +using GeneralUpdate.Common.Shared.Object; +using GeneralUpdate.Core; + +try +{ + Console.WriteLine($"升级程序初始化,{DateTime.Now}!"); + Console.WriteLine("当前运行目录:" + Thread.GetDomain().BaseDirectory); + + // 启动升级流程 + await new GeneralUpdateBootstrap() + // 监听下载统计信息 + .AddListenerMultiDownloadStatistics(OnMultiDownloadStatistics) + // 监听单个下载完成 + .AddListenerMultiDownloadCompleted(OnMultiDownloadCompleted) + // 监听所有下载完成 + .AddListenerMultiAllDownloadCompleted(OnMultiAllDownloadCompleted) + // 监听下载错误 + .AddListenerMultiDownloadError(OnMultiDownloadError) + // 监听异常 + .AddListenerException(OnException) + // 启动异步升级 + .LaunchAsync(); + + Console.WriteLine($"升级程序已启动,{DateTime.Now}!"); + await Task.Delay(2000); +} +catch (Exception e) +{ + Console.WriteLine(e.Message + "\n" + e.StackTrace); +} + +// 事件处理方法 +void OnMultiDownloadStatistics(object arg1, MultiDownloadStatisticsEventArgs arg2) +{ + var version = arg2.Version as VersionInfo; + Console.WriteLine($"当前下载版本:{version.Version},下载速度:{arg2.Speed}," + + $"剩余时间:{arg2.Remaining},进度:{arg2.ProgressPercentage}%"); +} + +void OnMultiDownloadCompleted(object arg1, MultiDownloadCompletedEventArgs arg2) +{ + var version = arg2.Version as VersionInfo; + Console.WriteLine(arg2.IsComplated ? + $"版本 {version.Version} 下载完成!" : + $"版本 {version.Version} 下载失败!"); +} + +void OnMultiAllDownloadCompleted(object arg1, MultiAllDownloadCompletedEventArgs arg2) +{ + Console.WriteLine(arg2.IsAllDownloadCompleted ? + "所有下载任务已完成!" : + $"下载任务失败!失败数量:{arg2.FailedVersions.Count}"); +} + +void OnMultiDownloadError(object arg1, MultiDownloadErrorEventArgs arg2) +{ + var version = arg2.Version as VersionInfo; + Console.WriteLine($"版本 {version.Version} 下载错误:{arg2.Exception}"); +} + +void OnException(object arg1, ExceptionEventArgs arg2) +{ + Console.WriteLine($"升级异常:{arg2.Exception}"); +} +``` + +--- + +## 核心 API 参考 + +### GeneralUpdateBootstrap 类方法 + +#### LaunchAsync 方法 + +异步启动升级流程。 + +```csharp +public async Task LaunchAsync() +``` + +**返回值:** +- 返回当前 GeneralUpdateBootstrap 实例,支持链式调用 + +#### Option 方法 + +设置升级选项。 + +```csharp +public GeneralUpdateBootstrap Option(UpdateOption option, object value) +``` + +**参数:** +- `option`: 升级选项枚举 +- `value`: 选项值 + +**示例:** +```csharp +.Option(UpdateOption.Drive, true) // 启用驱动升级 +``` + +#### AddListenerMultiDownloadStatistics 方法 + +监听下载统计信息(速度、进度、剩余时间等)。 + +```csharp +public GeneralUpdateBootstrap AddListenerMultiDownloadStatistics( + Action callbackAction) +``` + +#### AddListenerMultiDownloadCompleted 方法 + +监听单个更新包下载完成事件。 + +```csharp +public GeneralUpdateBootstrap AddListenerMultiDownloadCompleted( + Action callbackAction) +``` + +#### AddListenerMultiAllDownloadCompleted 方法 + +监听所有版本下载完成事件。 + +```csharp +public GeneralUpdateBootstrap AddListenerMultiAllDownloadCompleted( + Action callbackAction) +``` + +#### AddListenerMultiDownloadError 方法 + +监听每个版本下载错误事件。 + +```csharp +public GeneralUpdateBootstrap AddListenerMultiDownloadError( + Action callbackAction) +``` + +#### AddListenerException 方法 + +监听升级组件内部所有异常。 + +```csharp +public GeneralUpdateBootstrap AddListenerException( + Action callbackAction) +``` + +#### SetFieldMappings 方法 + +设置字段映射表,用于解析驱动包信息。 + +```csharp +public GeneralUpdateBootstrap SetFieldMappings(Dictionary fieldMappings) ``` +**参数:** +- `fieldMappings`: 字段映射字典,键为英文字段名,值为本地化字段名 +--- -### Example +## 配置类详解 -GeneralUpdateBootstrap uses code examples [[View]](https://github.com/GeneralLibrary/GeneralUpdate-Samples/blob/main/src/Upgrade/Program.cs)。 +### UpdateOption 枚举 -![](imgs/muti_donwload.png) +```csharp +public enum UpdateOption +{ + /// + /// 是否启用驱动升级功能 + /// + Drive +} +``` +### Packet 类 +升级包信息类,由 ClientCore 通过参数传递给 Core: -### Annotations +```csharp +public class Packet +{ + /// + /// 主更新检查 API 地址 + /// + public string MainUpdateUrl { get; set; } + + /// + /// 应用类型:1=客户端应用,2=更新应用 + /// + public int AppType { get; set; } + + /// + /// 更新检查 API 地址 + /// + public string UpdateUrl { get; set; } + + /// + /// 需要启动的应用程序名称 + /// + public string AppName { get; set; } + + /// + /// 主应用程序名称 + /// + public string MainAppName { get; set; } + + /// + /// 更新包文件格式(默认为 Zip) + /// + public string Format { get; set; } + + /// + /// 是否需要升级更新应用 + /// + public bool IsUpgradeUpdate { get; set; } + + /// + /// 是否需要更新主应用 + /// + public bool IsMainUpdate { get; set; } + + /// + /// 更新日志网页 URL + /// + public string UpdateLogUrl { get; set; } + + /// + /// 需要更新的版本信息列表 + /// + public List UpdateVersions { get; set; } + + /// + /// 文件操作编码格式 + /// + public Encoding Encoding { get; set; } + + /// + /// 下载超时时间(秒) + /// + public int DownloadTimeOut { get; set; } + + /// + /// 应用密钥,与服务器约定 + /// + public string AppSecretKey { get; set; } + + /// + /// 当前客户端版本 + /// + public string ClientVersion { get; set; } + + /// + /// 最新版本 + /// + public string LastVersion { get; set; } + + /// + /// 安装路径(用于更新文件逻辑) + /// + public string InstallPath { get; set; } + + /// + /// 下载文件的临时存储路径 + /// + public string TempPath { get; set; } + + /// + /// 升级终端程序的配置参数(Base64 编码) + /// + public string ProcessBase64 { get; set; } + + /// + /// 当前策略所属平台(Windows/Linux/Mac) + /// + public string Platform { get; set; } + + /// + /// 黑名单文件列表 + /// + public List BlackFiles { get; set; } + + /// + /// 黑名单文件格式列表 + /// + public List BlackFormats { get; set; } + + /// + /// 是否启用驱动升级功能 + /// + public bool DriveEnabled { get; set; } +} +``` -GeneralUpdateBootstrap provides the following capabilities. +--- -#### Constructors +## 实际使用示例 -| Constructors | Description | -| ------------------------ | ------------------------------------------ | -| GeneralUpdateBootstrap() | Current GeneralUpdateBootstrap constructor | -| base:AbstractBootstrap() | Parent class AbstractBootstrap constructor | +### 示例 1:基本升级流程 -#### Properties +```csharp +using GeneralUpdate.Common.Download; +using GeneralUpdate.Common.Internal; +using GeneralUpdate.Common.Shared.Object; +using GeneralUpdate.Core; -| Properties | Description | -| ------------ | ------------------------------------------ | -| Packet | Update package information | -| UpdateOption | Update operation configuration enumeration | +try +{ + Console.WriteLine("升级程序初始化..."); + + // 启动升级流程 + await new GeneralUpdateBootstrap() + .AddListenerMultiDownloadStatistics((sender, args) => + { + var version = args.Version as VersionInfo; + Console.WriteLine($"[{version.Version}] 下载进度: {args.ProgressPercentage}%"); + }) + .AddListenerException((sender, args) => + { + Console.WriteLine($"升级异常: {args.Exception.Message}"); + }) + .LaunchAsync(); + + Console.WriteLine("升级完成!"); +} +catch (Exception e) +{ + Console.WriteLine($"升级失败: {e.Message}"); +} +``` -#### Methods +### 示例 2:启用驱动升级 -| Method | Description | -| -------------------------------------- | ---------------------------------------------------------- | -| LaunchTaskAsync() | Asynchronously launch update with Task | -| LaunchAsync() | Launch update | -| Option() | Set update configuration | -| GetOption() | Get update configuration | -| AddListenerMultiAllDownloadCompleted() | Listen for completion of all version downloads | -| AddListenerMultiDownloadCompleted() | Listen for completion of each version download | -| AddListenerMultiDownloadError() | Listen for download errors for each version | -| AddListenerMultiDownloadStatistics() | Listen for download statistics/progress for each version | -| AddListenerException() | Listen for all internal exceptions in the update component | +```csharp +using GeneralUpdate.Core; +using GeneralUpdate.Common.Internal.Bootstrap; -### 🍵UpdateOption +// 中文字段映射表 +var fieldMappingsCN = new Dictionary +{ + { "DriverName", "驱动名称" }, + { "DriverVersion", "驱动版本" }, + { "DriverDescription", "驱动描述" }, + { "InstallPath", "安装路径" } +}; -**Enumeration** +await new GeneralUpdateBootstrap() + // 设置字段映射表 + .SetFieldMappings(fieldMappingsCN) + // 启用驱动更新 + .Option(UpdateOption.Drive, true) + .AddListenerException((sender, args) => + { + Console.WriteLine($"升级异常: {args.Exception.Message}"); + }) + .LaunchAsync(); +``` -**Drive** Whether to enable driver upgrade functionality. +### 示例 3:完整事件监听 +```csharp +using GeneralUpdate.Core; +using GeneralUpdate.Common.Download; +using GeneralUpdate.Common.Shared.Object; +await new GeneralUpdateBootstrap() + // 下载统计 + .AddListenerMultiDownloadStatistics((sender, args) => + { + var version = args.Version as VersionInfo; + Console.WriteLine($"[{version.Version}]"); + Console.WriteLine($" 速度: {args.Speed}"); + Console.WriteLine($" 进度: {args.ProgressPercentage}%"); + Console.WriteLine($" 已下载: {args.BytesReceived} / {args.TotalBytesToReceive}"); + Console.WriteLine($" 剩余时间: {args.Remaining}"); + }) + // 单个下载完成 + .AddListenerMultiDownloadCompleted((sender, args) => + { + var version = args.Version as VersionInfo; + string status = args.IsComplated ? "✓ 成功" : "✗ 失败"; + Console.WriteLine($"版本 {version.Version} 下载{status}"); + }) + // 所有下载完成 + .AddListenerMultiAllDownloadCompleted((sender, args) => + { + if (args.IsAllDownloadCompleted) + { + Console.WriteLine("✓ 所有版本下载完成,开始安装..."); + } + else + { + Console.WriteLine($"✗ 下载失败,{args.FailedVersions.Count} 个版本失败:"); + foreach (var version in args.FailedVersions) + { + Console.WriteLine($" - {version}"); + } + } + }) + // 下载错误 + .AddListenerMultiDownloadError((sender, args) => + { + var version = args.Version as VersionInfo; + Console.WriteLine($"✗ 版本 {version.Version} 错误:"); + Console.WriteLine($" {args.Exception.Message}"); + }) + // 异常处理 + .AddListenerException((sender, args) => + { + Console.WriteLine("⚠ 升级过程异常:"); + Console.WriteLine($" 错误: {args.Exception.Message}"); + Console.WriteLine($" 堆栈: {args.Exception.StackTrace}"); + }) + .LaunchAsync(); +``` + +### 示例 4:自定义升级流程 + +```csharp +using GeneralUpdate.Core; +using GeneralUpdate.Common.Download; +using GeneralUpdate.Common.Shared.Object; + +// 记录升级开始时间 +var startTime = DateTime.Now; +var downloadedVersions = new List(); + +await new GeneralUpdateBootstrap() + .AddListenerMultiDownloadCompleted((sender, args) => + { + if (args.IsComplated) + { + var version = args.Version as VersionInfo; + downloadedVersions.Add(version.Version); + } + }) + .AddListenerMultiAllDownloadCompleted((sender, args) => + { + if (args.IsAllDownloadCompleted) + { + var duration = DateTime.Now - startTime; + Console.WriteLine($"升级完成!"); + Console.WriteLine($"总耗时: {duration.TotalSeconds:F2} 秒"); + Console.WriteLine($"已更新版本: {string.Join(", ", downloadedVersions)}"); + } + }) + .AddListenerException((sender, args) => + { + // 记录日志到文件 + File.AppendAllText("upgrade_error.log", + $"[{DateTime.Now}] {args.Exception}\n"); + }) + .LaunchAsync(); +``` + +--- + +## 注意事项与警告 + +### ⚠️ 重要提示 + +1. **进程隔离** + - Core 必须作为独立进程运行,不能在主程序中直接调用 + - 升级时主程序必须完全关闭,否则文件替换会失败 + +2. **参数传递** + - ClientCore 通过 Base64 编码的参数传递配置给 Core + - 确保参数传递过程中不会被截断或损坏 + +3. **文件权限** + - 在 Windows 上可能需要管理员权限替换系统目录中的文件 + - 在 Linux/macOS 上需要适当的文件系统权限 + +4. **驱动升级** + - 驱动升级功能需要系统级权限 + - 建议在测试环境充分验证后再使用 + +5. **回滚机制** + - Core 不直接提供回滚功能,但保留了备份文件 + - 如需回滚,可使用 ClientCore 的备份功能 + +### 💡 最佳实践 + +- **日志记录**:实现完整的异常监听,记录升级过程中的所有问题 +- **超时设置**:根据网络环境合理设置下载超时时间 +- **进度反馈**:向用户显示升级进度,提升用户体验 +- **错误处理**:升级失败时提供清晰的错误信息和解决方案 +- **测试验证**:在各种网络条件下测试升级流程的稳定性 + +--- + +## 适用平台 + +| 产品 | 版本 | +| ------------------ | ----------------- | +| .NET | 5, 6, 7, 8, 9 | +| .NET Framework | 4.6.1 | +| .NET Standard | 2.0 | +| .NET Core | 2.0 | + +--- -### Applicable to +## 相关资源 -| Product | Versions | -| -------------- | ------------- | -| .NET | 5, 6, 7, 8, 9 | -| .NET Framework | 4.6.1 | -| .NET Standard | 2.0 | -| .NET Core | 2.0 | +- **示例代码**:[查看 GitHub 示例](https://github.com/GeneralLibrary/GeneralUpdate-Samples/blob/main/src/Upgrade/Program.cs) +- **主仓库**:[GeneralUpdate 项目](https://github.com/GeneralLibrary/GeneralUpdate) +- **相关组件**:[GeneralUpdate.ClientCore](./GeneralUpdate.ClientCore.md) | [GeneralUpdate.Bowl](./GeneralUpdate.Bowl.md) diff --git a/website/docs/doc/GeneralUpdate.Differential.md b/website/docs/doc/GeneralUpdate.Differential.md index b7f8576..edb101a 100644 --- a/website/docs/doc/GeneralUpdate.Differential.md +++ b/website/docs/doc/GeneralUpdate.Differential.md @@ -2,100 +2,447 @@ sidebar_position: 6 --- -### Definition +# GeneralUpdate.Differential -Namespace: GeneralUpdate.Differential +## 组件概览 -Assembly: GeneralUpdate.Core.dll +**GeneralUpdate.Differential** 是 GeneralUpdate 框架中负责二进制差异更新的核心组件。该组件提供了强大的差异算法,可以精确识别两个版本之间的文件变化,生成高效的增量补丁包,并支持补丁还原操作。通过使用差异更新,可以显著减少更新包的大小和下载时间,特别适合频繁发布更新的应用场景。 +**命名空间:** `GeneralUpdate.Differential` +**程序集:** `GeneralUpdate.Core.dll` +```csharp +public sealed class DifferentialCore +``` -This component provides capabilities for generating binary differential patch files (algorithm), file increment identification (version differences), deleted file identification (version differences), blacklisting, patch restoration, and more. +--- -```c# -public sealed class DifferentialCore +## 核心特性 + +### 1. 增量识别 +- 精确识别新增、修改、删除的文件 +- 智能文件版本对比 +- 支持跳过指定文件和格式 + +### 2. 二进制补丁生成 +- 高效的二进制差异算法 +- 最小化补丁文件大小 +- 快速补丁生成速度 + +### 3. 补丁还原 +- 安全的补丁应用流程 +- 自动处理文件依赖关系 +- 完整性验证机制 + +### 4. 黑名单支持 +- 文件级黑名单 +- 格式级黑名单 +- 灵活的过滤规则 + +--- + +## 快速开始 + +### 安装 + +通过 NuGet 安装 GeneralUpdate.Differential(包含在 Core 包中): + +```bash +dotnet add package GeneralUpdate.Core ``` +### 初始化与使用 + +以下示例展示了如何使用 DifferentialCore 进行增量识别和补丁操作: + +```csharp +using GeneralUpdate.Differential; + +// 增量识别并生成二进制补丁 +var sourcePath = @"D:\packet\app"; // 旧版本路径 +var targetPath = @"D:\packet\release"; // 新版本路径 +var patchPath = @"D:\packet\patch"; // 补丁输出路径 +await DifferentialCore.Instance?.Clean(sourcePath, targetPath, patchPath); -### Example +// 应用补丁(还原) +await DifferentialCore.Instance?.Dirty(sourcePath, patchPath); +``` + +--- + +## 核心 API 参考 + +### DifferentialCore 类 + +#### Instance 属性 + +获取 DifferentialCore 的单例实例。 + +```csharp +public static DifferentialCore Instance { get; } +``` + +#### Clean 方法 + +执行增量识别、删除文件识别,并生成二进制补丁文件。 + +**方法签名:** + +```csharp +public async Task Clean(string sourcePath, string targetPath, string patchPath = null) +``` + +**参数:** +- `sourcePath`: 旧版本文件夹路径 +- `targetPath`: 新版本文件夹路径 +- `patchPath`: 补丁文件输出目录(可选) + +**功能说明:** +1. 对比 sourcePath 和 targetPath 两个目录 +2. 识别新增、修改、删除的文件 +3. 为修改的文件生成二进制差异补丁 +4. 将补丁和新增文件保存到 patchPath + +**示例:** +```csharp +// 生成从 v1.0.0 到 v1.1.0 的补丁包 +var source = @"D:\MyApp\v1.0.0"; +var target = @"D:\MyApp\v1.1.0"; +var patch = @"D:\MyApp\patches\v1.1.0"; + +await DifferentialCore.Instance.Clean(source, target, patch); +// 结果:patch 目录包含所有必要的增量更新文件 +``` -The following example defines methods for increment identification, generating binary patches, patch restoration, and setting blacklists. The packaging tool in the GeneralUpdate.Tools project also strongly depends on this component. +#### Dirty 方法 -```c# -// Increment identification, generating binary patches -public async Task TestDifferentialClean() +应用补丁,将旧版本文件更新到新版本。 + +**方法签名:** + +```csharp +public async Task Dirty(string appPath, string patchPath) +``` + +**参数:** +- `appPath`: 客户端应用程序目录(当前版本) +- `patchPath`: 补丁文件路径 + +**功能说明:** +1. 读取 patchPath 中的补丁文件 +2. 将补丁应用到 appPath 中的对应文件 +3. 处理新增文件的复制 +4. 处理删除文件的移除 + +**示例:** +```csharp +// 将补丁应用到当前应用程序 +var appDir = AppDomain.CurrentDomain.BaseDirectory; +var patchDir = Path.Combine(appDir, "temp", "patches"); + +await DifferentialCore.Instance.Dirty(appDir, patchDir); +// 结果:应用程序更新到新版本 +``` + +--- + +## 实际使用示例 + +### 示例 1:基本补丁生成 + +```csharp +using GeneralUpdate.Differential; + +public async Task GeneratePatchAsync() { - // Path to the previous version's client folder - var path1 = "D:\\packet\\source"; - // Path to the latest version's client folder - var path2 = "D:\\packet\\target"; - // Path for generating patch files - var path3 = "D:\\packet\\patchs"; - await DifferentialCore.Instance.Clean(path1, path2, path3); + try + { + // 版本路径 + var oldVersion = @"D:\MyApp\1.0.0"; + var newVersion = @"D:\MyApp\1.0.1"; + var patchOutput = @"D:\MyApp\patches\1.0.1"; + + Console.WriteLine("开始生成补丁..."); + + // 生成补丁 + await DifferentialCore.Instance.Clean(oldVersion, newVersion, patchOutput); + + Console.WriteLine($"补丁生成完成!输出目录:{patchOutput}"); + + // 显示补丁信息 + var patchFiles = Directory.GetFiles(patchOutput, "*.*", SearchOption.AllDirectories); + Console.WriteLine($"生成了 {patchFiles.Length} 个补丁文件"); + + long totalSize = patchFiles.Sum(f => new FileInfo(f).Length); + Console.WriteLine($"总补丁大小:{totalSize / 1024.0:F2} KB"); + } + catch (Exception ex) + { + Console.WriteLine($"补丁生成失败:{ex.Message}"); + } } +``` + +### 示例 2:应用补丁 -// Patch restoration -public async Task TestDifferentialDirty() +```csharp +using GeneralUpdate.Differential; + +public async Task ApplyPatchAsync() { - // Path to the current version's client folder - var path1 = "D:\\packet\\source"; - // Path for generating patch files - var path2 = "D:\\packet\\patchs"; - await DifferentialCore.Instance.Dirty(path1, path2); + try + { + // 应用程序目录 + var appDirectory = @"D:\MyApp\current"; + // 补丁目录 + var patchDirectory = @"D:\MyApp\patches\1.0.1"; + + Console.WriteLine("开始应用补丁..."); + + // 验证补丁存在 + if (!Directory.Exists(patchDirectory)) + { + throw new DirectoryNotFoundException($"补丁目录不存在:{patchDirectory}"); + } + + // 应用补丁 + await DifferentialCore.Instance.Dirty(appDirectory, patchDirectory); + + Console.WriteLine("补丁应用成功!应用程序已更新到新版本。"); + } + catch (Exception ex) + { + Console.WriteLine($"补丁应用失败:{ex.Message}"); + } } ``` -### Annotations +### 示例 3:完整的补丁流程 + +```csharp +using GeneralUpdate.Differential; +using System.IO.Compression; -DifferentialCore provides capabilities for increment identification, generating binary patches, patch restoration, and setting blacklists. +public class PatchManager +{ + // 生成并打包补丁 + public async Task CreatePatchPackageAsync( + string oldVersionPath, + string newVersionPath, + string outputPath) + { + try + { + // 1. 生成补丁文件 + var tempPatchDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempPatchDir); + + Console.WriteLine($"正在生成补丁..."); + await DifferentialCore.Instance.Clean(oldVersionPath, newVersionPath, tempPatchDir); + + // 2. 压缩补丁文件 + var patchZipPath = Path.Combine(outputPath, "patch_1.0.1.zip"); + Console.WriteLine($"正在打包补丁..."); + + if (File.Exists(patchZipPath)) + File.Delete(patchZipPath); + + ZipFile.CreateFromDirectory(tempPatchDir, patchZipPath, + CompressionLevel.Optimal, false); + + // 3. 清理临时文件 + Directory.Delete(tempPatchDir, true); + + var patchSize = new FileInfo(patchZipPath).Length; + Console.WriteLine($"补丁包创建成功:{patchZipPath}"); + Console.WriteLine($"补丁包大小:{patchSize / 1024.0:F2} KB"); + + return patchZipPath; + } + catch (Exception ex) + { + Console.WriteLine($"创建补丁包失败:{ex.Message}"); + throw; + } + } + + // 解压并应用补丁 + public async Task ApplyPatchPackageAsync(string appPath, string patchZipPath) + { + try + { + // 1. 解压补丁包 + var tempExtractDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempExtractDir); + + Console.WriteLine($"正在解压补丁包..."); + ZipFile.ExtractToDirectory(patchZipPath, tempExtractDir); + + // 2. 应用补丁 + Console.WriteLine($"正在应用补丁..."); + await DifferentialCore.Instance.Dirty(appPath, tempExtractDir); + + // 3. 清理临时文件 + Directory.Delete(tempExtractDir, true); + + Console.WriteLine($"补丁应用成功!"); + } + catch (Exception ex) + { + Console.WriteLine($"应用补丁包失败:{ex.Message}"); + throw; + } + } +} -#### Methods +// 使用示例 +var manager = new PatchManager(); + +// 创建补丁包 +var patchZip = await manager.CreatePatchPackageAsync( + @"D:\MyApp\1.0.0", + @"D:\MyApp\1.0.1", + @"D:\MyApp\releases" +); + +// 应用补丁包 +await manager.ApplyPatchPackageAsync( + @"D:\MyApp\current", + patchZip +); +``` -| Name | Type | Description | -| ------- | ------ | ------------------------------------------------------------ | -| Clean() | Method | Increment identification, deleted file identification, and generating binary patch files | -| Dirty() | Method | Patch restoration (applying patches to old client files to achieve updates) | +### 示例 4:带进度显示的补丁操作 -### 🌼Clean() +```csharp +using GeneralUpdate.Differential; -**Method** +public class ProgressivePatchManager +{ + public async Task GeneratePatchWithProgressAsync( + string sourcePath, + string targetPath, + string patchPath, + IProgress progress) + { + try + { + progress?.Report("开始扫描文件差异..."); + + // 在实际场景中,可以在 Clean 前后添加进度报告 + await DifferentialCore.Instance.Clean(sourcePath, targetPath, patchPath); + + progress?.Report("补丁生成完成!"); + + // 统计信息 + var files = Directory.GetFiles(patchPath, "*.*", SearchOption.AllDirectories); + progress?.Report($"共生成 {files.Length} 个补丁文件"); + } + catch (Exception ex) + { + progress?.Report($"错误:{ex.Message}"); + throw; + } + } + + public async Task ApplyPatchWithProgressAsync( + string appPath, + string patchPath, + IProgress progress) + { + try + { + progress?.Report("开始应用补丁..."); + + await DifferentialCore.Instance.Dirty(appPath, patchPath); + + progress?.Report("补丁应用成功!"); + } + catch (Exception ex) + { + progress?.Report($"错误:{ex.Message}"); + throw; + } + } +} -Generate patch files [cannot include files with the same name but different extensions]. +// 使用示例 +var manager = new ProgressivePatchManager(); +var progress = new Progress(msg => Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] {msg}")); -```c# -public async Task Clean(string sourcePath, string targetPath, string patchPath = null); +await manager.GeneratePatchWithProgressAsync( + @"D:\MyApp\1.0.0", + @"D:\MyApp\1.0.1", + @"D:\MyApp\patches\1.0.1", + progress +); ``` +--- -**Parameters** +## 注意事项与警告 -**sourcePath** Path to the previous version's folder. +### ⚠️ 重要提示 -**targetPath** Path to the latest version's folder. +1. **文件名限制** + - 不能包含同名但扩展名不同的文件(如 file.txt 和 file.log) + - 建议使用唯一的文件名命名规则 -**patchPath** Directory to store the discovered incremental update files temporarily. +2. **目录结构** + - 源目录和目标目录的相对结构应保持一致 + - 补丁生成时会保留目录层次关系 -### 🌼Dirty() +3. **磁盘空间** + - 确保有足够的磁盘空间存储补丁文件 + - 二进制差异补丁通常比完整文件小,但仍需要临时空间 -**Method** +4. **文件占用** + - 应用补丁时,确保目标文件没有被其他进程占用 + - 建议在应用程序关闭后应用补丁 -Apply patches [cannot include files with the same name but different extensions]. +5. **备份建议** + - 在应用补丁前建议备份原始文件 + - 可以使用 ClientCore 的 BackUp 选项自动备份 -```c# -public async Task Dirty(string appPath, string patchPath); -``` +### 💡 最佳实践 + +- **版本管理**:为每个版本维护独立的补丁包,便于版本追踪和回滚 +- **补丁验证**:生成补丁后进行验证测试,确保补丁可以正确应用 +- **增量更新**:优先使用差异更新而非全量更新,可节省 50%-90% 的下载量 +- **错误处理**:实现完整的异常捕获和错误恢复机制 +- **性能优化**:对于大文件,差异算法的性能优势更加明显 + +### 🔍 工作原理 + +**Clean 方法工作流程:** +1. 扫描源目录和目标目录中的所有文件 +2. 比较文件的MD5哈希值以识别变化 +3. 对于修改的文件,使用二进制差异算法生成补丁 +4. 对于新增文件,直接复制到补丁目录 +5. 记录删除的文件列表 -**Parameters** +**Dirty 方法工作流程:** +1. 读取补丁目录中的所有文件 +2. 对于补丁文件,应用到对应的原文件上 +3. 对于新增文件,直接复制到应用目录 +4. 根据删除列表移除相应文件 +5. 验证更新完整性 -**appPath** Client application directory. +--- + +## 适用平台 -**patchPath** Path to the patch files. +| 产品 | 版本 | +| ------------------ | ----------------- | +| .NET | 5, 6, 7, 8, 9 | +| .NET Framework | 4.6.1 | +| .NET Standard | 2.0 | +| .NET Core | 2.0 | + +--- -### Applicable to +## 相关资源 -| Product | Versions | -| -------------- | ------------- | -| .NET | 5, 6, 7, 8, 9 | -| .NET Framework | 4.6.1 | -| .NET Standard | 2.0 | -| .NET Core | 2.0 | \ No newline at end of file +- **示例代码**:[查看 GitHub 示例](https://github.com/GeneralLibrary/GeneralUpdate-Samples/tree/main/src/Diff) +- **主仓库**:[GeneralUpdate 项目](https://github.com/GeneralLibrary/GeneralUpdate) +- **打包工具**:GeneralUpdate.PacketTool 项目依赖此组件实现差异打包 diff --git a/website/docusaurus.config.js b/website/docusaurus.config.js index 4cb20ee..575efb3 100644 --- a/website/docusaurus.config.js +++ b/website/docusaurus.config.js @@ -127,6 +127,7 @@ const config = { prism: { theme: prismThemes.github, darkTheme: prismThemes.dracula, + additionalLanguages: ['csharp', 'bash', 'json'], }, }), }; diff --git a/website/i18n/en/docusaurus-plugin-content-docs/current/doc/GeneralUpdate.Bowl.md b/website/i18n/en/docusaurus-plugin-content-docs/current/doc/GeneralUpdate.Bowl.md index 6cfe08b..1fb57e4 100644 --- a/website/i18n/en/docusaurus-plugin-content-docs/current/doc/GeneralUpdate.Bowl.md +++ b/website/i18n/en/docusaurus-plugin-content-docs/current/doc/GeneralUpdate.Bowl.md @@ -2,73 +2,225 @@ sidebar_position: 3 --- -### Definition +# GeneralUpdate.Bowl -Namespace: GeneralUpdate.Bowl +## Component Overview -Assembly: GeneralUpdate.Bowl.dll +**GeneralUpdate.Bowl** is an independent process monitoring component that launches before the end of the upgrade process. It is responsible for starting the main client application and monitoring its running status. This component provides comprehensive crash monitoring and diagnostic capabilities. When the monitored application encounters an exception, it automatically exports Dump files, driver information, system information, and event logs to help developers quickly locate issues. -This component is an independent process launched before the end of the upgrade process. It starts the main client application and monitors its normal operation before the process ends. +**Namespace:** `GeneralUpdate.Bowl` +**Assembly:** `GeneralUpdate.Bowl.dll` -```c# +```csharp public sealed class Bowl ``` +--- + +## Core Features + +### 1. Process Monitoring +- Real-time monitoring of target application status +- Automatic detection of process crashes and abnormal exits + +### 2. Crash Diagnostics +- Automatic generation of Dump files (.dmp) for crash analysis +- Export detailed system and driver information +- Collect Windows system event logs + +### 3. Version Management +- Store failure information categorized by version number +- Support both upgrade and normal working modes + +--- +## Quick Start -### Example +### Installation -The following example defines a method that includes the use of Bowl. +Install GeneralUpdate.Bowl via NuGet: + +```bash +dotnet add package GeneralUpdate.Bowl +``` + +### Initialization and Usage + +The following example demonstrates how to use the Bowl component to monitor an application: + +```csharp +using GeneralUpdate.Bowl; +using GeneralUpdate.Bowl.Strategys; -```c# var installPath = AppDomain.CurrentDomain.BaseDirectory; var lastVersion = "1.0.0.3"; var processInfo = new MonitorParameter { - ProcessNameOrId = "JsonTest.exe", + ProcessNameOrId = "YourApp.exe", DumpFileName = $"{lastVersion}_fail.dmp", FailFileName = $"{lastVersion}_fail.json", TargetPath = installPath, FailDirectory = Path.Combine(installPath, "fail", lastVersion), BackupDirectory = Path.Combine(installPath, lastVersion), - WorkModel = "Normal" + WorkModel = "Normal" // Use Normal mode for standalone monitoring }; Bowl.Launch(processInfo); ``` -### Capture +--- + +## Core API Reference + +### Launch Method + +Start the process monitoring functionality. + +**Method Signature:** + +```csharp +public static void Launch(MonitorParameter? monitorParameter = null) +``` + +**Parameters:** + +#### MonitorParameter Class -If a crash is detected, the following files will be generated in the running directory: +```csharp +public class MonitorParameter +{ + /// + /// Directory being monitored + /// + public string TargetPath { get; set; } + + /// + /// Directory where captured exception information is exported + /// + public string FailDirectory { get; set; } + + /// + /// Backup directory + /// + public string BackupDirectory { get; set; } + + /// + /// Name or ID of the process being monitored + /// + public string ProcessNameOrId { get; set; } + + /// + /// Dump file name + /// + public string DumpFileName { get; set; } + + /// + /// Upgrade package version information (.json) file name + /// + public string FailFileName { get; set; } -- 📒 Dump file (1.0.0.*_fail.dmp) -- 📒 Upgrade package version information (1.0.0.*_fail.json) -- 📒 Driver information (driverInfo.txt) -- 📒 Operating system/hardware information (systeminfo.txt) -- 📒 System event log (systemlog.evtx) + /// + /// Work Mode: + /// - Upgrade: Upgrade mode, primarily used in conjunction with GeneralUpdate for internal logic handling. + /// Do not modify arbitrarily when the default mode is activated. + /// - Normal: Normal mode, can be used independently to monitor a single program. + /// Exports crash information when the program crashes. + /// + public string WorkModel { get; set; } = "Upgrade"; +} +``` -These will be exported to the "fail" directory, categorized by version number. +--- -![](imgs\crash.jpg) +## Practical Usage Examples -#### (1) x.0.0.*_fail.dmp +### Example 1: Standalone Mode Application Monitoring -![](imgs\dump.png) +```csharp +using GeneralUpdate.Bowl; +using GeneralUpdate.Bowl.Strategys; -#### (2) x.0.0.*_fail.json +// Configure monitoring parameters +var installPath = AppDomain.CurrentDomain.BaseDirectory; +var currentVersion = "1.0.0.5"; + +var monitorConfig = new MonitorParameter +{ + ProcessNameOrId = "MyApplication.exe", + DumpFileName = $"{currentVersion}_crash.dmp", + FailFileName = $"{currentVersion}_crash.json", + TargetPath = installPath, + FailDirectory = Path.Combine(installPath, "crash_reports", currentVersion), + BackupDirectory = Path.Combine(installPath, "backups", currentVersion), + WorkModel = "Normal" // Standalone monitoring mode +}; + +// Start monitoring +Bowl.Launch(monitorConfig); +``` + +### Example 2: Use with GeneralUpdate + +```csharp +using GeneralUpdate.Bowl; +using GeneralUpdate.Bowl.Strategys; + +// Start Bowl monitoring after upgrade completion +var installPath = AppDomain.CurrentDomain.BaseDirectory; +var upgradedVersion = "2.0.0.1"; + +var upgradeMonitor = new MonitorParameter +{ + ProcessNameOrId = "UpdatedApp.exe", + DumpFileName = $"{upgradedVersion}_fail.dmp", + FailFileName = $"{upgradedVersion}_fail.json", + TargetPath = installPath, + FailDirectory = Path.Combine(installPath, "fail", upgradedVersion), + BackupDirectory = Path.Combine(installPath, upgradedVersion), + WorkModel = "Upgrade" // Upgrade mode +}; + +Bowl.Launch(upgradeMonitor); +``` + +--- + +## Crash Information Capture + +When a crash is detected, the following files will be generated in the running directory: + +- 📒 **Dump file** (`x.0.0.*_fail.dmp`) +- 📒 **Upgrade package version information** (`x.0.0.*_fail.json`) +- 📒 **Driver information** (`driverInfo.txt`) +- 📒 **Operating system/hardware information** (`systeminfo.txt`) +- 📒 **System event log** (`systemlog.evtx`) + +These files will be exported to the "fail" directory, categorized by version number. + +![Crash Files](imgs/crash.jpg) + +### 1. Dump File + +The Dump file contains a memory snapshot at the moment of crash, which can be used for debugging analysis: + +![Dump File](imgs/dump.png) + +### 2. Version Information File + +Detailed crash report in JSON format, including parameter configuration and ProcDump output: ```json { - "Parameter": { - "TargetPath": "D:\\github_project\\GeneralUpdate\\src\\c#\\Generalupdate.CatBowl\\bin\\Debug\\net9.0\\", - "FailDirectory": "D:\\github_project\\GeneralUpdate\\src\\c#\\Generalupdate.CatBowl\\bin\\Debug\\net9.0\\fail\\1.0.0.3", - "BackupDirectory": "D:\\github_project\\GeneralUpdate\\src\\c#\\Generalupdate.CatBowl\\bin\\Debug\\net9.0\\1.0.0.3", - "ProcessNameOrId": "JsonTest.exe", - "DumpFileName": "1.0.0.3_fail.dmp", - "FailFileName": "1.0.0.3_fail.json", - "WorkModel": "Normal", - "ExtendedField": null - }, - "ProcdumpOutPutLines": [ +"Parameter": { +"TargetPath": "D:\\github_project\\GeneralUpdate\\src\\c#\\Generalupdate.CatBowl\\bin\\Debug\\net9.0\\", +"FailDirectory": "D:\\github_project\\GeneralUpdate\\src\\c#\\Generalupdate.CatBowl\\bin\\Debug\\net9.0\\fail\\1.0.0.3", +"BackupDirectory": "D:\\github_project\\GeneralUpdate\\src\\c#\\Generalupdate.CatBowl\\bin\\Debug\\net9.0\\1.0.0.3", +"ProcessNameOrId": "JsonTest.exe", +"DumpFileName": "1.0.0.3_fail.dmp", +"FailFileName": "1.0.0.3_fail.json", +"WorkModel": "Normal", +"ExtendedField": null +}, +"ProcdumpOutPutLines": [ "ProcDump v11.0 - Sysinternals process dump utility", "Copyright (C) 2009-2022 Mark Russinovich and Andrew Richards", "Sysinternals - www.sysinternals.com", @@ -96,147 +248,83 @@ These will be exported to the "fail" directory, categorized by version number. } ``` -#### (3) driverInfo.txt +### 3. Driver Information File -```json -Module Name Display Name Description Driver Type Start Mode State Status Accept Stop Accept Pause Paged Pool Code(Bytes) BSS(Bytes) Link Date Path Init(Bytes) -============ ====================== ====================== ============= ========== ========== ========== =========== ============ ========== ========== ======= ====================== ================================================ ========== -360AntiAttac 360Safe Anti Attack Se 360Safe Anti Attack Se Kernel System Running OK TRUE FALSE 4,096 36,864 0 9/29/2022 3:45:03 PM C:\Windows\system32\Drivers\360AntiAttack64.sys 4,096 -360AntiHacke 360Safe Anti Hacker Se 360Safe Anti Hacker Se Kernel System Running OK TRUE FALSE 4,096 139,264 0 11/27/2023 3:43:37 PM C:\Windows\system32\Drivers\360AntiHacker64.sys 8,192 -360AntiHijac 360Safe Anti Hijack Se 360Safe Anti Hijack Se Kernel System Running OK TRUE FALSE 4,096 73,728 0 5/8/2024 12:19:52 PM C:\Windows\system32\Drivers\360AntiHijack64.sys 4,096 -360AntiSteal 360Safe Anti Steal Fil 360Safe Anti Steal Fil Kernel System Running OK TRUE FALSE 4,096 20,480 0 4/18/2024 3:58:04 PM C:\Windows\system32\Drivers\360AntiSteal64.sys 8,192 -360Box64 360Box mini-filter dri 360Box mini-filter dri File System System Running OK TRUE FALSE 0 225,280 0 8/7/2024 11:50:19 AM C:\Windows\system32\DRIVERS\360Box64.sys 12,288 - -//... +Contains detailed information about all drivers in the system: + +```text +Module Name Display Name Description Driver Type Start Mode State Status +============ ====================== ====================== ============= ========== ========== ========== +360AntiAttac 360Safe Anti Attack Se 360Safe Anti Attack Se Kernel System Running OK +360AntiHacke 360Safe Anti Hacker Se 360Safe Anti Hacker Se Kernel System Running OK +// ...more driver information ``` -#### (4) systeminfo.txt +### 4. System Information File -```json +Complete operating system and hardware configuration information: + +```text Host Name: **** -OS Name: Microsoft Windows 11 Pro -OS Version: 10.0.2*** Build 22*** -OS Manufacturer: Microsoft Corporation -OS Configuration: Standalone Workstation -OS Build Type: Multiprocessor Free -Registered Owner: ****@outlook.com -Registered Organization: -Product ID: ****-80000-***00-A**** -Original Install Date: 11/16/2023, 9:56:28 PM -System Boot Time: 11/26/2024, 9:37:51 PM -System Manufacturer: ASUS -System Model: System Product Name -System Type: x64-based PC -Processor(s): Installed 1 Processor(s). - [01]: Intel** Family * Model *** Stepping * GenuineIntel ~**** Mhz -BIOS Version: American Megatrends Inc. 1402, 4/1/2022 -Windows Directory: C:\Windows -System Directory: C:\Windows\system32 -Boot Device: \Device\Ha*****olume1 -System Locale: zh-cn;Chinese (China) -Input Locale: zh-cn;Chinese (China) -Time Zone: (UTC+08:00) **,**,*******,**** -Total Physical Memory: 16,194 MB -Available Physical Memory: 1,795 MB -Virtual Memory: Max Size: 25,410 MB -Virtual Memory: Available: 9,438 MB -Virtual Memory: In Use: 15,972 MB -Page File Location(s): D:\****file.sys -Domain: WORKGROUP -Logon Server: \\**** -Hotfix(s):: 6 Hotfix(s) Installed. - [01]: KB504**** - [02]: KB502**** - [03]: KB503**** - [04]: KB503**** - [05]: KB504**** - [06]: KB504**** -Network Card(s): 3 NIC(s) Installed. - [01]: Intel(R) Ethernet Connection (**) I***-V - Connection Name: Ethernet - DHCP Enabled: Yes - DHCP Server: 192.168.**.** - IP Address - [01]: 192.168.**.** - [02]: ***::2640:***:****:**** - [02]: VMware Virtual Ethernet Adapter for VMnet1 - Connection Name: VMware Network Adapter VMnet1 - DHCP Enabled: Yes - DHCP Server: 192.168.**.** - IP Address - [01]: 192.168.**.** - [02]: ***::9b3:***,***:**** - [03]: VMware Virtual Ethernet Adapter for VMnet8 - Connection Name: VMware Network Adapter VMnet8 - DHCP Enabled: Yes - DHCP Server: 192.168.**.** - IP Address - [01]: 192.***,***:**** - [02]: fe80::***:***:***:**** -Hyper-V Requirements: A hypervisor has been detected. Features required for Hyper-V will not be displayed. - -//... +OS Name: Microsoft Windows 11 Pro +OS Version: 10.0.*** Build 22*** +System Manufacturer: ASUS +System Model: System Product Name +Processor(s): Intel** Family * Model *** +Total Physical Memory: 16,194 MB +// ...more system information ``` -#### (5) systemlog.evtx +### 5. System Event Log -![](imgs\evtx.png) +System log in Windows Event Viewer format (.evtx file): -### Notes +![System Event Log](imgs/evtx.png) -Bowl provides runtime monitoring capabilities and exports relevant error information. +--- -#### Methods +## Notes and Warnings -| Method | Description | -| -------- | ---------------- | -| Launch() | Start monitoring | +### ⚠️ Important Notes -### 🌼Launch() +1. **Work Mode Selection** + - `Upgrade` mode: Specifically for integration with GeneralUpdate framework, includes internal logic processing + - `Normal` mode: Can be used independently, suitable for monitoring any .NET application -**Launch Function** +2. **Permission Requirements** + - Bowl requires sufficient permissions to generate Dump files and read system information + - It is recommended to run the monitored application with administrator privileges -```c# -Launch(MonitorParameter? monitorParameter = null); -``` +3. **Disk Space** + - Dump files may consume significant disk space (typically 50-200 MB) + - Ensure sufficient available space on the disk where FailDirectory is located -**Parameters** +4. **Dependencies** + - Bowl uses the ProcDump tool to generate Dump files, which is built into the component + - No additional dependencies need to be installed -```c# -public class MonitorParameter -{ - // Directory being monitored - public string TargetPath { get; set; } - - // Directory where captured exception information is exported - public string FailDirectory { get; set; } - - // Backup directory - public string BackupDirectory { get; set; } - - // Name or ID of the process being monitored - public string ProcessNameOrId { get; set; } - - // Dump file name - public string DumpFileName { get; set; } - - // Upgrade package version information (.json) file name - public string FailFileName { get; set; } +### 💡 Best Practices - /// - /// Upgrade: upgrade mode. This mode is primarily used in conjunction with GeneralUpdate for internal use. Please do not modify it arbitrarily when the default mode is activated. - /// Normal: Normal mode, This mode can be used independently to monitor a single program. If the program crashes, it will export the crash information. - /// - public string WorkModel { get; set; } = "Upgrade"; -} -``` +- **Version Management**: Use separate failure directories for each version for easier issue tracking +- **Log Cleanup**: Regularly clean up failure information from old versions to avoid disk space exhaustion +- **Testing**: Verify monitoring functionality in a test environment before production deployment + +--- + +## Applicable Platforms + +| Product | Version | +| --------------- | ----------------- | +| .NET | 5, 6, 7, 8, 9 | +| .NET Framework | 4.6.1 | +| .NET Standard | 2.0 | +| .NET Core | 2.0 | +| ASP.NET | Any | + +--- -### Applicable To +## Related Resources -| Product | Version | -| -------------- | ------------- | -| .NET | 5, 6, 7, 8, 9 | -| .NET Framework | 4.6.1 | -| .NET Standard | 2.0 | -| .NET Core | 2.0 | -| ASP.NET | Any | \ No newline at end of file +- **Example Code**: [View GitHub Examples](https://github.com/GeneralLibrary/GeneralUpdate-Samples/tree/main/src/Bowl) +- **Video Tutorial**: [Watch Bilibili Tutorial](https://www.bilibili.com/video/BV1c8iyYZE7P) +- **Main Repository**: [GeneralUpdate Project](https://github.com/GeneralLibrary/GeneralUpdate) diff --git a/website/i18n/en/docusaurus-plugin-content-docs/current/doc/GeneralUpdate.ClientCore.md b/website/i18n/en/docusaurus-plugin-content-docs/current/doc/GeneralUpdate.ClientCore.md index fbf4086..f63b17c 100644 --- a/website/i18n/en/docusaurus-plugin-content-docs/current/doc/GeneralUpdate.ClientCore.md +++ b/website/i18n/en/docusaurus-plugin-content-docs/current/doc/GeneralUpdate.ClientCore.md @@ -2,131 +2,605 @@ sidebar_position: 4 --- -### Definition +# GeneralUpdate.ClientCore -Namespace: GeneralUpdate.ClientCore +## Component Overview -Assembly: GeneralUpdate.ClientCore.dll +**GeneralUpdate.ClientCore** is one of the core components of the GeneralUpdate framework, providing rich client-side update functionalities. This component runs in the main application and is responsible for checking updates, downloading update packages, validating integrity, and then launching the upgrade assistant (GeneralUpdate.Core) to perform actual file replacement operations upon completion. The design philosophy of ClientCore is to enable the main program to safely check and prepare updates without affecting the current running state. +**Namespace:** `GeneralUpdate.ClientCore` +**Assembly:** `GeneralUpdate.ClientCore.dll` +```csharp +public class GeneralClientBootstrap : AbstractBootstrap +``` -GeneralUpdate.ClientCore is one of the core components, offering a wide range of primary functionalities. Its essence is similar to Core, but it has a different role: ClientCore is used in the main program, where it assists in updates and upgrades and then closes the main program to launch the upgrade assistant. +--- -```c# -public class GeneralClientBootstrap : AbstractBootstrap +## Core Features + +### 1. Multi-Version Download Management +- Support downloading multiple version update packages simultaneously +- Resume download and download speed limiting +- Real-time download progress and statistics + +### 2. Flexible Configuration Options +- Blacklist mechanism (files, formats, directories) +- Custom update strategies and operations +- Support binary differential updates and full updates + +### 3. Comprehensive Event Notifications +- Download progress, completion, and error events +- Support user-defined skip update options +- Exception and error monitoring throughout the process + +### 4. Multi-Platform Support +- Windows, Linux, macOS platform support +- Automatic platform detection and strategy selection + +![Multi Download](imgs/muti_donwload.png) + +--- + +## Quick Start + +### Installation + +Install GeneralUpdate.ClientCore via NuGet: + +```bash +dotnet add package GeneralUpdate.ClientCore ``` +### Initialization and Usage + +The following example demonstrates how to configure and launch update checking in the main program: + +```csharp +using System.Text; +using GeneralUpdate.ClientCore; +using GeneralUpdate.Common.Download; +using GeneralUpdate.Common.Internal; +using GeneralUpdate.Common.Internal.Bootstrap; +using GeneralUpdate.Common.Shared.Object; + +try +{ + Console.WriteLine($"Main program initialization, {DateTime.Now}!"); + + // Configure update parameters + var configinfo = new Configinfo + { + // Update verification API address + UpdateUrl = "http://127.0.0.1:5000/Upgrade/Verification", + // Update report API address + ReportUrl = "http://127.0.0.1:5000/Upgrade/Report", + // Main application name + MainAppName = "ClientSample.exe", + // Upgrade program name + AppName = "UpgradeSample.exe", + // Current client version + ClientVersion = "1.0.0.0", + // Upgrade client version + UpgradeClientVersion = "1.0.0.0", + // Installation path + InstallPath = Thread.GetDomain().BaseDirectory, + // Product ID (for multi-product branch management) + ProductId = "2d974e2a-31e6-4887-9bb1-b4689e98c77a", + // App secret key (for server verification) + AppSecretKey = "dfeb5833-975e-4afb-88f1-6278ee9aeff6" + }; + + // Launch update process + await new GeneralClientBootstrap() + // Listen for download statistics + .AddListenerMultiDownloadStatistics(OnMultiDownloadStatistics) + // Listen for single download completion + .AddListenerMultiDownloadCompleted(OnMultiDownloadCompleted) + // Listen for all downloads completion + .AddListenerMultiAllDownloadCompleted(OnMultiAllDownloadCompleted) + // Listen for download errors + .AddListenerMultiDownloadError(OnMultiDownloadError) + // Listen for exceptions + .AddListenerException(OnException) + // Set configuration + .SetConfig(configinfo) + // Set options + .Option(UpdateOption.DownloadTimeOut, 60) + .Option(UpdateOption.Encoding, Encoding.Default) + // Launch async update + .LaunchAsync(); + + Console.WriteLine($"Main program started, {DateTime.Now}!"); +} +catch (Exception e) +{ + Console.WriteLine(e.Message + "\n" + e.StackTrace); +} + +// Event handler methods +void OnMultiDownloadStatistics(object arg1, MultiDownloadStatisticsEventArgs arg2) +{ + var version = arg2.Version as VersionInfo; + Console.WriteLine($"Download version: {version.Version}, Speed: {arg2.Speed}, " + + $"Remaining time: {arg2.Remaining}, Progress: {arg2.ProgressPercentage}%"); +} + +void OnMultiDownloadCompleted(object arg1, MultiDownloadCompletedEventArgs arg2) +{ + var version = arg2.Version as VersionInfo; + Console.WriteLine(arg2.IsComplated ? + $"Version {version.Version} download complete!" : + $"Version {version.Version} download failed!"); +} + +void OnMultiAllDownloadCompleted(object arg1, MultiAllDownloadCompletedEventArgs arg2) +{ + Console.WriteLine(arg2.IsAllDownloadCompleted ? + "All download tasks completed!" : + $"Download tasks failed! Failed count: {arg2.FailedVersions.Count}"); +} + +void OnMultiDownloadError(object arg1, MultiDownloadErrorEventArgs arg2) +{ + var version = arg2.Version as VersionInfo; + Console.WriteLine($"Version {version.Version} download error: {arg2.Exception}"); +} + +void OnException(object arg1, ExceptionEventArgs arg2) +{ + Console.WriteLine($"Update exception: {arg2.Exception}"); +} +``` +--- -### Example +## Core API Reference -GeneralClientBootstrap uses code examples [[View]](https://github.com/GeneralLibrary/GeneralUpdate-Samples/blob/main/src/Client/Program.cs)。 +### GeneralClientBootstrap Class Methods -![](imgs/muti_donwload.png) +#### LaunchAsync Method +Launch the update process asynchronously. +```csharp +public async Task LaunchAsync() +``` -### Annotations +#### SetConfig Method -GeneralClientBootstrap provides the following capabilities. +Set update configuration information. -#### Properties +```csharp +public GeneralClientBootstrap SetConfig(Configinfo configinfo) +``` -| Properties | Description | -| ------------ | ------------------------------------------------------------ | -| UpdateOption | Enum for update operation configuration settings | -| Configinfo | Client-related parameter class (fields like AppType, AppName, AppSecretKey, etc.) | +#### Option Method -#### Methods +Set update options. -| Method | Description | -| -------------------------------------- | ------------------------------------------------------------ | -| LaunchTaskAsync() | Task-based asynchronous update launch | -| LaunchAsync() | Launch update | -| SetBlacklist() | Set blacklist for update files; pass in if certain files should not be updated. | -| Option() | Set update configuration. | -| Config() | Configure update-related parameters, such as server URL and port, appSecretKey for client identification and product branching. | -| GetOption() | Get update configuration. | -| SetCustomSkipOption() | Allow users to decide whether to proceed with an update in non-mandatory update scenarios. | -| AddCustomOption() | Add an asynchronous custom operation. In theory, any custom operation can be completed. It's recommended to register environment check methods to ensure dependencies and environment are intact after the update. | -| AddListenerMultiAllDownloadCompleted() | Notification for the completion of all download tasks. | -| AddListenerMultiDownloadCompleted() | Event for the completion of single or multiple update package downloads. | -| AddListenerMultiDownloadError() | Listen for errors during each version download | -| AddListenerMultiDownloadStatistics() | Notification for download speed, remaining download time, and current download version info. | -| AddListenerException() | Notification for any issues during the entire update process. | +```csharp +public GeneralClientBootstrap Option(UpdateOption option, object value) +``` -### 🌴Packet +#### SetBlacklist Method -| Property | -| ------------------------------------------------------------ | -| **MainUpdateUrl** string Main update check API address. | -| **AppType** int 1:ClientApp 2:UpdateApp | -| **UpdateUrl** string Update check API address. | -| **AppName** string Name of the application to be launched. | -| **MainAppName** string Name of the main application to be launched. | -| **Format** string Update package file format (default is Zip). | -| **IsUpgradeUpdate** bool Indicates if the update is needed to upgrade the application. | -| **IsMainUpdate** bool Indicates if the main application needs an update. | -| **UpdateLogUrl** string URL for the update log webpage. | -| **UpdateVersions** List Version information that needs updating. | -| **Encoding** Encoding File operation encoding format. | -| **DownloadTimeOut** int Download timeout duration. | -| **AppSecretKey** string Application secret key, agreed upon with the server. | -| **ClientVersion** string Current client version. | -| **LastVersion** string Latest version. | -| **InstallPath** string Installation path (used for update file logic). | -| **TempPath** string Temporary storage path for downloaded files (used for update file logic). | -| **ProcessBase64** string Configuration parameters for the upgrade terminal program. | -| **Platform** string Platform to which the current strategy belongs (Windows\Linux\Mac). | -| **BlackFiles** List Files in the blacklist will be skipped during updates. | -| **BlackFormats** File formats in the blacklist will be skipped during updates. | -| **DriveEnabled** bool Indicates if the driver upgrade feature is enabled. | +Set update blacklist to specify files that should not be updated. +```csharp +public GeneralClientBootstrap SetBlacklist(List blackFiles = null, + List blackFormats = null) +``` + +#### AddListenerMultiDownloadStatistics Method + +Listen for download statistics (speed, progress, remaining time, etc.). + +```csharp +public GeneralClientBootstrap AddListenerMultiDownloadStatistics( + Action callbackAction) +``` +#### AddListenerMultiDownloadCompleted Method -### 🌴Configinfo +Listen for single update package download completion event. -Certainly! Here's the translated content: +```csharp +public GeneralClientBootstrap AddListenerMultiDownloadCompleted( + Action callbackAction) +``` + +#### AddListenerMultiAllDownloadCompleted Method + +Listen for all download tasks completion event. + +```csharp +public GeneralClientBootstrap AddListenerMultiAllDownloadCompleted( + Action callbackAction) +``` -| **Attribute** | Type | Notes | -| -------------------- | ------ | ------------------------------------------------------------ | -| UpdateUrl | string | API address for update checks. | -| ReportUrl | string | API address for reporting update status. | -| AppName | string | Name of the application that needs to be launched. | -| MainAppName | string | Name of the main application that needs to be launched. | -| UpdateLogUrl | string | Web address for the update log. | -| AppSecretKey | string | Application secret key, agreed upon with the server for authentication and branching. | -| ClientVersion | string | Current version number of the client. | -| UpgradeClientVersion | string | Current version number of the upgrade client. | -| InstallPath | string | Installation path (used for update file logic). | -| BlackFiles | List | Files in the blacklist will be skipped during updates. | -| BlackFormats | List | File formats in the blacklist will be skipped during updates. | -| SkipDirectorys | List | Directory paths to be skipped that do not require updates. | -| ProductId | string | Unique ID of the current product branch. | -| Bowl | string | Path to the Bowl monitoring process, which starts after updates to check if the Bowl client starts normally. If an exception occurs after starting, the exception information will be captured. | -| Scheme | string | Used for passing a token in HTTP requests for authentication. | -| Token | string | Token used in HTTP requests for authentication. | -| Script | string | This script assigns permissions to files and is executed on the Linux platform after the update is completed. If permissions need to be assigned before the update, this can be injected via the `GeneralClientBootstrap.AddCustomOption` function in the bootstrap startup class, and the function will be executed prior to the update. | +#### AddListenerMultiDownloadError Method +Listen for download error events. +```csharp +public GeneralClientBootstrap AddListenerMultiDownloadError( + Action callbackAction) +``` + +#### AddListenerException Method + +Listen for all exceptions during the update process. + +```csharp +public GeneralClientBootstrap AddListenerException( + Action callbackAction) +``` + +#### AddCustomOption Method + +Add custom asynchronous operations that can execute custom logic before or after updates. + +```csharp +public GeneralClientBootstrap AddCustomOption(Func customFunc) +``` -### 🍵UpdateOption +#### SetCustomSkipOption Method -| Enum | -| ------------------------------------------------------------ | -| **Format** File format of the update package. | -| **Encoding** Compression encoding. | -| **DownloadTimeOut** Timeout duration (in seconds). If not specified, the default timeout is 30 seconds. | -| **Patch** Whether to enable the binary differential update function, which is enabled by default; if set to `false`, a full overwrite installation will be performed instead. | -| **BackUp** Whether to enable the backup function before update, which is enabled by default; no backup will be performed if set to `false`. | - - - -### Applicable To +Set custom skip options, allowing users to decide whether to continue with the update. + +```csharp +public GeneralClientBootstrap SetCustomSkipOption(Func customSkipFunc) +``` + +--- + +## Configuration Class Details + +### Configinfo Class + +```csharp +public class Configinfo +{ + /// + /// Update check API address + /// + public string UpdateUrl { get; set; } + + /// + /// Update status report API address + /// + public string ReportUrl { get; set; } + + /// + /// Application name to be launched (upgrade program) + /// + public string AppName { get; set; } + + /// + /// Main application name to be launched + /// + public string MainAppName { get; set; } + + /// + /// Update log webpage address + /// + public string UpdateLogUrl { get; set; } + + /// + /// Application secret key, agreed upon with server for authentication and product branching + /// + public string AppSecretKey { get; set; } + + /// + /// Current client version number + /// + public string ClientVersion { get; set; } + + /// + /// Current upgrade client version number + /// + public string UpgradeClientVersion { get; set; } + + /// + /// Installation path (used for update file logic) + /// + public string InstallPath { get; set; } + + /// + /// Blacklist file list, these files will be skipped during updates + /// + public List BlackFiles { get; set; } + + /// + /// Blacklist file format list, files with these formats will be skipped during updates + /// + public List BlackFormats { get; set; } + + /// + /// Directory path list to be skipped that do not require updates + /// + public List SkipDirectorys { get; set; } + + /// + /// Unique ID of the current product branch + /// + public string ProductId { get; set; } + + /// + /// Bowl monitoring process path, starts after updates to check if the client starts normally + /// + public string Bowl { get; set; } + + /// + /// Scheme used for passing token in HTTP requests (e.g., Bearer) + /// + public string Scheme { get; set; } + + /// + /// Token used for authentication in HTTP requests + /// + public string Token { get; set; } + + /// + /// Script for Linux platform to assign permissions to files after update completion + /// + public string Script { get; set; } +} +``` + +### UpdateOption Enum + +```csharp +public enum UpdateOption +{ + /// + /// Update package file format (default is Zip) + /// + Format, + + /// + /// Compression encoding format + /// + Encoding, + + /// + /// Download timeout duration (seconds). Default is 30 seconds if not specified + /// + DownloadTimeOut, + + /// + /// Whether to enable binary differential update function, enabled by default; + /// if set to false, full overwrite installation will be performed + /// + Patch, + + /// + /// Whether to enable backup function before update, enabled by default; + /// if set to false, no backup will be performed + /// + BackUp +} +``` + +--- + +## Practical Usage Examples + +### Example 1: Basic Update Process + +```csharp +using GeneralUpdate.ClientCore; +using GeneralUpdate.Common.Internal; + +var config = new Configinfo +{ + UpdateUrl = "http://your-server.com/api/update/check", + ReportUrl = "http://your-server.com/api/update/report", + MainAppName = "MyApp.exe", + AppName = "Updater.exe", + ClientVersion = "1.0.0.0", + UpgradeClientVersion = "1.0.0.0", + InstallPath = AppDomain.CurrentDomain.BaseDirectory, + ProductId = "your-product-id", + AppSecretKey = "your-secret-key" +}; + +await new GeneralClientBootstrap() + .SetConfig(config) + .AddListenerException((sender, args) => + { + Console.WriteLine($"Update exception: {args.Exception.Message}"); + }) + .LaunchAsync(); +``` + +### Example 2: Update with Blacklist + +```csharp +using GeneralUpdate.ClientCore; +using GeneralUpdate.Common.Internal; + +var config = new Configinfo +{ + UpdateUrl = "http://your-server.com/api/update/check", + ClientVersion = "1.0.0.0", + InstallPath = AppDomain.CurrentDomain.BaseDirectory, + // Blacklist configuration + BlackFiles = new List { "config.json", "userdata.db" }, + BlackFormats = new List { ".log", ".cache" }, + SkipDirectorys = new List { "logs", "temp" } +}; + +await new GeneralClientBootstrap() + .SetConfig(config) + .LaunchAsync(); +``` + +### Example 3: Custom Update Options + +```csharp +using System.Text; +using GeneralUpdate.ClientCore; +using GeneralUpdate.Common.Internal; +using GeneralUpdate.Common.Internal.Bootstrap; + +var config = new Configinfo +{ + UpdateUrl = "http://your-server.com/api/update/check", + ClientVersion = "1.0.0.0", + InstallPath = AppDomain.CurrentDomain.BaseDirectory +}; + +await new GeneralClientBootstrap() + .SetConfig(config) + // Set download timeout + .Option(UpdateOption.DownloadTimeOut, 120) + // Set encoding format + .Option(UpdateOption.Encoding, Encoding.UTF8) + // Enable binary differential update + .Option(UpdateOption.Patch, true) + // Enable backup + .Option(UpdateOption.BackUp, true) + .LaunchAsync(); +``` + +### Example 4: Complete Event Listening + +```csharp +using GeneralUpdate.ClientCore; +using GeneralUpdate.Common.Download; +using GeneralUpdate.Common.Internal; +using GeneralUpdate.Common.Shared.Object; + +var config = new Configinfo +{ + UpdateUrl = "http://your-server.com/api/update/check", + ClientVersion = "1.0.0.0", + InstallPath = AppDomain.CurrentDomain.BaseDirectory +}; + +await new GeneralClientBootstrap() + .SetConfig(config) + // Download statistics + .AddListenerMultiDownloadStatistics((sender, args) => + { + var version = args.Version as VersionInfo; + Console.WriteLine($"[{version.Version}] Progress: {args.ProgressPercentage}% | " + + $"Speed: {args.Speed} | Remaining: {args.Remaining}"); + }) + // Single download completed + .AddListenerMultiDownloadCompleted((sender, args) => + { + var version = args.Version as VersionInfo; + if (args.IsComplated) + Console.WriteLine($"✓ Version {version.Version} download succeeded"); + else + Console.WriteLine($"✗ Version {version.Version} download failed"); + }) + // All downloads completed + .AddListenerMultiAllDownloadCompleted((sender, args) => + { + if (args.IsAllDownloadCompleted) + Console.WriteLine("✓ All update packages downloaded, preparing installation..."); + else + Console.WriteLine($"✗ Download failed, {args.FailedVersions.Count} versions failed"); + }) + // Download error + .AddListenerMultiDownloadError((sender, args) => + { + var version = args.Version as VersionInfo; + Console.WriteLine($"✗ Version {version.Version} download error: {args.Exception.Message}"); + }) + // Exception handling + .AddListenerException((sender, args) => + { + Console.WriteLine($"⚠ Update exception: {args.Exception.Message}\n{args.Exception.StackTrace}"); + }) + .LaunchAsync(); +``` + +### Example 5: Custom Operations and Skip Options + +```csharp +using GeneralUpdate.ClientCore; +using GeneralUpdate.Common.Internal; + +var config = new Configinfo +{ + UpdateUrl = "http://your-server.com/api/update/check", + ClientVersion = "1.0.0.0", + InstallPath = AppDomain.CurrentDomain.BaseDirectory +}; + +await new GeneralClientBootstrap() + .SetConfig(config) + // Add custom operation (check environment before update) + .AddCustomOption(async () => + { + Console.WriteLine("Checking runtime environment..."); + await Task.Delay(1000); + // Check disk space, dependencies, etc. + Console.WriteLine("Environment check completed"); + }) + // Set user skip option + .SetCustomSkipOption(() => + { + Console.WriteLine("New version found, update now? (y/n)"); + var input = Console.ReadLine(); + return input?.ToLower() == "y"; + }) + .LaunchAsync(); +``` + +--- + +## Notes and Warnings + +### ⚠️ Important Notes + +1. **Version Number Format** + - Version numbers must follow semantic versioning specification (e.g., 1.0.0.0) + - Ensure version number format is consistent between client and server + +2. **Network Connection** + - Ensure update server address is accessible + - Recommend implementing retry mechanism to handle network fluctuations + +3. **Process Management** + - The update process will close the main program and launch the upgrade assistant + - Ensure all user data is saved before executing the update + +4. **Permission Requirements** + - Administrator privileges may be required on Windows to replace files + - Appropriate file system permissions are required on Linux/macOS + +5. **Blacklist Usage** + - Files and directories in the blacklist will not be updated + - Commonly used to protect configuration files, user data, etc. + +### 💡 Best Practices + +- **Backup Strategy**: Always enable the BackUp option to allow rollback in case of update failure +- **Differential Update**: Enable the Patch option to reduce download size and update time +- **Error Handling**: Implement complete exception listening and error handling logic +- **User Experience**: Prompt users before updating and allow them to choose update timing +- **Testing**: Thoroughly test the update process before production deployment + +--- + +## Applicable Platforms | Product | Version | | -------------- | ---------------- | -| .NET | 5, 6, 7, 8, 9,10 | -| .NET Framework | 4.6.1 | -| .NET Standard | 2.0 | -| .NET Core | 2.0 | +| .NET | 5, 6, 7, 8, 9, 10 | +| .NET Framework | 4.6.1 | +| .NET Standard | 2.0 | +| .NET Core | 2.0 | + +--- + +## Related Resources + +- **Sample Code**: [View GitHub Examples](https://github.com/GeneralLibrary/GeneralUpdate-Samples/blob/main/src/Client/Program.cs) +- **Main Repository**: [GeneralUpdate Project](https://github.com/GeneralLibrary/GeneralUpdate) diff --git a/website/i18n/en/docusaurus-plugin-content-docs/current/doc/GeneralUpdate.Core.md b/website/i18n/en/docusaurus-plugin-content-docs/current/doc/GeneralUpdate.Core.md index 31d5db9..882ee84 100644 --- a/website/i18n/en/docusaurus-plugin-content-docs/current/doc/GeneralUpdate.Core.md +++ b/website/i18n/en/docusaurus-plugin-content-docs/current/doc/GeneralUpdate.Core.md @@ -2,77 +2,564 @@ sidebar_position: 5 --- -### Definition +# GeneralUpdate.Core -Namespace: GeneralUpdate.Core +## Component Overview -Assembly: GeneralUpdate.Core.dll +**GeneralUpdate.Core** is one of the most essential components of the GeneralUpdate framework, providing complete upgrade execution capabilities. Unlike ClientCore, the Core component runs as an independent upgrade assistant program and is responsible for performing actual file replacement, version upgrades, and system update operations after the main program closes. Through process startup and parameter passing, Core receives update instructions from ClientCore and safely completes the main program's upgrade tasks. +**Namespace:** `GeneralUpdate.Core` +**Assembly:** `GeneralUpdate.Core.dll` +```csharp +public class GeneralUpdateBootstrap : AbstractBootstrap +``` + +--- -GeneralUpdate.Core is one of the most essential components, providing a wide range of primary functionalities. Once the main program upgrade operation is completed, this component is invoked through process startup and parameter passing to complete the main program upgrade operation. (Main responsibility is updating the main program) +## Core Features -```c# -public class GeneralUpdateBootstrap : AbstractBootstrap +### 1. File Replacement and Version Management +- Safe file replacement mechanism to avoid file locking issues +- Support multi-version incremental upgrades +- Automatic handling of file dependencies + +### 2. Driver Upgrade Support +- Optional driver upgrade functionality +- Field mapping table configuration +- Safe driver installation process + +### 3. Comprehensive Event Notifications +- Real-time download progress monitoring +- Multi-version download management +- Complete exception and error capture + +### 4. Cross-Platform Support +- Full support for Windows, Linux, macOS platforms +- Automatic platform detection and strategy adaptation + +![Multi Download](imgs/muti_donwload.png) + +--- + +## Quick Start + +### Installation + +Install GeneralUpdate.Core via NuGet: + +```bash +dotnet add package GeneralUpdate.Core +``` + +### Initialization and Usage + +The following example demonstrates how to configure and launch the upgrade process in the upgrade assistant program: + +```csharp +using GeneralUpdate.Common.Download; +using GeneralUpdate.Common.Internal; +using GeneralUpdate.Common.Shared.Object; +using GeneralUpdate.Core; + +try +{ + Console.WriteLine($"Upgrade program initialization, {DateTime.Now}!"); + Console.WriteLine("Current directory: " + Thread.GetDomain().BaseDirectory); + + // Launch upgrade process + await new GeneralUpdateBootstrap() + // Listen for download statistics + .AddListenerMultiDownloadStatistics(OnMultiDownloadStatistics) + // Listen for single download completion + .AddListenerMultiDownloadCompleted(OnMultiDownloadCompleted) + // Listen for all downloads completion + .AddListenerMultiAllDownloadCompleted(OnMultiAllDownloadCompleted) + // Listen for download errors + .AddListenerMultiDownloadError(OnMultiDownloadError) + // Listen for exceptions + .AddListenerException(OnException) + // Launch async upgrade + .LaunchAsync(); + + Console.WriteLine($"Upgrade program started, {DateTime.Now}!"); + await Task.Delay(2000); +} +catch (Exception e) +{ + Console.WriteLine(e.Message + "\n" + e.StackTrace); +} + +// Event handler methods +void OnMultiDownloadStatistics(object arg1, MultiDownloadStatisticsEventArgs arg2) +{ + var version = arg2.Version as VersionInfo; + Console.WriteLine($"Current download version: {version.Version}, Download speed: {arg2.Speed}, " + + $"Remaining time: {arg2.Remaining}, Progress: {arg2.ProgressPercentage}%"); +} + +void OnMultiDownloadCompleted(object arg1, MultiDownloadCompletedEventArgs arg2) +{ + var version = arg2.Version as VersionInfo; + Console.WriteLine(arg2.IsComplated ? + $"Version {version.Version} download complete!" : + $"Version {version.Version} download failed!"); +} + +void OnMultiAllDownloadCompleted(object arg1, MultiAllDownloadCompletedEventArgs arg2) +{ + Console.WriteLine(arg2.IsAllDownloadCompleted ? + "All download tasks completed!" : + $"Download tasks failed! Failed count: {arg2.FailedVersions.Count}"); +} + +void OnMultiDownloadError(object arg1, MultiDownloadErrorEventArgs arg2) +{ + var version = arg2.Version as VersionInfo; + Console.WriteLine($"Version {version.Version} download error: {arg2.Exception}"); +} + +void OnException(object arg1, ExceptionEventArgs arg2) +{ + Console.WriteLine($"Upgrade exception: {arg2.Exception}"); +} +``` + +--- + +## Core API Reference + +### GeneralUpdateBootstrap Class Methods + +#### LaunchAsync Method + +Launch the upgrade process asynchronously. + +```csharp +public async Task LaunchAsync() +``` + +**Return Value:** +- Returns the current GeneralUpdateBootstrap instance, supporting method chaining + +#### Option Method + +Set upgrade options. + +```csharp +public GeneralUpdateBootstrap Option(UpdateOption option, object value) +``` + +**Parameters:** +- `option`: Upgrade option enum +- `value`: Option value + +**Example:** +```csharp +.Option(UpdateOption.Drive, true) // Enable driver upgrade +``` + +#### AddListenerMultiDownloadStatistics Method + +Listen for download statistics (speed, progress, remaining time, etc.). + +```csharp +public GeneralUpdateBootstrap AddListenerMultiDownloadStatistics( + Action callbackAction) +``` + +#### AddListenerMultiDownloadCompleted Method + +Listen for single update package download completion event. + +```csharp +public GeneralUpdateBootstrap AddListenerMultiDownloadCompleted( + Action callbackAction) +``` + +#### AddListenerMultiAllDownloadCompleted Method + +Listen for all version downloads completion event. + +```csharp +public GeneralUpdateBootstrap AddListenerMultiAllDownloadCompleted( + Action callbackAction) +``` + +#### AddListenerMultiDownloadError Method + +Listen for download error events for each version. + +```csharp +public GeneralUpdateBootstrap AddListenerMultiDownloadError( + Action callbackAction) +``` + +#### AddListenerException Method + +Listen for all internal exceptions in the upgrade component. + +```csharp +public GeneralUpdateBootstrap AddListenerException( + Action callbackAction) +``` + +#### SetFieldMappings Method + +Set field mapping table for parsing driver package information. + +```csharp +public GeneralUpdateBootstrap SetFieldMappings(Dictionary fieldMappings) +``` + +**Parameters:** +- `fieldMappings`: Field mapping dictionary, key is English field name, value is localized field name + +--- + +## Configuration Class Details + +### UpdateOption Enum + +```csharp +public enum UpdateOption +{ + /// + /// Whether to enable driver upgrade functionality + /// + Drive +} ``` +### Packet Class + +Upgrade package information class, passed from ClientCore to Core via parameters: + +```csharp +public class Packet +{ + /// + /// Main update check API address + /// + public string MainUpdateUrl { get; set; } + + /// + /// Application type: 1=ClientApp, 2=UpdateApp + /// + public int AppType { get; set; } + + /// + /// Update check API address + /// + public string UpdateUrl { get; set; } + + /// + /// Name of the application to be launched + /// + public string AppName { get; set; } + + /// + /// Main application name + /// + public string MainAppName { get; set; } + + /// + /// Update package file format (default is Zip) + /// + public string Format { get; set; } + + /// + /// Indicates if the update application needs to be upgraded + /// + public bool IsUpgradeUpdate { get; set; } + + /// + /// Indicates if the main application needs to be updated + /// + public bool IsMainUpdate { get; set; } + + /// + /// Update log webpage URL + /// + public string UpdateLogUrl { get; set; } + + /// + /// List of version information that needs updating + /// + public List UpdateVersions { get; set; } + + /// + /// File operation encoding format + /// + public Encoding Encoding { get; set; } + + /// + /// Download timeout duration (seconds) + /// + public int DownloadTimeOut { get; set; } + + /// + /// Application secret key, agreed upon with the server + /// + public string AppSecretKey { get; set; } + + /// + /// Current client version + /// + public string ClientVersion { get; set; } + + /// + /// Latest version + /// + public string LastVersion { get; set; } + + /// + /// Installation path (used for update file logic) + /// + public string InstallPath { get; set; } + + /// + /// Temporary storage path for downloaded files + /// + public string TempPath { get; set; } + + /// + /// Configuration parameters for the upgrade terminal program (Base64 encoded) + /// + public string ProcessBase64 { get; set; } + + /// + /// Platform to which the current strategy belongs (Windows/Linux/Mac) + /// + public string Platform { get; set; } + + /// + /// Files in the blacklist + /// + public List BlackFiles { get; set; } + + /// + /// File formats in the blacklist + /// + public List BlackFormats { get; set; } + + /// + /// Indicates if the driver upgrade feature is enabled + /// + public bool DriveEnabled { get; set; } +} +``` +--- -### Example +## Practical Usage Examples -GeneralUpdateBootstrap uses code examples [[View]](https://github.com/GeneralLibrary/GeneralUpdate-Samples/blob/main/src/Upgrade/Program.cs)。 +### Example 1: Basic Upgrade Process -![](imgs/muti_donwload.png) +```csharp +using GeneralUpdate.Common.Download; +using GeneralUpdate.Common.Internal; +using GeneralUpdate.Common.Shared.Object; +using GeneralUpdate.Core; +try +{ + Console.WriteLine("Upgrade program initialization..."); + + // Launch upgrade process + await new GeneralUpdateBootstrap() + .AddListenerMultiDownloadStatistics((sender, args) => + { + var version = args.Version as VersionInfo; + Console.WriteLine($"[{version.Version}] Download progress: {args.ProgressPercentage}%"); + }) + .AddListenerException((sender, args) => + { + Console.WriteLine($"Upgrade exception: {args.Exception.Message}"); + }) + .LaunchAsync(); + + Console.WriteLine("Upgrade complete!"); +} +catch (Exception e) +{ + Console.WriteLine($"Upgrade failed: {e.Message}"); +} +``` +### Example 2: Enable Driver Upgrade -### Annotations +```csharp +using GeneralUpdate.Core; +using GeneralUpdate.Common.Internal.Bootstrap; -GeneralUpdateBootstrap provides the following capabilities. +// Chinese field mapping table +var fieldMappingsCN = new Dictionary +{ + { "DriverName", "驱动名称" }, + { "DriverVersion", "驱动版本" }, + { "DriverDescription", "驱动描述" }, + { "InstallPath", "安装路径" } +}; -#### Constructors +await new GeneralUpdateBootstrap() + // Set field mappings + .SetFieldMappings(fieldMappingsCN) + // Enable driver update + .Option(UpdateOption.Drive, true) + .AddListenerException((sender, args) => + { + Console.WriteLine($"Upgrade exception: {args.Exception.Message}"); + }) + .LaunchAsync(); +``` -| Constructors | Description | -| ------------------------ | ------------------------------------------ | -| GeneralUpdateBootstrap() | Current GeneralUpdateBootstrap constructor | -| base:AbstractBootstrap() | Parent class AbstractBootstrap constructor | +### Example 3: Complete Event Listening -#### Properties +```csharp +using GeneralUpdate.Core; +using GeneralUpdate.Common.Download; +using GeneralUpdate.Common.Shared.Object; -| Properties | Description | -| ------------ | ------------------------------------------ | -| Packet | Update package information | -| UpdateOption | Update operation configuration enumeration | +await new GeneralUpdateBootstrap() + // Download statistics + .AddListenerMultiDownloadStatistics((sender, args) => + { + var version = args.Version as VersionInfo; + Console.WriteLine($"[{version.Version}]"); + Console.WriteLine($" Speed: {args.Speed}"); + Console.WriteLine($" Progress: {args.ProgressPercentage}%"); + Console.WriteLine($" Downloaded: {args.BytesReceived} / {args.TotalBytesToReceive}"); + Console.WriteLine($" Remaining time: {args.Remaining}"); + }) + // Single download completed + .AddListenerMultiDownloadCompleted((sender, args) => + { + var version = args.Version as VersionInfo; + string status = args.IsComplated ? "✓ Success" : "✗ Failed"; + Console.WriteLine($"Version {version.Version} download {status}"); + }) + // All downloads completed + .AddListenerMultiAllDownloadCompleted((sender, args) => + { + if (args.IsAllDownloadCompleted) + { + Console.WriteLine("✓ All versions downloaded, starting installation..."); + } + else + { + Console.WriteLine($"✗ Download failed, {args.FailedVersions.Count} versions failed:"); + foreach (var version in args.FailedVersions) + { + Console.WriteLine($" - {version}"); + } + } + }) + // Download error + .AddListenerMultiDownloadError((sender, args) => + { + var version = args.Version as VersionInfo; + Console.WriteLine($"✗ Version {version.Version} error:"); + Console.WriteLine($" {args.Exception.Message}"); + }) + // Exception handling + .AddListenerException((sender, args) => + { + Console.WriteLine("⚠ Upgrade process exception:"); + Console.WriteLine($" Error: {args.Exception.Message}"); + Console.WriteLine($" Stack: {args.Exception.StackTrace}"); + }) + .LaunchAsync(); +``` -#### Methods +### Example 4: Custom Upgrade Process -| Method | Description | -| -------------------------------------- | ---------------------------------------------------------- | -| LaunchTaskAsync() | Asynchronously launch update with Task | -| LaunchAsync() | Launch update | -| Option() | Set update configuration | -| GetOption() | Get update configuration | -| AddListenerMultiAllDownloadCompleted() | Listen for completion of all version downloads | -| AddListenerMultiDownloadCompleted() | Listen for completion of each version download | -| AddListenerMultiDownloadError() | Listen for download errors for each version | -| AddListenerMultiDownloadStatistics() | Listen for download statistics/progress for each version | -| AddListenerException() | Listen for all internal exceptions in the update component | +```csharp +using GeneralUpdate.Core; +using GeneralUpdate.Common.Download; +using GeneralUpdate.Common.Shared.Object; +// Record upgrade start time +var startTime = DateTime.Now; +var downloadedVersions = new List(); +await new GeneralUpdateBootstrap() + .AddListenerMultiDownloadCompleted((sender, args) => + { + if (args.IsComplated) + { + var version = args.Version as VersionInfo; + downloadedVersions.Add(version.Version); + } + }) + .AddListenerMultiAllDownloadCompleted((sender, args) => + { + if (args.IsAllDownloadCompleted) + { + var duration = DateTime.Now - startTime; + Console.WriteLine($"Upgrade complete!"); + Console.WriteLine($"Total time: {duration.TotalSeconds:F2} seconds"); + Console.WriteLine($"Updated versions: {string.Join(", ", downloadedVersions)}"); + } + }) + .AddListenerException((sender, args) => + { + // Log to file + File.AppendAllText("upgrade_error.log", + $"[{DateTime.Now}] {args.Exception}\n"); + }) + .LaunchAsync(); +``` -### 🍵UpdateOption +--- -**Enumeration** +## Notes and Warnings -**Drive** Whether to enable driver upgrade functionality. +### ⚠️ Important Notes +1. **Process Isolation** + - Core must run as an independent process, cannot be called directly in the main program + - The main program must be completely closed during upgrade, otherwise file replacement will fail +2. **Parameter Passing** + - ClientCore passes configuration to Core via Base64 encoded parameters + - Ensure parameters are not truncated or corrupted during passing -### Applicable to +3. **File Permissions** + - Administrator privileges may be required on Windows to replace files in system directories + - Appropriate file system permissions are required on Linux/macOS -| Product | Versions | +4. **Driver Upgrade** + - Driver upgrade functionality requires system-level permissions + - Recommended to thoroughly validate in test environment before use + +5. **Rollback Mechanism** + - Core does not directly provide rollback functionality, but backup files are preserved + - For rollback, use ClientCore's backup functionality + +### 💡 Best Practices + +- **Logging**: Implement complete exception listening to record all issues during the upgrade process +- **Timeout Settings**: Set download timeout appropriately based on network environment +- **Progress Feedback**: Display upgrade progress to users to improve user experience +- **Error Handling**: Provide clear error messages and solutions when upgrade fails +- **Testing**: Test upgrade process stability under various network conditions + +--- + +## Applicable Platforms + +| Product | Version | | -------------- | ------------- | -| .NET | 5, 6, 7, 8, 9 | -| .NET Framework | 4.6.1 | -| .NET Standard | 2.0 | -| .NET Core | 2.0 | +| .NET | 5, 6, 7, 8, 9 | +| .NET Framework | 4.6.1 | +| .NET Standard | 2.0 | +| .NET Core | 2.0 | + +--- + +## Related Resources + +- **Sample Code**: [View GitHub Examples](https://github.com/GeneralLibrary/GeneralUpdate-Samples/blob/main/src/Upgrade/Program.cs) +- **Main Repository**: [GeneralUpdate Project](https://github.com/GeneralLibrary/GeneralUpdate) +- **Related Components**: [GeneralUpdate.ClientCore](./GeneralUpdate.ClientCore.md) | [GeneralUpdate.Bowl](./GeneralUpdate.Bowl.md) diff --git a/website/i18n/en/docusaurus-plugin-content-docs/current/doc/GeneralUpdate.Differential.md b/website/i18n/en/docusaurus-plugin-content-docs/current/doc/GeneralUpdate.Differential.md index b7f8576..4132a1a 100644 --- a/website/i18n/en/docusaurus-plugin-content-docs/current/doc/GeneralUpdate.Differential.md +++ b/website/i18n/en/docusaurus-plugin-content-docs/current/doc/GeneralUpdate.Differential.md @@ -2,100 +2,448 @@ sidebar_position: 6 --- -### Definition +# GeneralUpdate.Differential -Namespace: GeneralUpdate.Differential +## Component Overview -Assembly: GeneralUpdate.Core.dll +**GeneralUpdate.Differential** is the core component responsible for binary differential updates in the GeneralUpdate framework. This component provides powerful differential algorithms that can accurately identify file changes between two versions, generate efficient incremental patch packages, and support patch restoration operations. By using differential updates, you can significantly reduce update package size and download time, making it particularly suitable for scenarios with frequent update releases. +**Namespace:** `GeneralUpdate.Differential` +**Assembly:** `GeneralUpdate.Core.dll` +```csharp +public sealed class DifferentialCore +``` -This component provides capabilities for generating binary differential patch files (algorithm), file increment identification (version differences), deleted file identification (version differences), blacklisting, patch restoration, and more. +--- -```c# -public sealed class DifferentialCore +## Core Features + +### 1. Incremental Identification +- Accurately identify added, modified, and deleted files +- Intelligent file version comparison +- Support skipping specified files and formats + +### 2. Binary Patch Generation +- Efficient binary differential algorithm +- Minimize patch file size +- Fast patch generation speed + +### 3. Patch Restoration +- Safe patch application process +- Automatic handling of file dependencies +- Integrity verification mechanism + +### 4. Blacklist Support +- File-level blacklist +- Format-level blacklist +- Flexible filtering rules + +--- + +## Quick Start + +### Installation + +Install GeneralUpdate.Differential via NuGet (included in Core package): + +```bash +dotnet add package GeneralUpdate.Core +``` + +### Initialization and Usage + +The following example demonstrates how to use DifferentialCore for incremental identification and patch operations: + +```csharp +using GeneralUpdate.Differential; + +// Identify increments and generate binary patches +var sourcePath = @"D:\packet\app"; // Old version path +var targetPath = @"D:\packet\release"; // New version path +var patchPath = @"D:\packet\patch"; // Patch output path + +await DifferentialCore.Instance?.Clean(sourcePath, targetPath, patchPath); + +// Apply patches (restoration) +await DifferentialCore.Instance?.Dirty(sourcePath, patchPath); +``` + +--- + +## Core API Reference + +### DifferentialCore Class + +#### Instance Property + +Get the singleton instance of DifferentialCore. + +```csharp +public static DifferentialCore Instance { get; } +``` + +#### Clean Method + +Perform incremental identification, deleted file identification, and generate binary patch files. + +**Method Signature:** + +```csharp +public async Task Clean(string sourcePath, string targetPath, string patchPath = null) +``` + +**Parameters:** +- `sourcePath`: Path to the old version folder +- `targetPath`: Path to the new version folder +- `patchPath`: Directory to store discovered incremental update files (optional) + +**Function Description:** +1. Compare sourcePath and targetPath directories +2. Identify added, modified, and deleted files +3. Generate binary differential patches for modified files +4. Save patches and added files to patchPath + +**Example:** +```csharp +// Generate patch package from v1.0.0 to v1.1.0 +var source = @"D:\MyApp\v1.0.0"; +var target = @"D:\MyApp\v1.1.0"; +var patch = @"D:\MyApp\patches\v1.1.0"; + +await DifferentialCore.Instance.Clean(source, target, patch); +// Result: patch directory contains all necessary incremental update files ``` +#### Dirty Method +Apply patches to update old version files to the new version. -### Example +**Method Signature:** + +```csharp +public async Task Dirty(string appPath, string patchPath) +``` -The following example defines methods for increment identification, generating binary patches, patch restoration, and setting blacklists. The packaging tool in the GeneralUpdate.Tools project also strongly depends on this component. +**Parameters:** +- `appPath`: Client application directory (current version) +- `patchPath`: Path to the patch files + +**Function Description:** +1. Read patch files from patchPath +2. Apply patches to corresponding files in appPath +3. Handle copying of added files +4. Handle removal of deleted files + +**Example:** +```csharp +// Apply patches to current application +var appDir = AppDomain.CurrentDomain.BaseDirectory; +var patchDir = Path.Combine(appDir, "temp", "patches"); + +await DifferentialCore.Instance.Dirty(appDir, patchDir); +// Result: application updated to new version +``` -```c# -// Increment identification, generating binary patches -public async Task TestDifferentialClean() +--- + +## Practical Usage Examples + +### Example 1: Basic Patch Generation + +```csharp +using GeneralUpdate.Differential; + +public async Task GeneratePatchAsync() { - // Path to the previous version's client folder - var path1 = "D:\\packet\\source"; - // Path to the latest version's client folder - var path2 = "D:\\packet\\target"; - // Path for generating patch files - var path3 = "D:\\packet\\patchs"; - await DifferentialCore.Instance.Clean(path1, path2, path3); + try + { + // Version paths + var oldVersion = @"D:\MyApp\1.0.0"; + var newVersion = @"D:\MyApp\1.0.1"; + var patchOutput = @"D:\MyApp\patches\1.0.1"; + + Console.WriteLine("Starting patch generation..."); + + // Generate patches + await DifferentialCore.Instance.Clean(oldVersion, newVersion, patchOutput); + + Console.WriteLine($"Patch generation complete! Output directory: {patchOutput}"); + + // Display patch information + var patchFiles = Directory.GetFiles(patchOutput, "*.*", SearchOption.AllDirectories); + Console.WriteLine($"Generated {patchFiles.Length} patch files"); + + long totalSize = patchFiles.Sum(f => new FileInfo(f).Length); + Console.WriteLine($"Total patch size: {totalSize / 1024.0:F2} KB"); + } + catch (Exception ex) + { + Console.WriteLine($"Patch generation failed: {ex.Message}"); + } } +``` + +### Example 2: Apply Patches + +```csharp +using GeneralUpdate.Differential; -// Patch restoration -public async Task TestDifferentialDirty() +public async Task ApplyPatchAsync() { - // Path to the current version's client folder - var path1 = "D:\\packet\\source"; - // Path for generating patch files - var path2 = "D:\\packet\\patchs"; - await DifferentialCore.Instance.Dirty(path1, path2); + try + { + // Application directory + var appDirectory = @"D:\MyApp\current"; + // Patch directory + var patchDirectory = @"D:\MyApp\patches\1.0.1"; + + Console.WriteLine("Starting patch application..."); + + // Verify patch exists + if (!Directory.Exists(patchDirectory)) + { + throw new DirectoryNotFoundException($"Patch directory not found: {patchDirectory}"); + } + + // Apply patches + await DifferentialCore.Instance.Dirty(appDirectory, patchDirectory); + + Console.WriteLine("Patch applied successfully! Application updated to new version."); + } + catch (Exception ex) + { + Console.WriteLine($"Patch application failed: {ex.Message}"); + } } ``` -### Annotations +### Example 3: Complete Patch Workflow -DifferentialCore provides capabilities for increment identification, generating binary patches, patch restoration, and setting blacklists. +```csharp +using GeneralUpdate.Differential; +using System.IO.Compression; -#### Methods +public class PatchManager +{ + // Generate and package patches + public async Task CreatePatchPackageAsync( + string oldVersionPath, + string newVersionPath, + string outputPath) + { + try + { + // 1. Generate patch files + var tempPatchDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempPatchDir); + + Console.WriteLine($"Generating patches..."); + await DifferentialCore.Instance.Clean(oldVersionPath, newVersionPath, tempPatchDir); + + // 2. Compress patch files + var patchZipPath = Path.Combine(outputPath, "patch_1.0.1.zip"); + Console.WriteLine($"Packaging patches..."); + + if (File.Exists(patchZipPath)) + File.Delete(patchZipPath); + + ZipFile.CreateFromDirectory(tempPatchDir, patchZipPath, + CompressionLevel.Optimal, false); + + // 3. Clean up temp files + Directory.Delete(tempPatchDir, true); + + var patchSize = new FileInfo(patchZipPath).Length; + Console.WriteLine($"Patch package created successfully: {patchZipPath}"); + Console.WriteLine($"Patch package size: {patchSize / 1024.0:F2} KB"); + + return patchZipPath; + } + catch (Exception ex) + { + Console.WriteLine($"Patch package creation failed: {ex.Message}"); + throw; + } + } + + // Extract and apply patches + public async Task ApplyPatchPackageAsync(string appPath, string patchZipPath) + { + try + { + // 1. Extract patch package + var tempExtractDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempExtractDir); + + Console.WriteLine($"Extracting patch package..."); + ZipFile.ExtractToDirectory(patchZipPath, tempExtractDir); + + // 2. Apply patches + Console.WriteLine($"Applying patches..."); + await DifferentialCore.Instance.Dirty(appPath, tempExtractDir); + + // 3. Clean up temp files + Directory.Delete(tempExtractDir, true); + + Console.WriteLine($"Patch applied successfully!"); + } + catch (Exception ex) + { + Console.WriteLine($"Patch package application failed: {ex.Message}"); + throw; + } + } +} + +// Usage example +var manager = new PatchManager(); + +// Create patch package +var patchZip = await manager.CreatePatchPackageAsync( + @"D:\MyApp\1.0.0", + @"D:\MyApp\1.0.1", + @"D:\MyApp\releases" +); + +// Apply patch package +await manager.ApplyPatchPackageAsync( + @"D:\MyApp\current", + patchZip +); +``` -| Name | Type | Description | -| ------- | ------ | ------------------------------------------------------------ | -| Clean() | Method | Increment identification, deleted file identification, and generating binary patch files | -| Dirty() | Method | Patch restoration (applying patches to old client files to achieve updates) | +### Example 4: Patch Operations with Progress Display -### 🌼Clean() +```csharp +using GeneralUpdate.Differential; -**Method** +public class ProgressivePatchManager +{ + public async Task GeneratePatchWithProgressAsync( + string sourcePath, + string targetPath, + string patchPath, + IProgress progress) + { + try + { + progress?.Report("Starting file difference scan..."); + + // In actual scenarios, you can add progress reports before and after Clean + await DifferentialCore.Instance.Clean(sourcePath, targetPath, patchPath); + + progress?.Report("Patch generation complete!"); + + // Statistics + var files = Directory.GetFiles(patchPath, "*.*", SearchOption.AllDirectories); + progress?.Report($"Generated {files.Length} patch files"); + } + catch (Exception ex) + { + progress?.Report($"Error: {ex.Message}"); + throw; + } + } + + public async Task ApplyPatchWithProgressAsync( + string appPath, + string patchPath, + IProgress progress) + { + try + { + progress?.Report("Starting patch application..."); + + await DifferentialCore.Instance.Dirty(appPath, patchPath); + + progress?.Report("Patch applied successfully!"); + } + catch (Exception ex) + { + progress?.Report($"Error: {ex.Message}"); + throw; + } + } +} -Generate patch files [cannot include files with the same name but different extensions]. +// Usage example +var manager = new ProgressivePatchManager(); +var progress = new Progress(msg => Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] {msg}")); -```c# -public async Task Clean(string sourcePath, string targetPath, string patchPath = null); +await manager.GeneratePatchWithProgressAsync( + @"D:\MyApp\1.0.0", + @"D:\MyApp\1.0.1", + @"D:\MyApp\patches\1.0.1", + progress +); ``` -**Parameters** +--- -**sourcePath** Path to the previous version's folder. +## Notes and Warnings -**targetPath** Path to the latest version's folder. +### ⚠️ Important Notes -**patchPath** Directory to store the discovered incremental update files temporarily. +1. **File Name Restrictions** + - Cannot include files with the same name but different extensions (e.g., file.txt and file.log) + - Recommended to use unique file naming conventions -### 🌼Dirty() +2. **Directory Structure** + - The relative structure of source and target directories should remain consistent + - Directory hierarchy is preserved during patch generation -**Method** +3. **Disk Space** + - Ensure sufficient disk space for storing patch files + - Binary differential patches are usually smaller than complete files, but still require temporary space -Apply patches [cannot include files with the same name but different extensions]. +4. **File Locking** + - When applying patches, ensure target files are not locked by other processes + - Recommended to apply patches after the application is closed -```c# -public async Task Dirty(string appPath, string patchPath); -``` +5. **Backup Recommendations** + - Recommended to backup original files before applying patches + - Can use ClientCore's BackUp option for automatic backup -**Parameters** +### 💡 Best Practices -**appPath** Client application directory. +- **Version Management**: Maintain separate patch packages for each version for easier version tracking and rollback +- **Patch Validation**: Perform validation testing after generating patches to ensure they can be applied correctly +- **Incremental Updates**: Prioritize differential updates over full updates, which can save 50%-90% of download size +- **Error Handling**: Implement complete exception capture and error recovery mechanisms +- **Performance Optimization**: For large files, the performance advantage of the differential algorithm is more pronounced -**patchPath** Path to the patch files. +### 🔍 How It Works -### Applicable to +**Clean Method Workflow:** +1. Scan all files in source and target directories +2. Compare MD5 hash values of files to identify changes +3. For modified files, use binary differential algorithm to generate patches +4. For added files, copy directly to patch directory +5. Record list of deleted files -| Product | Versions | +**Dirty Method Workflow:** +1. Read all files in patch directory +2. For patch files, apply to corresponding original files +3. For added files, copy directly to application directory +4. Remove corresponding files according to deletion list +5. Verify update integrity + +--- + +## Applicable Platforms + +| Product | Version | | -------------- | ------------- | -| .NET | 5, 6, 7, 8, 9 | -| .NET Framework | 4.6.1 | -| .NET Standard | 2.0 | -| .NET Core | 2.0 | \ No newline at end of file +| .NET | 5, 6, 7, 8, 9 | +| .NET Framework | 4.6.1 | +| .NET Standard | 2.0 | +| .NET Core | 2.0 | + +--- + +## Related Resources + +- **Sample Code**: [View GitHub Examples](https://github.com/GeneralLibrary/GeneralUpdate-Samples/tree/main/src/Diff) +- **Main Repository**: [GeneralUpdate Project](https://github.com/GeneralLibrary/GeneralUpdate) +- **Packaging Tool**: The GeneralUpdate.PacketTool project depends on this component for differential packaging diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/doc/GeneralUpdate.Bowl.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/doc/GeneralUpdate.Bowl.md index 38885be..de44ec6 100644 --- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/doc/GeneralUpdate.Bowl.md +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/doc/GeneralUpdate.Bowl.md @@ -2,81 +2,223 @@ sidebar_position: 3 --- -### 定义 +# GeneralUpdate.Bowl -命名空间:GeneralUpdate.Bowl +## 组件概览 -程序集:GeneralUpdate.Bowl.dll +**GeneralUpdate.Bowl** 是一个独立的进程监控组件,在升级流程结束前启动,负责启动主客户端应用程序并监控其运行状态。该组件提供了完整的崩溃监控和诊断能力,当被监控的应用程序发生异常时,会自动导出Dump文件、驱动信息、系统信息和事件日志,帮助开发者快速定位问题。 +**命名空间:** `GeneralUpdate.Bowl` +**程序集:** `GeneralUpdate.Bowl.dll` - -该组件在升级流程结束之前启动的一个独立进程,它在流程结束之前去启动主客户端应用程序并监控是否正常运行。 - -```c# +```csharp public sealed class Bowl ``` +--- + +## 核心特性 + +### 1. 进程监控 +- 实时监控目标应用程序的运行状态 +- 自动检测进程崩溃和异常退出 + +### 2. 崩溃诊断 +- 自动生成Dump文件(.dmp)用于崩溃分析 +- 导出详细的系统和驱动信息 +- 收集Windows系统事件日志 + +### 3. 版本化管理 +- 按版本号分类存储故障信息 +- 支持升级和正常两种工作模式 + +--- + +## 快速开始 + +### 安装 + +通过 NuGet 安装 GeneralUpdate.Bowl: + +```bash +dotnet add package GeneralUpdate.Bowl +``` +### 初始化与使用 -### 示例 +以下示例展示了如何使用 Bowl 组件监控应用程序: -以下示例定义方法,包含Bowl使用。 +```csharp +using GeneralUpdate.Bowl; +using GeneralUpdate.Bowl.Strategys; -```c# var installPath = AppDomain.CurrentDomain.BaseDirectory; var lastVersion = "1.0.0.3"; var processInfo = new MonitorParameter { - ProcessNameOrId = "JsonTest.exe", + ProcessNameOrId = "YourApp.exe", DumpFileName = $"{lastVersion}_fail.dmp", FailFileName = $"{lastVersion}_fail.json", TargetPath = installPath, FailDirectory = Path.Combine(installPath, "fail", lastVersion), BackupDirectory = Path.Combine(installPath, lastVersion), - WorkModel = "Normal" + WorkModel = "Normal" // 使用 Normal 模式独立监控 }; Bowl.Launch(processInfo); ``` +--- + +## 核心 API 参考 + +### Launch 方法 + +启动进程监控功能。 + +**方法签名:** + +```csharp +public static void Launch(MonitorParameter? monitorParameter = null) +``` + +**参数:** + +#### MonitorParameter 类 + +```csharp +public class MonitorParameter +{ + /// + /// 被监控的目录 + /// + public string TargetPath { get; set; } + + /// + /// 导出异常信息的目录 + /// + public string FailDirectory { get; set; } + + /// + /// 备份目录 + /// + public string BackupDirectory { get; set; } + + /// + /// 被监控进程的名称或ID + /// + public string ProcessNameOrId { get; set; } + + /// + /// Dump 文件名 + /// + public string DumpFileName { get; set; } + + /// + /// 升级包版本信息(.json)文件名 + /// + public string FailFileName { get; set; } + + /// + /// 工作模式: + /// - Upgrade: 升级模式,主要用于与 GeneralUpdate 配合使用,内部逻辑处理,默认模式启动时请勿随意修改 + /// - Normal: 正常模式,可独立使用监控单个程序,程序崩溃时导出崩溃信息 + /// + public string WorkModel { get; set; } = "Upgrade"; +} +``` + +--- + +## 实际使用示例 + +### 示例 1:独立模式监控应用 + +```csharp +using GeneralUpdate.Bowl; +using GeneralUpdate.Bowl.Strategys; + +// 配置监控参数 +var installPath = AppDomain.CurrentDomain.BaseDirectory; +var currentVersion = "1.0.0.5"; + +var monitorConfig = new MonitorParameter +{ + ProcessNameOrId = "MyApplication.exe", + DumpFileName = $"{currentVersion}_crash.dmp", + FailFileName = $"{currentVersion}_crash.json", + TargetPath = installPath, + FailDirectory = Path.Combine(installPath, "crash_reports", currentVersion), + BackupDirectory = Path.Combine(installPath, "backups", currentVersion), + WorkModel = "Normal" // 独立监控模式 +}; + +// 启动监控 +Bowl.Launch(monitorConfig); +``` + +### 示例 2:结合 GeneralUpdate 使用 + +```csharp +using GeneralUpdate.Bowl; +using GeneralUpdate.Bowl.Strategys; +// 在升级完成后启动 Bowl 监控 +var installPath = AppDomain.CurrentDomain.BaseDirectory; +var upgradedVersion = "2.0.0.1"; -### 捕获 +var upgradeMonitor = new MonitorParameter +{ + ProcessNameOrId = "UpdatedApp.exe", + DumpFileName = $"{upgradedVersion}_fail.dmp", + FailFileName = $"{upgradedVersion}_fail.json", + TargetPath = installPath, + FailDirectory = Path.Combine(installPath, "fail", upgradedVersion), + BackupDirectory = Path.Combine(installPath, upgradedVersion), + WorkModel = "Upgrade" // 升级模式 +}; -如果监控到崩溃闪退将会在运行目录下生成: +Bowl.Launch(upgradeMonitor); +``` + +--- -- 📒Dump文件(1.0.0.*_fail.dmp) -- 📒升级包版本信息(1.0.0.*_fail.json) -- 📒驱动信息(driverInfo.txt) -- 📒操作系统信息/硬件信息(systeminfo.txt) -- 📒系统事件日志(systemlog.evtx) +## 崩溃信息捕获 -导出到“fail”目录下并根据版本号区分文件夹。 +当检测到崩溃时,以下文件将在运行目录中生成: -![](imgs\crash.jpg) +- 📒 **Dump 文件** (`x.0.0.*_fail.dmp`) +- 📒 **升级包版本信息** (`x.0.0.*_fail.json`) +- 📒 **驱动信息** (`driverInfo.txt`) +- 📒 **操作系统/硬件信息** (`systeminfo.txt`) +- 📒 **系统事件日志** (`systemlog.evtx`) +这些文件将按版本号分类导出到 "fail" 目录中。 +![崩溃文件](imgs/crash.jpg) -#### (1)x.0.0.*_fail.dmp +### 1. Dump 文件 -![](imgs\dump.png) +Dump 文件包含崩溃时刻的内存快照,可用于调试分析: +![Dump文件](imgs/dump.png) +### 2. 版本信息文件 -#### (2)x.0.0.*_fail.json +JSON 格式的详细崩溃报告,包含参数配置和 ProcDump 输出: ```json { - "Parameter": { - "TargetPath": "D:\\github_project\\GeneralUpdate\\src\\c#\\Generalupdate.CatBowl\\bin\\Debug\\net9.0\\", - "FailDirectory": "D:\\github_project\\GeneralUpdate\\src\\c#\\Generalupdate.CatBowl\\bin\\Debug\\net9.0\\fail\\1.0.0.3", - "BackupDirectory": "D:\\github_project\\GeneralUpdate\\src\\c#\\Generalupdate.CatBowl\\bin\\Debug\\net9.0\\1.0.0.3", - "ProcessNameOrId": "JsonTest.exe", - "DumpFileName": "1.0.0.3_fail.dmp", - "FailFileName": "1.0.0.3_fail.json", - "WorkModel": "Normal", - "ExtendedField": null - }, - "ProcdumpOutPutLines": [ +"Parameter": { +"TargetPath": "D:\\github_project\\GeneralUpdate\\src\\c#\\Generalupdate.CatBowl\\bin\\Debug\\net9.0\\", +"FailDirectory": "D:\\github_project\\GeneralUpdate\\src\\c#\\Generalupdate.CatBowl\\bin\\Debug\\net9.0\\fail\\1.0.0.3", +"BackupDirectory": "D:\\github_project\\GeneralUpdate\\src\\c#\\Generalupdate.CatBowl\\bin\\Debug\\net9.0\\1.0.0.3", +"ProcessNameOrId": "JsonTest.exe", +"DumpFileName": "1.0.0.3_fail.dmp", +"FailFileName": "1.0.0.3_fail.json", +"WorkModel": "Normal", +"ExtendedField": null +}, +"ProcdumpOutPutLines": [ "ProcDump v11.0 - Sysinternals process dump utility", "Copyright (C) 2009-2022 Mark Russinovich and Andrew Richards", "Sysinternals - www.sysinternals.com", @@ -104,163 +246,83 @@ Bowl.Launch(processInfo); } ``` +### 3. 驱动信息文件 +包含系统中所有驱动程序的详细信息: -#### (3)driverInfo.txt - -```json - -模块名 显示名称 描述 驱动程序类型 启动模式 状态 状态 接受停止 接受暂停 分页缓冲池 代码(字节) BSS(字 链接日期 路径 Init(字节) -============ ====================== ====================== ============= ========== ========== ========== =========== ============ ========== ========== ======= ====================== ================================================ ========== -360AntiAttac 360Safe Anti Attack Se 360Safe Anti Attack Se Kernel System Running OK TRUE FALSE 4,096 36,864 0 9/29/2022 3:45:03 PM C:\Windows\system32\Drivers\360AntiAttack64.sys 4,096 -360AntiHacke 360Safe Anti Hacker Se 360Safe Anti Hacker Se Kernel System Running OK TRUE FALSE 4,096 139,264 0 11/27/2023 3:43:37 PM C:\Windows\system32\Drivers\360AntiHacker64.sys 8,192 -360AntiHijac 360Safe Anti Hijack Se 360Safe Anti Hijack Se Kernel System Running OK TRUE FALSE 4,096 73,728 0 5/8/2024 12:19:52 PM C:\Windows\system32\Drivers\360AntiHijack64.sys 4,096 -360AntiSteal 360Safe Anti Steal Fil 360Safe Anti Steal Fil Kernel System Running OK TRUE FALSE 4,096 20,480 0 4/18/2024 3:58:04 PM C:\Windows\system32\Drivers\360AntiSteal64.sys 8,192 -360Box64 360Box mini-filter dri 360Box mini-filter dri File System System Running OK TRUE FALSE 0 225,280 0 8/7/2024 11:50:19 AM C:\Windows\system32\DRIVERS\360Box64.sys 12,288 - -//... +```text +Module Name Display Name Description Driver Type Start Mode State Status +============ ====================== ====================== ============= ========== ========== ========== +360AntiAttac 360Safe Anti Attack Se 360Safe Anti Attack Se Kernel System Running OK +360AntiHacke 360Safe Anti Hacker Se 360Safe Anti Hacker Se Kernel System Running OK +// ...更多驱动信息 ``` +### 4. 系统信息文件 +完整的操作系统和硬件配置信息: -#### (4)systeminfo.txt - -```json - -主机名: **** -OS 名称: Microsoft Windows 11 专业版 -OS 版本: 10.0.2*** Build 22*** -OS 制造商: Microsoft Corporation -OS 配置: 独立工作站 -OS 构建类型: Multiprocessor Free -注册的所有人: ****@outlook.com -注册的组织: -产品 ID: ****-80000-***00-A**** -初始安装日期: 11/16/2023, 9:56:28 PM -系统启动时间: 11/26/2024, 9:37:51 PM -系统制造商: ASUS -系统型号: System Product Name -系统类型: x64-based PC -处理器: 安装了 1 个处理器。 - [01]: Intel** Family * Model *** Stepping * GenuineIntel ~**** Mhz -BIOS 版本: American Megatrends Inc. 1402, 4/1/2022 -Windows 目录: C:\Windows -系统目录: C:\Windows\system32 -启动设备: \Device\Ha*****olume1 -系统区域设置: zh-cn;中文(中国) -输入法区域设置: zh-cn;中文(中国) -时区: (UTC+08:00) **,**,*******,**** -物理内存总量: 16,194 MB -可用的物理内存: 1,795 MB -虚拟内存: 最大值: 25,410 MB -虚拟内存: 可用: 9,438 MB -虚拟内存: 使用中: 15,972 MB -页面文件位置: D:\****file.sys -域: WORKGROUP -登录服务器: \\**** -修补程序: 安装了 6 个修补程序。 - [01]: KB504**** - [02]: KB502**** - [03]: KB503**** - [04]: KB503**** - [05]: KB504**** - [06]: KB504**** -网卡: 安装了 3 个 NIC。 - [01]: Intel(R) Ethernet Connection (**) I***-V - 连接名: 以太网 - 启用 DHCP: 是 - DHCP 服务器: 192.168.**.** - IP 地址 - [01]: 192.168.**.** - [02]: ***::2640:***:****:**** - [02]: VMware Virtual Ethernet Adapter for VMnet1 - 连接名: VMware Network Adapter VMnet1 - 启用 DHCP: 是 - DHCP 服务器: 192.168.**.** - IP 地址 - [01]: 192.168.**.** - [02]: ***::9b3:***,***:**** - [03]: VMware Virtual Ethernet Adapter for VMnet8 - 连接名: VMware Network Adapter VMnet8 - 启用 DHCP: 是 - DHCP 服务器: 192.168.**.** - IP 地址 - [01]: 192.***,***:**** - [02]: fe80::***:***:***:**** -Hyper-V 要求: 已检测到虚拟机监控程序。将不显示 Hyper-V 所需的功能。 - -//... +```text +Host Name: **** +OS Name: Microsoft Windows 11 Pro +OS Version: 10.0.*** Build 22*** +System Manufacturer: ASUS +System Model: System Product Name +Processor(s): Intel** Family * Model *** +Total Physical Memory: 16,194 MB +// ...更多系统信息 ``` +### 5. 系统事件日志 +Windows 事件查看器格式的系统日志(.evtx 文件): -#### (5)systemlog.evtx - -![](imgs\evtx.png) - - - -### 注解 - -Bowl提供运行监控功能,并导出相关错误信息 。 - +![系统事件日志](imgs/evtx.png) +--- -#### 方法 +## 注意事项与警告 -| Method | | -| -------- | -------- | -| Launch() | 启动监控 | +### ⚠️ 重要提示 +1. **工作模式选择** + - `Upgrade` 模式:专门用于与 GeneralUpdate 框架集成,包含内部逻辑处理 + - `Normal` 模式:可独立使用,适合监控任何 .NET 应用程序 +2. **权限要求** + - Bowl 需要足够的权限来生成 Dump 文件和读取系统信息 + - 建议以管理员权限运行需要监控的应用程序 -### 🌼Launch() +3. **磁盘空间** + - Dump 文件可能占用大量磁盘空间(通常 50-200 MB) + - 确保 FailDirectory 所在磁盘有足够的可用空间 -**启动函数** +4. **依赖项** + - Bowl 使用 ProcDump 工具生成 Dump 文件,该工具已内置在组件中 + - 无需额外安装依赖项 -```c# -Launch(MonitorParameter? monitorParameter = null); -``` +### 💡 最佳实践 -**参数** +- **版本号管理**:为每个版本使用独立的故障目录,便于问题追踪 +- **日志清理**:定期清理旧版本的故障信息,避免磁盘空间耗尽 +- **测试验证**:在生产环境部署前,在测试环境验证监控功能 -```c# -public class MonitorParameter -{ - //被监控的目录 - public string TargetPath { get; set; } - - //捕获的异常信息导出到的目录 - public string FailDirectory { get; set; } - - //备份目录 - public string BackupDirectory { get; set; } - - //监控进程名称或者进程id - public string ProcessNameOrId { get; set; } - - //dump文件名 - public string DumpFileName { get; set; } - - //升级包版本信息(.json)文件名 - public string FailFileName { get; set; } +--- - /// - /// Upgrade: upgrade mode. This mode is primarily used in conjunction with GeneralUpdate for internal use. Please do not modify it arbitrarily when the default mode is activated. - /// Normal: Normal mode,This mode can be used independently to monitor a single program. If the program crashes, it will export the crash information. - /// - public string WorkModel { get; set; } = "Upgrade"; -} -``` +## 适用平台 +| 产品 | 版本 | +| --------------- | ----------------- | +| .NET | 5, 6, 7, 8, 9 | +| .NET Framework | 4.6.1 | +| .NET Standard | 2.0 | +| .NET Core | 2.0 | +| ASP.NET | Any | +--- -### 适用于 +## 相关资源 -| 产品 | 版本 | -| -------------- | ------------- | -| .NET | 5、6、7、8、9 | -| .NET Framework | 4.6.1 | -| .NET Standard | 2.0 | -| .NET Core | 2.0 | -| ASP.NET | Any | \ No newline at end of file +- **示例代码**:[查看 GitHub 示例](https://github.com/GeneralLibrary/GeneralUpdate-Samples/tree/main/src/Bowl) +- **视频教程**:[观看 Bilibili 教程](https://www.bilibili.com/video/BV1c8iyYZE7P) +- **主仓库**:[GeneralUpdate 项目](https://github.com/GeneralLibrary/GeneralUpdate) diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/doc/GeneralUpdate.ClientCore.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/doc/GeneralUpdate.ClientCore.md index 320e848..deb4ec3 100644 --- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/doc/GeneralUpdate.ClientCore.md +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/doc/GeneralUpdate.ClientCore.md @@ -2,130 +2,603 @@ sidebar_position: 4 --- -### 定义 +# GeneralUpdate.ClientCore -命名空间:GeneralUpdate.ClientCore +## 组件概览 -程序集:GeneralUpdate.ClientCore.dll +**GeneralUpdate.ClientCore** 是 GeneralUpdate 框架的核心组件之一,提供了丰富的客户端更新功能。该组件运行在主应用程序中,负责检查更新、下载更新包、验证完整性,并在完成后启动升级助手(GeneralUpdate.Core)来执行实际的文件替换操作。ClientCore 的设计理念是让主程序能够安全地检查和准备更新,而不影响当前运行状态。 +**命名空间:** `GeneralUpdate.ClientCore` +**程序集:** `GeneralUpdate.ClientCore.dll` +```csharp +public class GeneralClientBootstrap : AbstractBootstrap +``` -GeneralUpdate.ClientCore是最核心的组件之一,提供了大量主要功能。本质和Core没有区别,但是有职责上的区别ClientCore用于主程序中,更新升级助手然后关闭主程序启动升级助手。 +--- -```c# -public class GeneralClientBootstrap : AbstractBootstrap +## 核心特性 + +### 1. 多版本下载管理 +- 支持同时下载多个版本的更新包 +- 断点续传和下载速度限制 +- 实时下载进度和统计信息 + +### 2. 灵活的配置选项 +- 黑名单机制(文件、格式、目录) +- 自定义更新策略和操作 +- 支持二进制差异更新和全量更新 + +### 3. 完整的事件通知 +- 下载进度、完成、错误事件 +- 支持用户自定义跳过更新选项 +- 异常和错误全程监控 + +### 4. 多平台支持 +- Windows、Linux、macOS 平台支持 +- 自动平台检测和策略选择 + +![Multi Download](imgs/muti_donwload.png) + +--- + +## 快速开始 + +### 安装 + +通过 NuGet 安装 GeneralUpdate.ClientCore: + +```bash +dotnet add package GeneralUpdate.ClientCore ``` +### 初始化与使用 + +以下示例展示了如何在主程序中配置和启动更新检查: + +```csharp +using System.Text; +using GeneralUpdate.ClientCore; +using GeneralUpdate.Common.Download; +using GeneralUpdate.Common.Internal; +using GeneralUpdate.Common.Internal.Bootstrap; +using GeneralUpdate.Common.Shared.Object; + +try +{ + Console.WriteLine($"主程序初始化,{DateTime.Now}!"); + + // 配置更新参数 + var configinfo = new Configinfo + { + // 更新验证 API 地址 + UpdateUrl = "http://127.0.0.1:5000/Upgrade/Verification", + // 更新报告 API 地址 + ReportUrl = "http://127.0.0.1:5000/Upgrade/Report", + // 主应用程序名称 + MainAppName = "ClientSample.exe", + // 升级程序名称 + AppName = "UpgradeSample.exe", + // 当前客户端版本 + ClientVersion = "1.0.0.0", + // 升级端版本 + UpgradeClientVersion = "1.0.0.0", + // 安装路径 + InstallPath = Thread.GetDomain().BaseDirectory, + // 产品 ID(用于多产品分支管理) + ProductId = "2d974e2a-31e6-4887-9bb1-b4689e98c77a", + // 应用密钥(用于服务器验证) + AppSecretKey = "dfeb5833-975e-4afb-88f1-6278ee9aeff6" + }; + + // 启动更新流程 + await new GeneralClientBootstrap() + // 监听下载统计信息 + .AddListenerMultiDownloadStatistics(OnMultiDownloadStatistics) + // 监听单个下载完成 + .AddListenerMultiDownloadCompleted(OnMultiDownloadCompleted) + // 监听所有下载完成 + .AddListenerMultiAllDownloadCompleted(OnMultiAllDownloadCompleted) + // 监听下载错误 + .AddListenerMultiDownloadError(OnMultiDownloadError) + // 监听异常 + .AddListenerException(OnException) + // 设置配置 + .SetConfig(configinfo) + // 设置选项 + .Option(UpdateOption.DownloadTimeOut, 60) + .Option(UpdateOption.Encoding, Encoding.Default) + // 启动异步更新 + .LaunchAsync(); + + Console.WriteLine($"主程序已启动,{DateTime.Now}!"); +} +catch (Exception e) +{ + Console.WriteLine(e.Message + "\n" + e.StackTrace); +} + +// 事件处理方法 +void OnMultiDownloadStatistics(object arg1, MultiDownloadStatisticsEventArgs arg2) +{ + var version = arg2.Version as VersionInfo; + Console.WriteLine($"下载版本:{version.Version},速度:{arg2.Speed}," + + $"剩余时间:{arg2.Remaining},进度:{arg2.ProgressPercentage}%"); +} + +void OnMultiDownloadCompleted(object arg1, MultiDownloadCompletedEventArgs arg2) +{ + var version = arg2.Version as VersionInfo; + Console.WriteLine(arg2.IsComplated ? + $"版本 {version.Version} 下载完成!" : + $"版本 {version.Version} 下载失败!"); +} + +void OnMultiAllDownloadCompleted(object arg1, MultiAllDownloadCompletedEventArgs arg2) +{ + Console.WriteLine(arg2.IsAllDownloadCompleted ? + "所有下载任务已完成!" : + $"下载任务失败!失败数量:{arg2.FailedVersions.Count}"); +} + +void OnMultiDownloadError(object arg1, MultiDownloadErrorEventArgs arg2) +{ + var version = arg2.Version as VersionInfo; + Console.WriteLine($"版本 {version.Version} 下载错误:{arg2.Exception}"); +} + +void OnException(object arg1, ExceptionEventArgs arg2) +{ + Console.WriteLine($"更新异常:{arg2.Exception}"); +} +``` +--- -### 示例 +## 核心 API 参考 -GeneralClientBootstrap使用代码示例 [进入](https://github.com/GeneralLibrary/GeneralUpdate-Samples/blob/main/src/Client/Program.cs)。 +### GeneralClientBootstrap 类方法 -![](imgs/muti_donwload.png) +#### LaunchAsync 方法 +异步启动更新流程。 +```csharp +public async Task LaunchAsync() +``` -### 注解 +#### SetConfig 方法 -GeneralClientBootstrap提供以下能力。 +设置更新配置信息。 -#### 属性 +```csharp +public GeneralClientBootstrap SetConfig(Configinfo configinfo) +``` -| Properties | | -| ------------ | ---------------------------------------------------------- | -| UpdateOption | 更新操作配置设置枚举 | -| Configinfo | 客户端相关参数类(AppType、AppName、AppSecretKey等字段)。 | +#### Option 方法 -#### 方法 +设置更新选项。 -| Method | | -| -------------------------------------- | ------------------------------------------------------------ | -| LaunchTaskAsync() | Task异步启动更新 | -| LaunchAsync() | 启动更新 | -| SetBlacklist() | 设置更新文件黑名单,如果不需要更新文件 名则传入即可。 | -| Option() | 设置更新配置。 | -| Config() | 更新相关内容配置参数,url 服务器地址及 端口号, appSecretKey客户端唯一标识用于 区分产品分支。 | -| GetOption() | 获取更新配置。 | -| SetCustomSkipOption() | 让用户在非强制更新的状态下决定是否进行更新。 | -| AddCustomOption() | 添加一个异步的自定义操作。理论上,任何自定义操作都可以完成。建议注册环境检查方法,以确保更新完成后存在正常的依赖和环境。 | -| AddListenerMultiAllDownloadCompleted() | 完成所有的下载任务通知。 | -| AddListenerMultiDownloadCompleted() | 单个或多个更新包下载完成事件。 | -| AddListenerMultiDownloadError() | 监听每个版本下载异常的事件 | -| AddListenerMultiDownloadStatistics() | 单个或多个更新包下载速度、剩余下载事 件、当前下载版本信息通知事件。 | -| AddListenerException() | 整个更新过程出现的任何问题都会通过这个回调函数通知。 | +```csharp +public GeneralClientBootstrap Option(UpdateOption option, object value) +``` +#### SetBlacklist 方法 +设置更新黑名单,指定不需要更新的文件。 -### 🌴Packet +```csharp +public GeneralClientBootstrap SetBlacklist(List blackFiles = null, + List blackFormats = null) +``` + +#### AddListenerMultiDownloadStatistics 方法 + +监听下载统计信息(速度、进度、剩余时间等)。 + +```csharp +public GeneralClientBootstrap AddListenerMultiDownloadStatistics( + Action callbackAction) +``` -| 属性 | -| ------------------------------------------------------------ | -| **MainUpdateUrl** string 更新检查api地址。 | -| **AppType** int 1:ClientApp 2:UpdateApp | -| **UpdateUrl** string Update 更新检查api地址。 | -| **AppName** string 需要启动应用程序的名称。 | -| **MainAppName** string 需要启动主应用程序的名称。 | -| **Format** string 更新包文件格式(默认格式为Zip)。 | -| **IsUpgradeUpdate** bool 是否需要更新来升级应用程序。 | -| **IsMainUpdate** bool 主应用程序是否需要更新。 | -| **UpdateLogUrl** string 更新日志网页地址。 | -| **UpdateVersions** List 需要更新的版本信息VersionInfo。 | -| **Encoding** Encoding 文件操作的编码格式。 | -| **DownloadTimeOut** int 下载超时时间。 | -| **AppSecretKey** string 应用程序密钥,需要和服务器约定好。 | -| **ClientVersion** string 客户端当前版本号。 | -| **LastVersion** string 最新版本号。 | -| **InstallPath** string 安装路径(用于更新文件逻辑)。 | -| **TempPath** string 下载文件临时存储路径(用于更新文件逻辑)。 | -| **ProcessBase64** string 升级终端程序的配置参数。 | -| **Platform** string 当前策略所属的平台。(Windows\linux\Mac) | -| **BlackFiles** List 黑名单中的文件将跳过更新。 | -| **BlackFormats** 黑名单中的文件格式将跳过更新。 | +#### AddListenerMultiDownloadCompleted 方法 +监听单个更新包下载完成事件。 +```csharp +public GeneralClientBootstrap AddListenerMultiDownloadCompleted( + Action callbackAction) +``` + +#### AddListenerMultiAllDownloadCompleted 方法 + +监听所有下载任务完成事件。 + +```csharp +public GeneralClientBootstrap AddListenerMultiAllDownloadCompleted( + Action callbackAction) +``` -### 🌴Configinfo +#### AddListenerMultiDownloadError 方法 -| **属性** | 类型 | 注释 | -| -------------------- | ------ | ------------------------------------------------------------ | -| UpdateUrl | string | 更新检查api地址。 | -| ReportUrl | string | 上报更新状态api地址。 | -| AppName | string | 需要启动应用程序的名称。 | -| MainAppName | string | 需要启动主应用程序的名称。 | -| UpdateLogUrl | string | 更新日志网页地址。 | -| AppSecretKey | string | 应用程序密钥,需要和服务端约定好验证身份和分支。 | -| ClientVersion | string | 客户端当前版本号。 | -| UpgradeClientVersion | string | 升级端当前版本号。 | -| InstallPath | string | 安装路径(用于更新文件逻辑)。 | -| BlackFiles | List | 黑名单中的文件将跳过更新。 | -| BlackFormats | List | 黑名单中的文件格式将跳过更新。 | -| SkipDirectorys | List | 跳过不需要更新的文件夹目录。 | -| ProductId | string | 当前产品分支的唯一id。 | -| Bowl | string | Bowl监控进程路径,更新完成之后启动Bowl监控客户端是否正常启动。如果启动后异常会捕捉异常信息。 | -| Scheme | string | 用于HTTP请求传入token进行身份验证。 | -| Token | string | 用于HTTP请求传入token进行身份验证。 | -| Script | string | 在Linux平台中更新完成之后执行,脚本给文件赋权限。更新之前需要赋权限在引导启动类里可通过GeneralClientBootstrap.AddCustomOption函数注入,函数会在更新前执行。 | +监听下载错误事件。 +```csharp +public GeneralClientBootstrap AddListenerMultiDownloadError( + Action callbackAction) +``` + +#### AddListenerException 方法 + +监听更新过程中的所有异常。 + +```csharp +public GeneralClientBootstrap AddListenerException( + Action callbackAction) +``` + +#### AddCustomOption 方法 + +添加自定义异步操作,可在更新前后执行自定义逻辑。 + +```csharp +public GeneralClientBootstrap AddCustomOption(Func customFunc) +``` +#### SetCustomSkipOption 方法 + +设置自定义跳过选项,允许用户决定是否继续更新。 + +```csharp +public GeneralClientBootstrap SetCustomSkipOption(Func customSkipFunc) +``` + +--- + +## 配置类详解 + +### Configinfo 类 + +```csharp +public class Configinfo +{ + /// + /// 更新检查 API 地址 + /// + public string UpdateUrl { get; set; } + + /// + /// 更新状态报告 API 地址 + /// + public string ReportUrl { get; set; } + + /// + /// 需要启动的应用程序名称(升级程序) + /// + public string AppName { get; set; } + + /// + /// 需要启动的主应用程序名称 + /// + public string MainAppName { get; set; } + + /// + /// 更新日志网页地址 + /// + public string UpdateLogUrl { get; set; } + + /// + /// 应用密钥,与服务器约定用于身份验证和产品分支 + /// + public string AppSecretKey { get; set; } + + /// + /// 当前客户端版本号 + /// + public string ClientVersion { get; set; } + + /// + /// 当前升级客户端版本号 + /// + public string UpgradeClientVersion { get; set; } + + /// + /// 安装路径(用于更新文件逻辑) + /// + public string InstallPath { get; set; } + + /// + /// 黑名单文件列表,这些文件在更新时会被跳过 + /// + public List BlackFiles { get; set; } + + /// + /// 黑名单文件格式列表,这些格式的文件在更新时会被跳过 + /// + public List BlackFormats { get; set; } + + /// + /// 需要跳过的目录路径列表,这些目录不需要更新 + /// + public List SkipDirectorys { get; set; } + + /// + /// 当前产品分支的唯一 ID + /// + public string ProductId { get; set; } + + /// + /// Bowl 监控进程路径,更新完成后启动 Bowl 检查客户端是否正常启动 + /// + public string Bowl { get; set; } + + /// + /// HTTP 请求中用于传递 token 的 Scheme(如 Bearer) + /// + public string Scheme { get; set; } + + /// + /// HTTP 请求中用于身份验证的 Token + /// + public string Token { get; set; } + + /// + /// Linux 平台下的脚本,用于在更新完成后为文件分配权限 + /// + public string Script { get; set; } +} +``` + +### UpdateOption 枚举 + +```csharp +public enum UpdateOption +{ + /// + /// 更新包文件格式(默认为 Zip) + /// + Format, + + /// + /// 压缩编码格式 + /// + Encoding, + + /// + /// 下载超时时间(秒)。如果不指定,默认超时时间为 30 秒 + /// + DownloadTimeOut, + + /// + /// 是否启用二进制差异更新功能,默认启用;设置为 false 则执行全量覆盖安装 + /// + Patch, + + /// + /// 是否在更新前启用备份功能,默认启用;设置为 false 则不进行备份 + /// + BackUp +} +``` + +--- + +## 实际使用示例 + +### 示例 1:基本更新流程 + +```csharp +using GeneralUpdate.ClientCore; +using GeneralUpdate.Common.Internal; + +var config = new Configinfo +{ + UpdateUrl = "http://your-server.com/api/update/check", + ReportUrl = "http://your-server.com/api/update/report", + MainAppName = "MyApp.exe", + AppName = "Updater.exe", + ClientVersion = "1.0.0.0", + UpgradeClientVersion = "1.0.0.0", + InstallPath = AppDomain.CurrentDomain.BaseDirectory, + ProductId = "your-product-id", + AppSecretKey = "your-secret-key" +}; + +await new GeneralClientBootstrap() + .SetConfig(config) + .AddListenerException((sender, args) => + { + Console.WriteLine($"更新异常: {args.Exception.Message}"); + }) + .LaunchAsync(); +``` + +### 示例 2:带黑名单的更新 + +```csharp +using GeneralUpdate.ClientCore; +using GeneralUpdate.Common.Internal; + +var config = new Configinfo +{ + UpdateUrl = "http://your-server.com/api/update/check", + ClientVersion = "1.0.0.0", + InstallPath = AppDomain.CurrentDomain.BaseDirectory, + // 黑名单配置 + BlackFiles = new List { "config.json", "userdata.db" }, + BlackFormats = new List { ".log", ".cache" }, + SkipDirectorys = new List { "logs", "temp" } +}; + +await new GeneralClientBootstrap() + .SetConfig(config) + .LaunchAsync(); +``` + +### 示例 3:自定义更新选项 + +```csharp +using System.Text; +using GeneralUpdate.ClientCore; +using GeneralUpdate.Common.Internal; +using GeneralUpdate.Common.Internal.Bootstrap; + +var config = new Configinfo +{ + UpdateUrl = "http://your-server.com/api/update/check", + ClientVersion = "1.0.0.0", + InstallPath = AppDomain.CurrentDomain.BaseDirectory +}; + +await new GeneralClientBootstrap() + .SetConfig(config) + // 设置下载超时 + .Option(UpdateOption.DownloadTimeOut, 120) + // 设置编码格式 + .Option(UpdateOption.Encoding, Encoding.UTF8) + // 启用二进制差异更新 + .Option(UpdateOption.Patch, true) + // 启用备份 + .Option(UpdateOption.BackUp, true) + .LaunchAsync(); +``` + +### 示例 4:完整的事件监听 + +```csharp +using GeneralUpdate.ClientCore; +using GeneralUpdate.Common.Download; +using GeneralUpdate.Common.Internal; +using GeneralUpdate.Common.Shared.Object; + +var config = new Configinfo +{ + UpdateUrl = "http://your-server.com/api/update/check", + ClientVersion = "1.0.0.0", + InstallPath = AppDomain.CurrentDomain.BaseDirectory +}; + +await new GeneralClientBootstrap() + .SetConfig(config) + // 下载统计 + .AddListenerMultiDownloadStatistics((sender, args) => + { + var version = args.Version as VersionInfo; + Console.WriteLine($"[{version.Version}] 进度: {args.ProgressPercentage}% | " + + $"速度: {args.Speed} | 剩余: {args.Remaining}"); + }) + // 单个下载完成 + .AddListenerMultiDownloadCompleted((sender, args) => + { + var version = args.Version as VersionInfo; + if (args.IsComplated) + Console.WriteLine($"✓ 版本 {version.Version} 下载成功"); + else + Console.WriteLine($"✗ 版本 {version.Version} 下载失败"); + }) + // 所有下载完成 + .AddListenerMultiAllDownloadCompleted((sender, args) => + { + if (args.IsAllDownloadCompleted) + Console.WriteLine("✓ 所有更新包下载完成,准备安装..."); + else + Console.WriteLine($"✗ 下载失败,共 {args.FailedVersions.Count} 个版本失败"); + }) + // 下载错误 + .AddListenerMultiDownloadError((sender, args) => + { + var version = args.Version as VersionInfo; + Console.WriteLine($"✗ 版本 {version.Version} 下载错误: {args.Exception.Message}"); + }) + // 异常处理 + .AddListenerException((sender, args) => + { + Console.WriteLine($"⚠ 更新异常: {args.Exception.Message}\n{args.Exception.StackTrace}"); + }) + .LaunchAsync(); +``` + +### 示例 5:自定义操作和跳过选项 + +```csharp +using GeneralUpdate.ClientCore; +using GeneralUpdate.Common.Internal; + +var config = new Configinfo +{ + UpdateUrl = "http://your-server.com/api/update/check", + ClientVersion = "1.0.0.0", + InstallPath = AppDomain.CurrentDomain.BaseDirectory +}; + +await new GeneralClientBootstrap() + .SetConfig(config) + // 添加自定义操作(更新前检查环境) + .AddCustomOption(async () => + { + Console.WriteLine("正在检查运行环境..."); + await Task.Delay(1000); + // 检查磁盘空间、依赖项等 + Console.WriteLine("环境检查完成"); + }) + // 设置用户跳过选项 + .SetCustomSkipOption(() => + { + Console.WriteLine("发现新版本,是否更新?(y/n)"); + var input = Console.ReadLine(); + return input?.ToLower() == "y"; + }) + .LaunchAsync(); +``` + +--- + +## 注意事项与警告 + +### ⚠️ 重要提示 + +1. **版本号格式** + - 版本号必须遵循语义化版本规范(如 1.0.0.0) + - 确保客户端和服务器端版本号格式一致 + +2. **网络连接** + - 确保更新服务器地址可访问 + - 建议实现重试机制处理网络波动 + +3. **进程管理** + - 更新过程会关闭主程序并启动升级助手 + - 确保保存所有用户数据后再执行更新 + +4. **权限要求** + - 在 Windows 上可能需要管理员权限来替换文件 + - 在 Linux/macOS 上需要适当的文件系统权限 + +5. **黑名单使用** + - 黑名单中的文件和目录不会被更新 + - 常用于保护配置文件、用户数据等 + +### 💡 最佳实践 + +- **备份策略**:始终启用 BackUp 选项,以便更新失败时可以回滚 +- **差异更新**:启用 Patch 选项以减少下载量和更新时间 +- **错误处理**:实现完整的异常监听和错误处理逻辑 +- **用户体验**:在更新前提示用户并允许选择更新时机 +- **测试验证**:在生产环境部署前充分测试更新流程 + +--- + +## 适用平台 + +| 产品 | 版本 | +| ------------------ | -------------------- | +| .NET | 5, 6, 7, 8, 9, 10 | +| .NET Framework | 4.6.1 | +| .NET Standard | 2.0 | +| .NET Core | 2.0 | + +--- -### 🍵UpdateOption +## 相关资源 -| **枚举** | -| ------------------------------------------------------------ | -| **Format** 更新包的文件格式。 | -| **Encoding** 压缩编码。 | -| **DownloadTimeOut** 超时时间(单位:秒)。如果未指定此参数,则默认超时时间为30秒。 | -| **Patch** 是否开启二进制差分功能,默认开启,如果设置为false均为覆盖安装。 | -| **BackUp** 是否开启更新前备份功能,默认开启,如果设置为false则不备份。 | - - - -### 适用于 - -| 产品 | 版本 | -| -------------- | ----------------- | -| .NET | 5、6、7、8、9、10 | -| .NET Framework | 4.6.1 | -| .NET Standard | 2.0 | -| .NET Core | 2.0 | +- **示例代码**:[查看 GitHub 示例](https://github.com/GeneralLibrary/GeneralUpdate-Samples/blob/main/src/Client/Program.cs) +- **主仓库**:[GeneralUpdate 项目](https://github.com/GeneralLibrary/GeneralUpdate) diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/doc/GeneralUpdate.Core.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/doc/GeneralUpdate.Core.md index 94503c0..7e60681 100644 --- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/doc/GeneralUpdate.Core.md +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/doc/GeneralUpdate.Core.md @@ -2,70 +2,564 @@ sidebar_position: 5 --- -### 定义 +# GeneralUpdate.Core -命名空间:GeneralUpdate.Core +## 组件概览 -程序集:GeneralUpdate.Core.dll +**GeneralUpdate.Core** 是 GeneralUpdate 框架最核心的组件之一,提供了完整的升级执行能力。与 ClientCore 不同,Core 组件作为独立的升级助手程序运行,负责在主程序关闭后执行实际的文件替换、版本升级和系统更新操作。通过进程启动和参数传递的方式,Core 接收来自 ClientCore 的更新指令,并安全地完成主程序的升级任务。 +**命名空间:** `GeneralUpdate.Core` +**程序集:** `GeneralUpdate.Core.dll` +```csharp +public class GeneralUpdateBootstrap : AbstractBootstrap +``` -GeneralUpdate.Core是最核心的组件之一,提供了大量主要功能。当主程序升级操作完成之后会通过进程 启动并传参的方式调用本组件来完成主程序升级操作。(主要职责更新主程序) +--- -```c# -public class GeneralUpdateBootstrap : AbstractBootstrap +## 核心特性 + +### 1. 文件替换与版本管理 +- 安全的文件替换机制,避免文件占用问题 +- 支持多版本增量升级 +- 自动处理文件依赖关系 + +### 2. 驱动升级支持 +- 可选的驱动程序升级功能 +- 字段映射表配置 +- 安全的驱动安装流程 + +### 3. 完整的事件通知 +- 下载进度实时监控 +- 多版本下载管理 +- 异常和错误完整捕获 + +### 4. 跨平台支持 +- Windows、Linux、macOS 平台全支持 +- 自动平台检测和策略适配 + +![Multi Download](imgs/muti_donwload.png) + +--- + +## 快速开始 + +### 安装 + +通过 NuGet 安装 GeneralUpdate.Core: + +```bash +dotnet add package GeneralUpdate.Core ``` +### 初始化与使用 + +以下示例展示了如何在升级助手程序中配置和启动升级流程: + +```csharp +using GeneralUpdate.Common.Download; +using GeneralUpdate.Common.Internal; +using GeneralUpdate.Common.Shared.Object; +using GeneralUpdate.Core; + +try +{ + Console.WriteLine($"升级程序初始化,{DateTime.Now}!"); + Console.WriteLine("当前运行目录:" + Thread.GetDomain().BaseDirectory); + + // 启动升级流程 + await new GeneralUpdateBootstrap() + // 监听下载统计信息 + .AddListenerMultiDownloadStatistics(OnMultiDownloadStatistics) + // 监听单个下载完成 + .AddListenerMultiDownloadCompleted(OnMultiDownloadCompleted) + // 监听所有下载完成 + .AddListenerMultiAllDownloadCompleted(OnMultiAllDownloadCompleted) + // 监听下载错误 + .AddListenerMultiDownloadError(OnMultiDownloadError) + // 监听异常 + .AddListenerException(OnException) + // 启动异步升级 + .LaunchAsync(); + + Console.WriteLine($"升级程序已启动,{DateTime.Now}!"); + await Task.Delay(2000); +} +catch (Exception e) +{ + Console.WriteLine(e.Message + "\n" + e.StackTrace); +} + +// 事件处理方法 +void OnMultiDownloadStatistics(object arg1, MultiDownloadStatisticsEventArgs arg2) +{ + var version = arg2.Version as VersionInfo; + Console.WriteLine($"当前下载版本:{version.Version},下载速度:{arg2.Speed}," + + $"剩余时间:{arg2.Remaining},进度:{arg2.ProgressPercentage}%"); +} +void OnMultiDownloadCompleted(object arg1, MultiDownloadCompletedEventArgs arg2) +{ + var version = arg2.Version as VersionInfo; + Console.WriteLine(arg2.IsComplated ? + $"版本 {version.Version} 下载完成!" : + $"版本 {version.Version} 下载失败!"); +} -### 示例 +void OnMultiAllDownloadCompleted(object arg1, MultiAllDownloadCompletedEventArgs arg2) +{ + Console.WriteLine(arg2.IsAllDownloadCompleted ? + "所有下载任务已完成!" : + $"下载任务失败!失败数量:{arg2.FailedVersions.Count}"); +} -GeneralUpdateBootstrap使用代码示例 [进入](https://github.com/GeneralLibrary/GeneralUpdate-Samples/blob/main/src/Upgrade/Program.cs)。 +void OnMultiDownloadError(object arg1, MultiDownloadErrorEventArgs arg2) +{ + var version = arg2.Version as VersionInfo; + Console.WriteLine($"版本 {version.Version} 下载错误:{arg2.Exception}"); +} -![](imgs/muti_donwload.png) +void OnException(object arg1, ExceptionEventArgs arg2) +{ + Console.WriteLine($"升级异常:{arg2.Exception}"); +} +``` + +--- +## 核心 API 参考 +### GeneralUpdateBootstrap 类方法 -### 注解 +#### LaunchAsync 方法 -GeneralUpdateBootstrap提供以下能力。 +异步启动升级流程。 -#### 构造函数 +```csharp +public async Task LaunchAsync() +``` -| Constructors | | -| ------------------------ | ---------------------------------- | -| GeneralUpdateBootstrap() | 当前GeneralUpdateBootstrap构造函数 | -| base:AbstractBootstrap() | 父类AbstractBootstrap构造函数 | +**返回值:** +- 返回当前 GeneralUpdateBootstrap 实例,支持链式调用 -#### 属性 +#### Option 方法 -| Properties | | -| ------------ | -------------------- | -| Packet | 更新包信息 | -| UpdateOption | 更新操作配置设置枚举 | +设置升级选项。 -#### 方法 +```csharp +public GeneralUpdateBootstrap Option(UpdateOption option, object value) +``` -| Method | | -| -------------------------------------- | ------------------------------------------------ | -| LaunchTaskAsync() | Task异步启动更新 | -| LaunchAsync() | 启动更新 | -| Option() | 设置更新配置。 | -| GetOption() | 获取更新配置。 | -| AddListenerMultiAllDownloadCompleted() | 监听所有更新版本下载完成事件 | -| AddListenerMultiDownloadCompleted() | 监听每个版本下载完成事件 | -| AddListenerMultiDownloadError() | 监听每个版本下载异常的事件 | -| AddListenerMultiDownloadStatistics() | 监听每个版本下载统计信息\下载进度事件 | -| AddListenerException() | 监听更新组件内部的所有异常 | -| SetFieldMappings() | 设置字段映射表,用于解析所有驱动包的信息的字符串 | +**参数:** +- `option`: 升级选项枚举 +- `value`: 选项值 +**示例:** +```csharp +.Option(UpdateOption.Drive, true) // 启用驱动升级 +``` + +#### AddListenerMultiDownloadStatistics 方法 + +监听下载统计信息(速度、进度、剩余时间等)。 + +```csharp +public GeneralUpdateBootstrap AddListenerMultiDownloadStatistics( + Action callbackAction) +``` + +#### AddListenerMultiDownloadCompleted 方法 + +监听单个更新包下载完成事件。 + +```csharp +public GeneralUpdateBootstrap AddListenerMultiDownloadCompleted( + Action callbackAction) +``` + +#### AddListenerMultiAllDownloadCompleted 方法 + +监听所有版本下载完成事件。 + +```csharp +public GeneralUpdateBootstrap AddListenerMultiAllDownloadCompleted( + Action callbackAction) +``` + +#### AddListenerMultiDownloadError 方法 + +监听每个版本下载错误事件。 + +```csharp +public GeneralUpdateBootstrap AddListenerMultiDownloadError( + Action callbackAction) +``` + +#### AddListenerException 方法 + +监听升级组件内部所有异常。 + +```csharp +public GeneralUpdateBootstrap AddListenerException( + Action callbackAction) +``` + +#### SetFieldMappings 方法 + +设置字段映射表,用于解析驱动包信息。 + +```csharp +public GeneralUpdateBootstrap SetFieldMappings(Dictionary fieldMappings) +``` +**参数:** +- `fieldMappings`: 字段映射字典,键为英文字段名,值为本地化字段名 + +--- + +## 配置类详解 + +### UpdateOption 枚举 + +```csharp +public enum UpdateOption +{ + /// + /// 是否启用驱动升级功能 + /// + Drive +} +``` + +### Packet 类 + +升级包信息类,由 ClientCore 通过参数传递给 Core: + +```csharp +public class Packet +{ + /// + /// 主更新检查 API 地址 + /// + public string MainUpdateUrl { get; set; } + + /// + /// 应用类型:1=客户端应用,2=更新应用 + /// + public int AppType { get; set; } + + /// + /// 更新检查 API 地址 + /// + public string UpdateUrl { get; set; } + + /// + /// 需要启动的应用程序名称 + /// + public string AppName { get; set; } + + /// + /// 主应用程序名称 + /// + public string MainAppName { get; set; } + + /// + /// 更新包文件格式(默认为 Zip) + /// + public string Format { get; set; } + + /// + /// 是否需要升级更新应用 + /// + public bool IsUpgradeUpdate { get; set; } + + /// + /// 是否需要更新主应用 + /// + public bool IsMainUpdate { get; set; } + + /// + /// 更新日志网页 URL + /// + public string UpdateLogUrl { get; set; } + + /// + /// 需要更新的版本信息列表 + /// + public List UpdateVersions { get; set; } + + /// + /// 文件操作编码格式 + /// + public Encoding Encoding { get; set; } + + /// + /// 下载超时时间(秒) + /// + public int DownloadTimeOut { get; set; } + + /// + /// 应用密钥,与服务器约定 + /// + public string AppSecretKey { get; set; } + + /// + /// 当前客户端版本 + /// + public string ClientVersion { get; set; } + + /// + /// 最新版本 + /// + public string LastVersion { get; set; } + + /// + /// 安装路径(用于更新文件逻辑) + /// + public string InstallPath { get; set; } + + /// + /// 下载文件的临时存储路径 + /// + public string TempPath { get; set; } + + /// + /// 升级终端程序的配置参数(Base64 编码) + /// + public string ProcessBase64 { get; set; } + + /// + /// 当前策略所属平台(Windows/Linux/Mac) + /// + public string Platform { get; set; } + + /// + /// 黑名单文件列表 + /// + public List BlackFiles { get; set; } + + /// + /// 黑名单文件格式列表 + /// + public List BlackFormats { get; set; } + + /// + /// 是否启用驱动升级功能 + /// + public bool DriveEnabled { get; set; } +} +``` + +--- + +## 实际使用示例 + +### 示例 1:基本升级流程 + +```csharp +using GeneralUpdate.Common.Download; +using GeneralUpdate.Common.Internal; +using GeneralUpdate.Common.Shared.Object; +using GeneralUpdate.Core; + +try +{ + Console.WriteLine("升级程序初始化..."); + + // 启动升级流程 + await new GeneralUpdateBootstrap() + .AddListenerMultiDownloadStatistics((sender, args) => + { + var version = args.Version as VersionInfo; + Console.WriteLine($"[{version.Version}] 下载进度: {args.ProgressPercentage}%"); + }) + .AddListenerException((sender, args) => + { + Console.WriteLine($"升级异常: {args.Exception.Message}"); + }) + .LaunchAsync(); + + Console.WriteLine("升级完成!"); +} +catch (Exception e) +{ + Console.WriteLine($"升级失败: {e.Message}"); +} +``` + +### 示例 2:启用驱动升级 + +```csharp +using GeneralUpdate.Core; +using GeneralUpdate.Common.Internal.Bootstrap; + +// 中文字段映射表 +var fieldMappingsCN = new Dictionary +{ + { "DriverName", "驱动名称" }, + { "DriverVersion", "驱动版本" }, + { "DriverDescription", "驱动描述" }, + { "InstallPath", "安装路径" } +}; + +await new GeneralUpdateBootstrap() + // 设置字段映射表 + .SetFieldMappings(fieldMappingsCN) + // 启用驱动更新 + .Option(UpdateOption.Drive, true) + .AddListenerException((sender, args) => + { + Console.WriteLine($"升级异常: {args.Exception.Message}"); + }) + .LaunchAsync(); +``` + +### 示例 3:完整事件监听 + +```csharp +using GeneralUpdate.Core; +using GeneralUpdate.Common.Download; +using GeneralUpdate.Common.Shared.Object; + +await new GeneralUpdateBootstrap() + // 下载统计 + .AddListenerMultiDownloadStatistics((sender, args) => + { + var version = args.Version as VersionInfo; + Console.WriteLine($"[{version.Version}]"); + Console.WriteLine($" 速度: {args.Speed}"); + Console.WriteLine($" 进度: {args.ProgressPercentage}%"); + Console.WriteLine($" 已下载: {args.BytesReceived} / {args.TotalBytesToReceive}"); + Console.WriteLine($" 剩余时间: {args.Remaining}"); + }) + // 单个下载完成 + .AddListenerMultiDownloadCompleted((sender, args) => + { + var version = args.Version as VersionInfo; + string status = args.IsComplated ? "✓ 成功" : "✗ 失败"; + Console.WriteLine($"版本 {version.Version} 下载{status}"); + }) + // 所有下载完成 + .AddListenerMultiAllDownloadCompleted((sender, args) => + { + if (args.IsAllDownloadCompleted) + { + Console.WriteLine("✓ 所有版本下载完成,开始安装..."); + } + else + { + Console.WriteLine($"✗ 下载失败,{args.FailedVersions.Count} 个版本失败:"); + foreach (var version in args.FailedVersions) + { + Console.WriteLine($" - {version}"); + } + } + }) + // 下载错误 + .AddListenerMultiDownloadError((sender, args) => + { + var version = args.Version as VersionInfo; + Console.WriteLine($"✗ 版本 {version.Version} 错误:"); + Console.WriteLine($" {args.Exception.Message}"); + }) + // 异常处理 + .AddListenerException((sender, args) => + { + Console.WriteLine("⚠ 升级过程异常:"); + Console.WriteLine($" 错误: {args.Exception.Message}"); + Console.WriteLine($" 堆栈: {args.Exception.StackTrace}"); + }) + .LaunchAsync(); +``` + +### 示例 4:自定义升级流程 + +```csharp +using GeneralUpdate.Core; +using GeneralUpdate.Common.Download; +using GeneralUpdate.Common.Shared.Object; + +// 记录升级开始时间 +var startTime = DateTime.Now; +var downloadedVersions = new List(); + +await new GeneralUpdateBootstrap() + .AddListenerMultiDownloadCompleted((sender, args) => + { + if (args.IsComplated) + { + var version = args.Version as VersionInfo; + downloadedVersions.Add(version.Version); + } + }) + .AddListenerMultiAllDownloadCompleted((sender, args) => + { + if (args.IsAllDownloadCompleted) + { + var duration = DateTime.Now - startTime; + Console.WriteLine($"升级完成!"); + Console.WriteLine($"总耗时: {duration.TotalSeconds:F2} 秒"); + Console.WriteLine($"已更新版本: {string.Join(", ", downloadedVersions)}"); + } + }) + .AddListenerException((sender, args) => + { + // 记录日志到文件 + File.AppendAllText("upgrade_error.log", + $"[{DateTime.Now}] {args.Exception}\n"); + }) + .LaunchAsync(); +``` + +--- + +## 注意事项与警告 + +### ⚠️ 重要提示 + +1. **进程隔离** + - Core 必须作为独立进程运行,不能在主程序中直接调用 + - 升级时主程序必须完全关闭,否则文件替换会失败 + +2. **参数传递** + - ClientCore 通过 Base64 编码的参数传递配置给 Core + - 确保参数传递过程中不会被截断或损坏 + +3. **文件权限** + - 在 Windows 上可能需要管理员权限替换系统目录中的文件 + - 在 Linux/macOS 上需要适当的文件系统权限 + +4. **驱动升级** + - 驱动升级功能需要系统级权限 + - 建议在测试环境充分验证后再使用 + +5. **回滚机制** + - Core 不直接提供回滚功能,但保留了备份文件 + - 如需回滚,可使用 ClientCore 的备份功能 + +### 💡 最佳实践 + +- **日志记录**:实现完整的异常监听,记录升级过程中的所有问题 +- **超时设置**:根据网络环境合理设置下载超时时间 +- **进度反馈**:向用户显示升级进度,提升用户体验 +- **错误处理**:升级失败时提供清晰的错误信息和解决方案 +- **测试验证**:在各种网络条件下测试升级流程的稳定性 + +--- + +## 适用平台 + +| 产品 | 版本 | +| ------------------ | ----------------- | +| .NET | 5, 6, 7, 8, 9 | +| .NET Framework | 4.6.1 | +| .NET Standard | 2.0 | +| .NET Core | 2.0 | + +--- -### 适用于 +## 相关资源 -| 产品 | 版本 | -| -------------- | ------------- | -| .NET | 5、6、7、8、9 | -| .NET Framework | 4.6.1 | -| .NET Standard | 2.0 | -| .NET Core | 2.0 | +- **示例代码**:[查看 GitHub 示例](https://github.com/GeneralLibrary/GeneralUpdate-Samples/blob/main/src/Upgrade/Program.cs) +- **主仓库**:[GeneralUpdate 项目](https://github.com/GeneralLibrary/GeneralUpdate) +- **相关组件**:[GeneralUpdate.ClientCore](./GeneralUpdate.ClientCore.md) | [GeneralUpdate.Bowl](./GeneralUpdate.Bowl.md) diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/doc/GeneralUpdate.Differential.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/doc/GeneralUpdate.Differential.md index 20d7f65..edb101a 100644 --- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/doc/GeneralUpdate.Differential.md +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/doc/GeneralUpdate.Differential.md @@ -2,108 +2,447 @@ sidebar_position: 6 --- -### 定义 +# GeneralUpdate.Differential -命名空间:GeneralUpdate.Differential +## 组件概览 -程序集:GeneralUpdate.Core.dll +**GeneralUpdate.Differential** 是 GeneralUpdate 框架中负责二进制差异更新的核心组件。该组件提供了强大的差异算法,可以精确识别两个版本之间的文件变化,生成高效的增量补丁包,并支持补丁还原操作。通过使用差异更新,可以显著减少更新包的大小和下载时间,特别适合频繁发布更新的应用场景。 +**命名空间:** `GeneralUpdate.Differential` +**程序集:** `GeneralUpdate.Core.dll` +```csharp +public sealed class DifferentialCore +``` -该组件提供文件的二进制差分补丁文件生成(算法),文件增量识别(版本差异)、删除文件识别(版本差异)、黑名单、补丁还原等能力。 +--- -```c# -public sealed class DifferentialCore +## 核心特性 + +### 1. 增量识别 +- 精确识别新增、修改、删除的文件 +- 智能文件版本对比 +- 支持跳过指定文件和格式 + +### 2. 二进制补丁生成 +- 高效的二进制差异算法 +- 最小化补丁文件大小 +- 快速补丁生成速度 + +### 3. 补丁还原 +- 安全的补丁应用流程 +- 自动处理文件依赖关系 +- 完整性验证机制 + +### 4. 黑名单支持 +- 文件级黑名单 +- 格式级黑名单 +- 灵活的过滤规则 + +--- + +## 快速开始 + +### 安装 + +通过 NuGet 安装 GeneralUpdate.Differential(包含在 Core 包中): + +```bash +dotnet add package GeneralUpdate.Core ``` +### 初始化与使用 +以下示例展示了如何使用 DifferentialCore 进行增量识别和补丁操作: -### 示例 +```csharp +using GeneralUpdate.Differential; -以下示例定义方法,以包含增量识别,生成二进制补丁、补丁还原、设置黑名单示例GeneralUpdate.Tools项目中的打包工具也是强依赖此组件。 +// 增量识别并生成二进制补丁 +var sourcePath = @"D:\packet\app"; // 旧版本路径 +var targetPath = @"D:\packet\release"; // 新版本路径 +var patchPath = @"D:\packet\patch"; // 补丁输出路径 -```c# -//增量识别,生成二进制补丁 -public async Task TestDifferentialClean() -{ - //上一个版本的客户端文件夹路径 - var path1 = "D:\\packet\\source"; - //最新版本客户端文件夹路径 - var path2 = "D:\\packet\\target"; - //补丁文件生成路径 - var path3 = "D:\\packet\\patchs"; - await DifferentialCore.Instance.Clean(path1, path2, path3); -} +await DifferentialCore.Instance?.Clean(sourcePath, targetPath, patchPath); + +// 应用补丁(还原) +await DifferentialCore.Instance?.Dirty(sourcePath, patchPath); +``` + +--- + +## 核心 API 参考 + +### DifferentialCore 类 + +#### Instance 属性 + +获取 DifferentialCore 的单例实例。 + +```csharp +public static DifferentialCore Instance { get; } +``` + +#### Clean 方法 + +执行增量识别、删除文件识别,并生成二进制补丁文件。 + +**方法签名:** + +```csharp +public async Task Clean(string sourcePath, string targetPath, string patchPath = null) +``` -//补丁还原 -public async Task TestDifferentialDirty() +**参数:** +- `sourcePath`: 旧版本文件夹路径 +- `targetPath`: 新版本文件夹路径 +- `patchPath`: 补丁文件输出目录(可选) + +**功能说明:** +1. 对比 sourcePath 和 targetPath 两个目录 +2. 识别新增、修改、删除的文件 +3. 为修改的文件生成二进制差异补丁 +4. 将补丁和新增文件保存到 patchPath + +**示例:** +```csharp +// 生成从 v1.0.0 到 v1.1.0 的补丁包 +var source = @"D:\MyApp\v1.0.0"; +var target = @"D:\MyApp\v1.1.0"; +var patch = @"D:\MyApp\patches\v1.1.0"; + +await DifferentialCore.Instance.Clean(source, target, patch); +// 结果:patch 目录包含所有必要的增量更新文件 +``` + +#### Dirty 方法 + +应用补丁,将旧版本文件更新到新版本。 + +**方法签名:** + +```csharp +public async Task Dirty(string appPath, string patchPath) +``` + +**参数:** +- `appPath`: 客户端应用程序目录(当前版本) +- `patchPath`: 补丁文件路径 + +**功能说明:** +1. 读取 patchPath 中的补丁文件 +2. 将补丁应用到 appPath 中的对应文件 +3. 处理新增文件的复制 +4. 处理删除文件的移除 + +**示例:** +```csharp +// 将补丁应用到当前应用程序 +var appDir = AppDomain.CurrentDomain.BaseDirectory; +var patchDir = Path.Combine(appDir, "temp", "patches"); + +await DifferentialCore.Instance.Dirty(appDir, patchDir); +// 结果:应用程序更新到新版本 +``` + +--- + +## 实际使用示例 + +### 示例 1:基本补丁生成 + +```csharp +using GeneralUpdate.Differential; + +public async Task GeneratePatchAsync() { - //当前版本的客户端文件夹路径 - var path1 = "D:\\packet\\source"; - //补丁文件生成路径 - var path2 = "D:\\packet\\patchs"; - await DifferentialCore.Instance.Dirty(path1, path2); + try + { + // 版本路径 + var oldVersion = @"D:\MyApp\1.0.0"; + var newVersion = @"D:\MyApp\1.0.1"; + var patchOutput = @"D:\MyApp\patches\1.0.1"; + + Console.WriteLine("开始生成补丁..."); + + // 生成补丁 + await DifferentialCore.Instance.Clean(oldVersion, newVersion, patchOutput); + + Console.WriteLine($"补丁生成完成!输出目录:{patchOutput}"); + + // 显示补丁信息 + var patchFiles = Directory.GetFiles(patchOutput, "*.*", SearchOption.AllDirectories); + Console.WriteLine($"生成了 {patchFiles.Length} 个补丁文件"); + + long totalSize = patchFiles.Sum(f => new FileInfo(f).Length); + Console.WriteLine($"总补丁大小:{totalSize / 1024.0:F2} KB"); + } + catch (Exception ex) + { + Console.WriteLine($"补丁生成失败:{ex.Message}"); + } } ``` +### 示例 2:应用补丁 +```csharp +using GeneralUpdate.Differential; -### 注解 +public async Task ApplyPatchAsync() +{ + try + { + // 应用程序目录 + var appDirectory = @"D:\MyApp\current"; + // 补丁目录 + var patchDirectory = @"D:\MyApp\patches\1.0.1"; + + Console.WriteLine("开始应用补丁..."); + + // 验证补丁存在 + if (!Directory.Exists(patchDirectory)) + { + throw new DirectoryNotFoundException($"补丁目录不存在:{patchDirectory}"); + } + + // 应用补丁 + await DifferentialCore.Instance.Dirty(appDirectory, patchDirectory); + + Console.WriteLine("补丁应用成功!应用程序已更新到新版本。"); + } + catch (Exception ex) + { + Console.WriteLine($"补丁应用失败:{ex.Message}"); + } +} +``` -DifferentialCore提供增量识别,生成二进制补丁、补丁还原、设置黑名单能力。 +### 示例 3:完整的补丁流程 -#### 方法 +```csharp +using GeneralUpdate.Differential; +using System.IO.Compression; -| 名称 | 类型 | 备注 | -| ------- | ---- | ---------------------------------------------------- | -| Clean() | 方法 | 增量识别,删除文件识别,生成二进制补丁文件 | -| Dirty() | 方法 | 补丁还原(将补丁打到旧的客户端文件上达到更新的目的) | +public class PatchManager +{ + // 生成并打包补丁 + public async Task CreatePatchPackageAsync( + string oldVersionPath, + string newVersionPath, + string outputPath) + { + try + { + // 1. 生成补丁文件 + var tempPatchDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempPatchDir); + + Console.WriteLine($"正在生成补丁..."); + await DifferentialCore.Instance.Clean(oldVersionPath, newVersionPath, tempPatchDir); + + // 2. 压缩补丁文件 + var patchZipPath = Path.Combine(outputPath, "patch_1.0.1.zip"); + Console.WriteLine($"正在打包补丁..."); + + if (File.Exists(patchZipPath)) + File.Delete(patchZipPath); + + ZipFile.CreateFromDirectory(tempPatchDir, patchZipPath, + CompressionLevel.Optimal, false); + + // 3. 清理临时文件 + Directory.Delete(tempPatchDir, true); + + var patchSize = new FileInfo(patchZipPath).Length; + Console.WriteLine($"补丁包创建成功:{patchZipPath}"); + Console.WriteLine($"补丁包大小:{patchSize / 1024.0:F2} KB"); + + return patchZipPath; + } + catch (Exception ex) + { + Console.WriteLine($"创建补丁包失败:{ex.Message}"); + throw; + } + } + + // 解压并应用补丁 + public async Task ApplyPatchPackageAsync(string appPath, string patchZipPath) + { + try + { + // 1. 解压补丁包 + var tempExtractDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempExtractDir); + + Console.WriteLine($"正在解压补丁包..."); + ZipFile.ExtractToDirectory(patchZipPath, tempExtractDir); + + // 2. 应用补丁 + Console.WriteLine($"正在应用补丁..."); + await DifferentialCore.Instance.Dirty(appPath, tempExtractDir); + + // 3. 清理临时文件 + Directory.Delete(tempExtractDir, true); + + Console.WriteLine($"补丁应用成功!"); + } + catch (Exception ex) + { + Console.WriteLine($"应用补丁包失败:{ex.Message}"); + throw; + } + } +} +// 使用示例 +var manager = new PatchManager(); + +// 创建补丁包 +var patchZip = await manager.CreatePatchPackageAsync( + @"D:\MyApp\1.0.0", + @"D:\MyApp\1.0.1", + @"D:\MyApp\releases" +); + +// 应用补丁包 +await manager.ApplyPatchPackageAsync( + @"D:\MyApp\current", + patchZip +); +``` +### 示例 4:带进度显示的补丁操作 -### 🌼Clean() +```csharp +using GeneralUpdate.Differential; -**方法** +public class ProgressivePatchManager +{ + public async Task GeneratePatchWithProgressAsync( + string sourcePath, + string targetPath, + string patchPath, + IProgress progress) + { + try + { + progress?.Report("开始扫描文件差异..."); + + // 在实际场景中,可以在 Clean 前后添加进度报告 + await DifferentialCore.Instance.Clean(sourcePath, targetPath, patchPath); + + progress?.Report("补丁生成完成!"); + + // 统计信息 + var files = Directory.GetFiles(patchPath, "*.*", SearchOption.AllDirectories); + progress?.Report($"共生成 {files.Length} 个补丁文件"); + } + catch (Exception ex) + { + progress?.Report($"错误:{ex.Message}"); + throw; + } + } + + public async Task ApplyPatchWithProgressAsync( + string appPath, + string patchPath, + IProgress progress) + { + try + { + progress?.Report("开始应用补丁..."); + + await DifferentialCore.Instance.Dirty(appPath, patchPath); + + progress?.Report("补丁应用成功!"); + } + catch (Exception ex) + { + progress?.Report($"错误:{ex.Message}"); + throw; + } + } +} -生成补丁文件[不能包含文件名相同但扩展名不同的文件]。 +// 使用示例 +var manager = new ProgressivePatchManager(); +var progress = new Progress(msg => Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] {msg}")); -```c# -public async Task Clean(string sourcePath, string targetPath, string patchPath = null); +await manager.GeneratePatchWithProgressAsync( + @"D:\MyApp\1.0.0", + @"D:\MyApp\1.0.1", + @"D:\MyApp\patches\1.0.1", + progress +); ``` +--- -**参数** +## 注意事项与警告 -**sourcePath** 上一个版本的文件夹路径。 +### ⚠️ 重要提示 -**targetPath** 最近版本的文件夹路径。 +1. **文件名限制** + - 不能包含同名但扩展名不同的文件(如 file.txt 和 file.log) + - 建议使用唯一的文件名命名规则 -**patchPath** 将发现的增量更新文件存储在临时目录中。 +2. **目录结构** + - 源目录和目标目录的相对结构应保持一致 + - 补丁生成时会保留目录层次关系 +3. **磁盘空间** + - 确保有足够的磁盘空间存储补丁文件 + - 二进制差异补丁通常比完整文件小,但仍需要临时空间 +4. **文件占用** + - 应用补丁时,确保目标文件没有被其他进程占用 + - 建议在应用程序关闭后应用补丁 -### 🌼Dirty() +5. **备份建议** + - 在应用补丁前建议备份原始文件 + - 可以使用 ClientCore 的 BackUp 选项自动备份 -**方法** +### 💡 最佳实践 -应用补丁[不能包含文件名相同但扩展名不同的文件]。 +- **版本管理**:为每个版本维护独立的补丁包,便于版本追踪和回滚 +- **补丁验证**:生成补丁后进行验证测试,确保补丁可以正确应用 +- **增量更新**:优先使用差异更新而非全量更新,可节省 50%-90% 的下载量 +- **错误处理**:实现完整的异常捕获和错误恢复机制 +- **性能优化**:对于大文件,差异算法的性能优势更加明显 -```c# -public async Task Dirty(string appPath, string patchPath); -``` +### 🔍 工作原理 -**参数** +**Clean 方法工作流程:** +1. 扫描源目录和目标目录中的所有文件 +2. 比较文件的MD5哈希值以识别变化 +3. 对于修改的文件,使用二进制差异算法生成补丁 +4. 对于新增文件,直接复制到补丁目录 +5. 记录删除的文件列表 -**appPath** 客户端应用程序目录。 +**Dirty 方法工作流程:** +1. 读取补丁目录中的所有文件 +2. 对于补丁文件,应用到对应的原文件上 +3. 对于新增文件,直接复制到应用目录 +4. 根据删除列表移除相应文件 +5. 验证更新完整性 -**patchPath** 补丁文件路径。 +--- + +## 适用平台 +| 产品 | 版本 | +| ------------------ | ----------------- | +| .NET | 5, 6, 7, 8, 9 | +| .NET Framework | 4.6.1 | +| .NET Standard | 2.0 | +| .NET Core | 2.0 | +--- -### 适用于 +## 相关资源 -| 产品 | 版本 | -| -------------- | ------------- | -| .NET | 5、6、7、8、9 | -| .NET Framework | 4.6.1 | -| .NET Standard | 2.0 | -| .NET Core | 2.0 | \ No newline at end of file +- **示例代码**:[查看 GitHub 示例](https://github.com/GeneralLibrary/GeneralUpdate-Samples/tree/main/src/Diff) +- **主仓库**:[GeneralUpdate 项目](https://github.com/GeneralLibrary/GeneralUpdate) +- **打包工具**:GeneralUpdate.PacketTool 项目依赖此组件实现差异打包