diff --git a/.gitignore b/.gitignore index 56bb423..0e4c3bb 100644 --- a/.gitignore +++ b/.gitignore @@ -194,4 +194,8 @@ FakesAssemblies/ *.v6.1 .idea/ -.vs/ \ No newline at end of file +.vs/ + +# Generated extensions directory +**/extensions/ +*.slnx \ No newline at end of file diff --git a/src/Drivelution/DrivelutionSample/DrivelutionSample.csproj b/src/Drivelution/DrivelutionSample/DrivelutionSample.csproj new file mode 100644 index 0000000..7aa88ef --- /dev/null +++ b/src/Drivelution/DrivelutionSample/DrivelutionSample.csproj @@ -0,0 +1,14 @@ + + + + Exe + net10.0 + enable + enable + + + + + + + diff --git a/src/Drivelution/DrivelutionSample/DrivelutionSample.sln b/src/Drivelution/DrivelutionSample/DrivelutionSample.sln new file mode 100644 index 0000000..f2c5200 --- /dev/null +++ b/src/Drivelution/DrivelutionSample/DrivelutionSample.sln @@ -0,0 +1,34 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.31903.59 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DrivelutionSample", "DrivelutionSample.csproj", "{8015E777-C917-47A3-A335-56EBFB7063F1}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {8015E777-C917-47A3-A335-56EBFB7063F1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8015E777-C917-47A3-A335-56EBFB7063F1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8015E777-C917-47A3-A335-56EBFB7063F1}.Debug|x64.ActiveCfg = Debug|Any CPU + {8015E777-C917-47A3-A335-56EBFB7063F1}.Debug|x64.Build.0 = Debug|Any CPU + {8015E777-C917-47A3-A335-56EBFB7063F1}.Debug|x86.ActiveCfg = Debug|Any CPU + {8015E777-C917-47A3-A335-56EBFB7063F1}.Debug|x86.Build.0 = Debug|Any CPU + {8015E777-C917-47A3-A335-56EBFB7063F1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8015E777-C917-47A3-A335-56EBFB7063F1}.Release|Any CPU.Build.0 = Release|Any CPU + {8015E777-C917-47A3-A335-56EBFB7063F1}.Release|x64.ActiveCfg = Release|Any CPU + {8015E777-C917-47A3-A335-56EBFB7063F1}.Release|x64.Build.0 = Release|Any CPU + {8015E777-C917-47A3-A335-56EBFB7063F1}.Release|x86.ActiveCfg = Release|Any CPU + {8015E777-C917-47A3-A335-56EBFB7063F1}.Release|x86.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/src/Drivelution/DrivelutionSample/Program.cs b/src/Drivelution/DrivelutionSample/Program.cs new file mode 100644 index 0000000..d769cc5 --- /dev/null +++ b/src/Drivelution/DrivelutionSample/Program.cs @@ -0,0 +1,279 @@ +using GeneralUpdate.Drivelution; +using GeneralUpdate.Drivelution.Abstractions.Configuration; +using GeneralUpdate.Drivelution.Abstractions.Models; + +try +{ + Console.WriteLine($"=== GeneralUpdate.Drivelution 示例程序 ==="); + Console.WriteLine($"=== GeneralUpdate.Drivelution Sample Program ===\n"); + Console.WriteLine($"初始化时间:{DateTime.Now}"); + Console.WriteLine($"Initialization Time: {DateTime.Now}\n"); + + // ======================================== + // 1. 获取平台信息 / Get Platform Information + // ======================================== + Console.WriteLine("=== 1. 获取平台信息 / Get Platform Information ==="); + var platformInfo = GeneralDrivelution.GetPlatformInfo(); + Console.WriteLine($"平台 / Platform: {platformInfo.Platform}"); + Console.WriteLine($"操作系统 / Operating System: {platformInfo.OperatingSystem}"); + Console.WriteLine($"架构 / Architecture: {platformInfo.Architecture}"); + Console.WriteLine($"系统版本 / System Version: {platformInfo.SystemVersion}"); + Console.WriteLine($"是否支持 / Is Supported: {(platformInfo.IsSupported ? "是/Yes" : "否/No")}"); + Console.WriteLine($"\n详细信息 / Full Info: {platformInfo}"); + Console.WriteLine("\n" + new string('=', 80) + "\n"); + + // ======================================== + // 2. 创建驱动更新实例 / Create Driver Updater Instance + // ======================================== + Console.WriteLine("=== 2. 创建驱动更新实例 / Create Driver Updater Instance ==="); + + // 使用默认配置创建 / Create with default configuration + var updater = GeneralDrivelution.Create(); + Console.WriteLine("✓ 默认实例创建成功 / Default instance created successfully"); + + // 使用自定义配置创建 / Create with custom configuration + var options = new DrivelutionOptions + { + DefaultBackupPath = "./driver_backups", + DefaultRetryCount = 5, + DefaultRetryIntervalSeconds = 3, + AutoCleanupBackups = true, + BackupsToKeep = 5 + }; + var customUpdater = GeneralDrivelution.Create(options); + Console.WriteLine("✓ 自定义实例创建成功 / Custom instance created successfully"); + Console.WriteLine($" 备份路径 / Backup Path: {options.DefaultBackupPath}"); + Console.WriteLine($" 重试次数 / Retry Count: {options.DefaultRetryCount}"); + Console.WriteLine($" 自动清理备份 / Auto Cleanup Backups: {options.AutoCleanupBackups}"); + Console.WriteLine("\n" + new string('=', 80) + "\n"); + + // ======================================== + // 3. 从目录读取驱动信息 / Get Drivers from Directory + // ======================================== + Console.WriteLine("=== 3. 从目录读取驱动信息 / Get Drivers from Directory ==="); + + // 创建测试驱动目录 / Create test driver directory + var testDriverDir = Path.Combine(Path.GetTempPath(), "test_drivers"); + Directory.CreateDirectory(testDriverDir); + Console.WriteLine($"测试目录 / Test Directory: {testDriverDir}"); + + // 根据平台创建测试驱动文件 / Create test driver files based on platform + if (platformInfo.Platform == "Windows") + { + // 创建模拟的 Windows INF 文件 / Create mock Windows INF file + var infFile = Path.Combine(testDriverDir, "test_driver.inf"); + var infContent = @" +[Version] +Signature=""$Windows NT$"" +Class=System +ClassGuid={4d36e97d-e325-11ce-bfc1-08002be10318} +Provider=%ManufacturerName% +DriverVer=02/12/2024,1.2.3.0 +CatalogFile=test_driver.cat + +[Manufacturer] +%ManufacturerName%=Standard,NTamd64 + +[Standard.NTamd64] +%DeviceDesc%=TestDriver_Install,PCI\VEN_8086&DEV_1234 + +[TestDriver_Install] +CopyFiles=Drivers_Dir + +[Drivers_Dir] +test_driver.sys + +[DestinationDirs] +Drivers_Dir=12 + +[Strings] +ManufacturerName=""Sample Driver Manufacturer"" +DeviceDesc=""Sample Test Driver"" +"; + File.WriteAllText(infFile, infContent); + Console.WriteLine($"✓ 已创建测试 INF 文件 / Created test INF file: {Path.GetFileName(infFile)}"); + } + else if (platformInfo.Platform == "Linux") + { + // 创建模拟的 Linux 内核模块文件 / Create mock Linux kernel module file + var koFile = Path.Combine(testDriverDir, "test_driver.ko"); + File.WriteAllText(koFile, "Mock Linux kernel module content"); + Console.WriteLine($"✓ 已创建测试 KO 文件 / Created test KO file: {Path.GetFileName(koFile)}"); + } + + // 获取目录中的驱动信息 / Get drivers from directory + var drivers = await GeneralDrivelution.GetDriversFromDirectoryAsync(testDriverDir); + Console.WriteLine($"\n发现驱动数量 / Drivers Found: {drivers.Count}"); + + if (drivers.Count > 0) + { + foreach (var driver in drivers) + { + Console.WriteLine($"\n驱动信息 / Driver Information:"); + Console.WriteLine($" 名称 / Name: {driver.Name}"); + Console.WriteLine($" 版本 / Version: {driver.Version}"); + Console.WriteLine($" 文件路径 / File Path: {driver.FilePath}"); + Console.WriteLine($" 目标操作系统 / Target OS: {driver.TargetOS}"); + Console.WriteLine($" 架构 / Architecture: {driver.Architecture}"); + Console.WriteLine($" 哈希值 / Hash: {driver.Hash}"); + Console.WriteLine($" 哈希算法 / Hash Algorithm: {driver.HashAlgorithm}"); + } + } + else + { + Console.WriteLine("未发现驱动文件 / No driver files found"); + } + Console.WriteLine("\n" + new string('=', 80) + "\n"); + + // ======================================== + // 4. 验证驱动文件 / Validate Driver File + // ======================================== + Console.WriteLine("=== 4. 验证驱动文件 / Validate Driver File ==="); + + // 创建测试驱动文件 / Create test driver file + var testDriverFile = Path.Combine(testDriverDir, "sample_driver.sys"); + File.WriteAllText(testDriverFile, "Sample driver binary content"); + + var driverInfo = new DriverInfo + { + Name = "Sample Driver", + Version = "1.0.0", + FilePath = testDriverFile, + TargetOS = platformInfo.OperatingSystem, + Architecture = platformInfo.Architecture, + Description = "示例驱动程序 / Sample driver for demonstration", + ReleaseDate = DateTime.Now + }; + + Console.WriteLine($"驱动名称 / Driver Name: {driverInfo.Name}"); + Console.WriteLine($"驱动版本 / Driver Version: {driverInfo.Version}"); + Console.WriteLine($"文件路径 / File Path: {driverInfo.FilePath}"); + + var isValid = await GeneralDrivelution.ValidateAsync(driverInfo); + Console.WriteLine($"\n验证结果 / Validation Result: {(isValid ? "✓ 通过/Passed" : "✗ 失败/Failed")}"); + Console.WriteLine("\n" + new string('=', 80) + "\n"); + + // ======================================== + // 5. 快速更新驱动 / Quick Update Driver + // ======================================== + Console.WriteLine("=== 5. 快速更新驱动 / Quick Update Driver ==="); + Console.WriteLine("注意:此示例仅演示API调用,不会实际安装驱动"); + Console.WriteLine("Note: This example only demonstrates API usage, will not actually install drivers\n"); + + // 使用默认策略的快速更新 / Quick update with default strategy + Console.WriteLine("使用默认策略 / Using default strategy:"); + Console.WriteLine(" • 需要备份 / Requires Backup: 是/Yes"); + Console.WriteLine(" • 重试次数 / Retry Count: 3"); + Console.WriteLine(" • 重试间隔 / Retry Interval: 5秒/seconds"); + + var quickResult = await GeneralDrivelution.QuickUpdateAsync(driverInfo); + + Console.WriteLine($"\n更新结果 / Update Result:"); + Console.WriteLine($" 状态 / Status: {quickResult.Status}"); + Console.WriteLine($" 成功 / Success: {(quickResult.Success ? "是/Yes" : "否/No")}"); + Console.WriteLine($" 开始时间 / Start Time: {quickResult.StartTime:yyyy-MM-dd HH:mm:ss}"); + Console.WriteLine($" 结束时间 / End Time: {quickResult.EndTime:yyyy-MM-dd HH:mm:ss}"); + Console.WriteLine($" 耗时 / Duration: {quickResult.DurationMs} ms"); + Console.WriteLine($" 消息 / Message: {quickResult.Message}"); + + if (quickResult.Error != null) + { + Console.WriteLine($" 错误信息 / Error: {quickResult.Error.Message}"); + } + + if (quickResult.StepLogs.Count > 0) + { + Console.WriteLine($"\n 执行步骤 / Execution Steps:"); + foreach (var log in quickResult.StepLogs) + { + Console.WriteLine($" - {log}"); + } + } + Console.WriteLine("\n" + new string('=', 80) + "\n"); + + // ======================================== + // 6. 使用自定义策略更新 / Update with Custom Strategy + // ======================================== + Console.WriteLine("=== 6. 使用自定义策略更新 / Update with Custom Strategy ==="); + + var strategy = new UpdateStrategy + { + Mode = UpdateMode.Full, + RequireBackup = true, + BackupPath = Path.Combine(testDriverDir, "backups"), + RetryCount = 5, + RetryIntervalSeconds = 3, + RestartMode = RestartMode.Prompt, + TimeoutSeconds = 120, + SkipHashValidation = false, + SkipSignatureValidation = false + }; + + Console.WriteLine("自定义策略配置 / Custom Strategy Configuration:"); + Console.WriteLine($" 更新模式 / Update Mode: {strategy.Mode}"); + Console.WriteLine($" 需要备份 / Require Backup: {(strategy.RequireBackup ? "是/Yes" : "否/No")}"); + Console.WriteLine($" 备份路径 / Backup Path: {strategy.BackupPath}"); + Console.WriteLine($" 重试次数 / Retry Count: {strategy.RetryCount}"); + Console.WriteLine($" 重试间隔 / Retry Interval: {strategy.RetryIntervalSeconds} 秒/seconds"); + Console.WriteLine($" 重启模式 / Restart Mode: {strategy.RestartMode}"); + Console.WriteLine($" 超时时间 / Timeout: {strategy.TimeoutSeconds} 秒/seconds"); + + var customResult = await GeneralDrivelution.QuickUpdateAsync(driverInfo, strategy); + + Console.WriteLine($"\n更新结果 / Update Result:"); + Console.WriteLine($" 状态 / Status: {customResult.Status}"); + Console.WriteLine($" 成功 / Success: {(customResult.Success ? "是/Yes" : "否/No")}"); + Console.WriteLine($" 备份路径 / Backup Path: {customResult.BackupPath ?? "无/None"}"); + Console.WriteLine($" 已回滚 / Rolled Back: {(customResult.RolledBack ? "是/Yes" : "否/No")}"); + Console.WriteLine($" 耗时 / Duration: {customResult.DurationMs} ms"); + Console.WriteLine("\n" + new string('=', 80) + "\n"); + + // ======================================== + // 7. 备份和回滚操作 / Backup and Rollback Operations + // ======================================== + Console.WriteLine("=== 7. 备份和回滚操作 / Backup and Rollback Operations ==="); + + // 备份驱动 / Backup driver + var backupPath = Path.Combine(testDriverDir, "manual_backup"); + Directory.CreateDirectory(backupPath); + + Console.WriteLine($"备份驱动到 / Backing up driver to: {backupPath}"); + var backupSuccess = await updater.BackupAsync(driverInfo, backupPath); + Console.WriteLine($"备份结果 / Backup Result: {(backupSuccess ? "✓ 成功/Success" : "✗ 失败/Failed")}"); + + if (backupSuccess) + { + // 模拟回滚操作 / Simulate rollback operation + Console.WriteLine($"\n从备份回滚驱动 / Rolling back driver from backup"); + var rollbackSuccess = await updater.RollbackAsync(backupPath); + Console.WriteLine($"回滚结果 / Rollback Result: {(rollbackSuccess ? "✓ 成功/Success" : "✗ 失败/Failed")}"); + } + + Console.WriteLine("\n" + new string('=', 80) + "\n"); + + // ======================================== + // 清理测试文件 / Cleanup Test Files + // ======================================== + Console.WriteLine("=== 清理 / Cleanup ==="); + if (Directory.Exists(testDriverDir)) + { + try + { + Directory.Delete(testDriverDir, true); + Console.WriteLine("✓ 测试文件已清理 / Test files cleaned up"); + } + catch (Exception ex) + { + Console.WriteLine($"✗ 清理失败 / Cleanup failed: {ex.Message}"); + } + } + + Console.WriteLine("\n=== 示例程序执行完成 / Sample Program Completed ==="); + Console.WriteLine($"完成时间:{DateTime.Now}"); + Console.WriteLine($"Completion Time: {DateTime.Now}"); +} +catch (Exception e) +{ + Console.WriteLine($"\n异常 / Exception: {e.Message}"); + Console.WriteLine($"堆栈跟踪 / Stack Trace:\n{e.StackTrace}"); +} diff --git a/src/Extension/ExtensionSample/ExtensionSample.csproj b/src/Extension/ExtensionSample/ExtensionSample.csproj new file mode 100644 index 0000000..0f1436d --- /dev/null +++ b/src/Extension/ExtensionSample/ExtensionSample.csproj @@ -0,0 +1,14 @@ + + + + Exe + net9.0 + enable + enable + + + + + + + diff --git a/src/Extension/ExtensionSample/ExtensionSample.sln b/src/Extension/ExtensionSample/ExtensionSample.sln new file mode 100644 index 0000000..129b6bb --- /dev/null +++ b/src/Extension/ExtensionSample/ExtensionSample.sln @@ -0,0 +1,34 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.31903.59 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ExtensionSample", "ExtensionSample.csproj", "{5E892380-DB04-4680-8EB2-101A351EE9DB}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {5E892380-DB04-4680-8EB2-101A351EE9DB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5E892380-DB04-4680-8EB2-101A351EE9DB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5E892380-DB04-4680-8EB2-101A351EE9DB}.Debug|x64.ActiveCfg = Debug|Any CPU + {5E892380-DB04-4680-8EB2-101A351EE9DB}.Debug|x64.Build.0 = Debug|Any CPU + {5E892380-DB04-4680-8EB2-101A351EE9DB}.Debug|x86.ActiveCfg = Debug|Any CPU + {5E892380-DB04-4680-8EB2-101A351EE9DB}.Debug|x86.Build.0 = Debug|Any CPU + {5E892380-DB04-4680-8EB2-101A351EE9DB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5E892380-DB04-4680-8EB2-101A351EE9DB}.Release|Any CPU.Build.0 = Release|Any CPU + {5E892380-DB04-4680-8EB2-101A351EE9DB}.Release|x64.ActiveCfg = Release|Any CPU + {5E892380-DB04-4680-8EB2-101A351EE9DB}.Release|x64.Build.0 = Release|Any CPU + {5E892380-DB04-4680-8EB2-101A351EE9DB}.Release|x86.ActiveCfg = Release|Any CPU + {5E892380-DB04-4680-8EB2-101A351EE9DB}.Release|x86.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/src/Extension/ExtensionSample/Program.cs b/src/Extension/ExtensionSample/Program.cs new file mode 100644 index 0000000..fc600c1 --- /dev/null +++ b/src/Extension/ExtensionSample/Program.cs @@ -0,0 +1,413 @@ +using GeneralUpdate.Extension.Common.DTOs; +using GeneralUpdate.Extension.Common.Enums; +using GeneralUpdate.Extension.Common.Models; +using GeneralUpdate.Extension.Core; +using Newtonsoft.Json; +using System.IO.Compression; + +try +{ + Console.WriteLine($"=== GeneralUpdate.Extension 示例程序 ==="); + Console.WriteLine($"=== GeneralUpdate.Extension Sample Program ===\n"); + Console.WriteLine($"初始化时间:{DateTime.Now}"); + Console.WriteLine($"Initialization Time: {DateTime.Now}\n"); + + // ======================================== + // 1. 初始化扩展主机 / Initialize Extension Host + // ======================================== + Console.WriteLine("=== 1. 初始化扩展主机 / Initialize Extension Host ==="); + + var extensionsDir = Path.Combine(Directory.GetCurrentDirectory(), "extensions"); + Directory.CreateDirectory(extensionsDir); + + var options = new ExtensionHostOptions + { + ServerUrl = "http://127.0.0.1:7391/Extension", + // Scheme = "Bearer", + // Token = "your-token-here", + HostVersion = "1.0.0", + ExtensionsDirectory = extensionsDir, + CatalogPath = Path.Combine(extensionsDir, "catalog.json") + }; + + Console.WriteLine("主机配置 / Host Configuration:"); + Console.WriteLine($" 服务器地址 / Server URL: {options.ServerUrl}"); + Console.WriteLine($" 主机版本 / Host Version: {options.HostVersion}"); + Console.WriteLine($" 扩展目录 / Extensions Directory: {options.ExtensionsDirectory}"); + Console.WriteLine($" 目录文件 / Catalog Path: {options.CatalogPath}"); + + var host = new GeneralExtensionHost(options); + Console.WriteLine("\n✓ 扩展主机创建成功 / Extension host created successfully"); + Console.WriteLine("\n" + new string('=', 80) + "\n"); + + // ======================================== + // 2. 订阅扩展更新事件 / Subscribe to Extension Update Events + // ======================================== + Console.WriteLine("=== 2. 订阅扩展更新事件 / Subscribe to Extension Update Events ==="); + + host.ExtensionUpdateStatusChanged += (sender, e) => + { + Console.WriteLine($"[事件/Event] 扩展/Extension: {e.ExtensionName ?? e.ExtensionId}"); + Console.WriteLine($" 状态/Status: {e.Status}"); + if (e.Status == ExtensionUpdateStatus.Updating) + { + Console.WriteLine($" 进度/Progress: {e.Progress}%"); + } + if (e.Status == ExtensionUpdateStatus.UpdateFailed) + { + Console.WriteLine($" 错误/Error: {e.ErrorMessage}"); + } + Console.WriteLine(); + }; + + Console.WriteLine("✓ 事件订阅成功 / Event subscription successful"); + Console.WriteLine("\n" + new string('=', 80) + "\n"); + + // ======================================== + // 3. 创建示例扩展包 / Create Sample Extension Package + // ======================================== + Console.WriteLine("=== 3. 创建示例扩展包 / Create Sample Extension Package ==="); + + var extensionId = Guid.NewGuid().ToString(); + var extensionMetadata = new ExtensionMetadata + { + Id = extensionId, + Name = "sample-extension", + DisplayName = "示例扩展 / Sample Extension", + Version = "1.0.0", + Description = "这是一个演示用的示例扩展 / This is a sample extension for demonstration", + Publisher = "GeneralUpdate Team", + Format = ".zip", + FileSize = 0, + Hash = "sample-hash-sha256", + Status = true, + SupportedPlatforms = TargetPlatform.All, + MinHostVersion = "1.0.0", + MaxHostVersion = "2.0.0", + IsPreRelease = false, + ReleaseDate = DateTime.UtcNow, + UploadTime = DateTime.UtcNow, + DownloadUrl = "http://127.0.0.1:7391/Extension/download", + Categories = "Tools,Development", + License = "MIT", + Dependencies = null + }; + + Console.WriteLine("扩展元数据 / Extension Metadata:"); + Console.WriteLine($" ID: {extensionMetadata.Id}"); + Console.WriteLine($" 名称 / Name: {extensionMetadata.Name}"); + Console.WriteLine($" 显示名称 / Display Name: {extensionMetadata.DisplayName}"); + Console.WriteLine($" 版本 / Version: {extensionMetadata.Version}"); + Console.WriteLine($" 发布者 / Publisher: {extensionMetadata.Publisher}"); + Console.WriteLine($" 支持平台 / Supported Platforms: {extensionMetadata.SupportedPlatforms}"); + Console.WriteLine($" 最小主机版本 / Min Host Version: {extensionMetadata.MinHostVersion}"); + Console.WriteLine($" 最大主机版本 / Max Host Version: {extensionMetadata.MaxHostVersion}"); + + // 创建扩展包 / Create extension package + var zipFileName = $"{extensionMetadata.Name}_{extensionMetadata.Version}.zip"; + var zipPath = Path.Combine(extensionsDir, zipFileName); + + await CreateExtensionPackage(zipPath, extensionMetadata); + + var fileInfo = new FileInfo(zipPath); + extensionMetadata.FileSize = fileInfo.Length; + + Console.WriteLine($"\n✓ 扩展包已创建 / Extension package created: {zipPath}"); + Console.WriteLine($" 文件大小 / File Size: {extensionMetadata.FileSize} bytes ({extensionMetadata.FileSize / 1024.0:F2} KB)"); + Console.WriteLine("\n" + new string('=', 80) + "\n"); + + // ======================================== + // 4. 安装扩展 / Install Extension + // ======================================== + Console.WriteLine("=== 4. 安装扩展 / Install Extension ==="); + Console.WriteLine($"扩展路径 / Extension Path: {zipPath}"); + Console.WriteLine($"启用回滚 / Rollback Enabled: true\n"); + + var installSuccess = await host.InstallExtensionAsync(zipPath, rollbackOnFailure: true); + + if (installSuccess) + { + Console.WriteLine("✓ 扩展安装成功 / Extension installed successfully"); + + var extractedDir = Path.Combine(extensionsDir, extensionMetadata.Name); + if (Directory.Exists(extractedDir)) + { + Console.WriteLine($" 安装目录 / Installation Directory: {extractedDir}"); + var extractedFiles = Directory.GetFiles(extractedDir); + Console.WriteLine($" 提取的文件 / Extracted Files ({extractedFiles.Length}):"); + foreach (var file in extractedFiles) + { + Console.WriteLine($" • {Path.GetFileName(file)}"); + } + } + } + else + { + Console.WriteLine("✗ 扩展安装失败 / Extension installation failed"); + } + Console.WriteLine("\n" + new string('=', 80) + "\n"); + + // ======================================== + // 5. 更新扩展目录 / Update Extension Catalog + // ======================================== + Console.WriteLine("=== 5. 更新扩展目录 / Update Extension Catalog ==="); + + host.ExtensionCatalog.AddOrUpdateInstalledExtension(extensionMetadata); + Console.WriteLine("✓ 扩展已添加到目录 / Extension added to catalog"); + Console.WriteLine(" (目录会自动保存 / Catalog is saved automatically)"); + Console.WriteLine("\n" + new string('=', 80) + "\n"); + + // ======================================== + // 6. 管理已安装的扩展 / Manage Installed Extensions + // ======================================== + Console.WriteLine("=== 6. 管理已安装的扩展 / Manage Installed Extensions ==="); + + // 加载已安装的扩展 / Load installed extensions + host.ExtensionCatalog.LoadInstalledExtensions(); + Console.WriteLine("✓ 已加载已安装的扩展 / Installed extensions loaded"); + + // 获取所有已安装的扩展 / Get all installed extensions + var installedExtensions = host.ExtensionCatalog.GetInstalledExtensions(); + Console.WriteLine($"\n已安装扩展数量 / Total Installed Extensions: {installedExtensions.Count}"); + + if (installedExtensions.Count > 0) + { + Console.WriteLine("\n已安装扩展列表 / Installed Extensions List:"); + foreach (var ext in installedExtensions) + { + Console.WriteLine($"\n • {ext.DisplayName} v{ext.Version}"); + Console.WriteLine($" ID: {ext.Id}"); + Console.WriteLine($" 名称 / Name: {ext.Name}"); + Console.WriteLine($" 状态 / Status: {(ext.Status == true ? "启用/Enabled" : "禁用/Disabled")}"); + Console.WriteLine($" 平台 / Platform: {ext.SupportedPlatforms}"); + Console.WriteLine($" 发布者 / Publisher: {ext.Publisher}"); + Console.WriteLine($" 描述 / Description: {ext.Description}"); + } + } + + // 根据ID获取特定扩展 / Get specific extension by ID + Console.WriteLine($"\n--- 根据ID获取扩展 / Get Extension by ID ---"); + var extension = host.ExtensionCatalog.GetInstalledExtensionById(extensionId); + if (extension != null) + { + Console.WriteLine($"✓ 找到扩展 / Found extension:"); + Console.WriteLine($" ID: {extension.Id}"); + Console.WriteLine($" 名称 / Name: {extension.DisplayName}"); + Console.WriteLine($" 版本 / Version: {extension.Version}"); + } + else + { + Console.WriteLine($"✗ 未找到扩展 / Extension not found"); + } + + // 根据平台获取扩展 / Get extensions by platform + Console.WriteLine($"\n--- 根据平台获取扩展 / Get Extensions by Platform ---"); + var windowsExtensions = host.ExtensionCatalog.GetInstalledExtensionsByPlatform(TargetPlatform.Windows); + Console.WriteLine($"Windows 平台扩展数量 / Windows Platform Extensions: {windowsExtensions.Count}"); + + var allPlatformExtensions = host.ExtensionCatalog.GetInstalledExtensionsByPlatform(TargetPlatform.All); + Console.WriteLine($"所有平台扩展数量 / All Platform Extensions: {allPlatformExtensions.Count}"); + Console.WriteLine("\n" + new string('=', 80) + "\n"); + + // ======================================== + // 7. 检查扩展兼容性 / Check Extension Compatibility + // ======================================== + Console.WriteLine("=== 7. 检查扩展兼容性 / Check Extension Compatibility ==="); + + if (extension != null) + { + var isCompatible = host.IsExtensionCompatible(extension); + Console.WriteLine($"扩展名称 / Extension Name: {extension.DisplayName}"); + Console.WriteLine($"扩展版本 / Extension Version: {extension.Version}"); + Console.WriteLine($"最小主机版本 / Min Host Version: {extension.MinHostVersion}"); + Console.WriteLine($"最大主机版本 / Max Host Version: {extension.MaxHostVersion}"); + Console.WriteLine($"当前主机版本 / Current Host Version: {options.HostVersion}"); + Console.WriteLine($"兼容性 / Compatibility: {(isCompatible ? "✓ 兼容/Compatible" : "✗ 不兼容/Not Compatible")}"); + } + Console.WriteLine("\n" + new string('=', 80) + "\n"); + + // ======================================== + // 8. 自动更新设置 / Auto-Update Settings + // ======================================== + Console.WriteLine("=== 8. 自动更新设置 / Auto-Update Settings ==="); + + if (extension != null) + { + // 启用自动更新 / Enable auto-update + host.SetAutoUpdate(extensionId, true); + Console.WriteLine($"✓ 已为扩展启用自动更新 / Auto-update enabled for extension: {extension.DisplayName}"); + + // 检查是否启用自动更新 / Check if auto-update is enabled + var autoUpdateEnabled = host.IsAutoUpdateEnabled(extensionId); + Console.WriteLine($" 自动更新状态 / Auto-Update Status: {(autoUpdateEnabled ? "启用/Enabled" : "禁用/Disabled")}"); + + // 启用全局自动更新 / Enable global auto-update + host.SetGlobalAutoUpdate(true); + Console.WriteLine($"\n✓ 已启用全局自动更新 / Global auto-update enabled"); + } + Console.WriteLine("\n" + new string('=', 80) + "\n"); + + // ======================================== + // 9. 查询远程扩展 / Query Remote Extensions + // ======================================== + Console.WriteLine("=== 9. 查询远程扩展 / Query Remote Extensions ==="); + Console.WriteLine("注意:此功能需要服务器运行,本示例仅演示API调用"); + Console.WriteLine("Note: This feature requires a running server, this example only demonstrates API usage\n"); + + var query = new ExtensionQueryDTO + { + Name = "sample", + Platform = TargetPlatform.All, + HostVersion = "1.0.0", + Status = true, + PageNumber = 1, + PageSize = 20, + BeginDate = DateTime.Now.AddDays(-30), + EndDate = DateTime.Now + }; + + Console.WriteLine("查询参数 / Query Parameters:"); + Console.WriteLine($" 名称 / Name: {query.Name}"); + Console.WriteLine($" 平台 / Platform: {query.Platform}"); + Console.WriteLine($" 主机版本 / Host Version: {query.HostVersion}"); + Console.WriteLine($" 页码 / Page Number: {query.PageNumber}"); + Console.WriteLine($" 每页大小 / Page Size: {query.PageSize}"); + + try + { + var queryResult = await host.QueryExtensionsAsync(query); + if (queryResult.Body != null) + { + Console.WriteLine($"\n✓ 查询成功 / Query successful"); + Console.WriteLine($" 总数 / Total Count: {queryResult.Body.TotalCount}"); + Console.WriteLine($" 当前页 / Current Page: {queryResult.Body.PageNumber}"); + Console.WriteLine($" 每页大小 / Page Size: {queryResult.Body.PageSize}"); + + var itemsList = queryResult.Body.Items.ToList(); + if (itemsList.Count > 0) + { + Console.WriteLine($"\n 找到的扩展 / Found Extensions:"); + foreach (var ext in itemsList) + { + Console.WriteLine($"\n • {ext.DisplayName} v{ext.Version}"); + Console.WriteLine($" ID: {ext.Id}"); + Console.WriteLine($" 发布者 / Publisher: {ext.Publisher}"); + Console.WriteLine($" 兼容 / Compatible: {ext.IsCompatible}"); + Console.WriteLine($" 平台 / Platform: {ext.SupportedPlatforms}"); + } + } + } + else + { + Console.WriteLine($"\n✗ 查询失败 / Query failed: {queryResult.Message}"); + } + } + catch (Exception ex) + { + Console.WriteLine($"\n✗ 查询错误 / Query error: {ex.Message}"); + Console.WriteLine($" (这是预期的,因为服务器未运行)"); + Console.WriteLine($" (This is expected as the server is not running)"); + } + Console.WriteLine("\n" + new string('=', 80) + "\n"); + + // ======================================== + // 10. 清理 / Cleanup + // ======================================== + Console.WriteLine("=== 10. 清理 / Cleanup ==="); + Console.WriteLine("注意:示例创建的文件保留在extensions目录中供检查"); + Console.WriteLine("Note: Files created by this example are kept in the extensions directory for inspection"); + Console.WriteLine($"扩展目录 / Extensions Directory: {extensionsDir}"); + + Console.WriteLine("\n=== 示例程序执行完成 / Sample Program Completed ==="); + Console.WriteLine($"完成时间:{DateTime.Now}"); + Console.WriteLine($"Completion Time: {DateTime.Now}"); +} +catch (Exception e) +{ + Console.WriteLine($"\n异常 / Exception: {e.Message}"); + Console.WriteLine($"堆栈跟踪 / Stack Trace:\n{e.StackTrace}"); +} + +// 辅助方法:创建扩展包 / Helper method: Create extension package +static async Task CreateExtensionPackage(string zipPath, ExtensionMetadata metadata) +{ + await Task.Run(() => + { + var tempDir = Path.Combine(Path.GetTempPath(), $"extension-temp-{Guid.NewGuid()}"); + Directory.CreateDirectory(tempDir); + + try + { + // 1. 创建 extension.json 元数据文件 / Create extension.json metadata file + var metadataJson = JsonConvert.SerializeObject(metadata, Formatting.Indented); + File.WriteAllText(Path.Combine(tempDir, "extension.json"), metadataJson); + + // 2. 创建模拟的 extension.dll 文件 / Create mock extension.dll file + var dllContent = $@"// Mock DLL content +// 模拟的DLL内容 +// In production, this would be the actual compiled extension binary +// 在生产环境中,这将是实际编译的扩展二进制文件 +namespace {metadata.Name} +{{ + public class ExtensionEntry + {{ + public void Initialize() + {{ + // Extension initialization code + // 扩展初始化代码 + }} + }} +}}"; + File.WriteAllText(Path.Combine(tempDir, "extension.dll"), dllContent); + + // 3. 创建 README.md + var readmeContent = $@"# {metadata.DisplayName} + +## 版本 / Version: {metadata.Version} + +### 描述 / Description +{metadata.Description} + +### 发布者 / Publisher +{metadata.Publisher} + +### 许可证 / License +{metadata.License} + +### 支持的平台 / Supported Platforms +{metadata.SupportedPlatforms} + +### 兼容性 / Compatibility +- 最小主机版本 / Min Host Version: {metadata.MinHostVersion} +- 最大主机版本 / Max Host Version: {metadata.MaxHostVersion} + +### 分类 / Categories +{metadata.Categories} + +--- + +## 安装 / Installation +此扩展包与 GeneralUpdate.Extension 主机兼容。 +This extension package is compatible with GeneralUpdate.Extension host. + +生成时间 / Generated: {DateTime.UtcNow:yyyy-MM-dd HH:mm:ss UTC} +"; + File.WriteAllText(Path.Combine(tempDir, "README.md"), readmeContent); + + // 4. 创建压缩包 / Create zip file + if (File.Exists(zipPath)) + { + File.Delete(zipPath); + } + + ZipFile.CreateFromDirectory(tempDir, zipPath); + } + finally + { + if (Directory.Exists(tempDir)) + { + Directory.Delete(tempDir, true); + } + } + }); +}