Skip to content

Commit

Permalink
Merge pull request #37 from GeneralLibrary/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
JusterZhu authored Jan 14, 2024
2 parents a961ecf + 9090854 commit 7a1ae7c
Show file tree
Hide file tree
Showing 17 changed files with 146 additions and 40 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
| 回滚 | 待测试 | 逐版本更新时会备份每个版本,如果更新失败则逐版本回滚。 |
| 驱动更新 | 支持 | 逐版本更新时会备份每个版本的驱动文件(.inf),如果更新失败则逐版本回滚。 |
| 遗言 | 待测试 | 开机时和升级时会检查升级是否成功,如果失败则根据遗言还原之前的备份。遗言是更新之前就已经自动创建在C:\generalupdate_willmessages目录下的will_message.json文件。will_message.json的内容是持久化回滚备份的文件目录相关信息。(需要部署GeneralUpdate.SystemService系统服务) |
| 自定义方法列表 | 待测试 | 注入一个自定义方法集合,该集合会在更新启动前执行。执行自定义方法列表如果出现任何异常,将通过异常订阅通知。(推荐在更新之前检查当前软件环境) |
| 自定义方法列表 | 支持 | 注入一个自定义方法集合,该集合会在更新启动前执行。执行自定义方法列表如果出现任何异常,将通过异常订阅通知。(推荐在更新之前检查当前软件环境) |



Expand Down
2 changes: 1 addition & 1 deletion README_en.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
| Restore | test | Each version is backed up during a version-by-version update and rolled back version-by-version if the update fails. |
| Driver upgrade | yes | The driver file (.INF) of each version is backed up during the version-by-version update and is rolled back version-by-version if the update fails. |
| Will message | test | The upgrade is checked for success at boot and upgrade, and if it fails, the previous backup is restored according to the last word. The last word is that the will_message.json file in the C:\generalupdate_willmessages directory was automatically created before the update. will_message.json is about the file directory of the persistent rollback backup.(need to deploy GeneralUpdate. SystemService system service) |
| A list of custom methods | test | Inject a custom collection of methods that are executed before the update starts. Execute a custom method list, and if there are any exceptions, you will be notified by exception subscription.(It is recommended to check the current software environment before updating) |
| A list of custom methods | 支持 | Inject a custom collection of methods that are executed before the update starts. Execute a custom method list, and if there are any exceptions, you will be notified by exception subscription.(It is recommended to check the current software environment before updating) |



Expand Down
4 changes: 2 additions & 2 deletions src/c#/GeneralUpdate.Api/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
app.MapGet("/versions/{clientType}/{clientVersion}/{clientAppKey}", (int clientType, string clientVersion, string clientAppKey, IUpdateService updateService) =>
{
var versions = new List<VersionDTO>();
var hash = "415eed05eb310f480d1e4d15516fa00e484ddb9f416908b217f17b782ded2030";//生成好的更新包文件的MD5码,因为返回给客户端的时候需要同这个来验证是否可用
var hash = "28d10f1fc2a23dd1afe0af40d132b25c72ea56005963f653c27889f03d381c8d";//生成好的更新包文件的MD5码,因为返回给客户端的时候需要同这个来验证是否可用
var pubTime = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();
string version = null;
if (clientType == AppType.ClientApp)
Expand All @@ -51,7 +51,7 @@
version = "0.0.0.0";
//version = "9.9.9.9"; //这里设置为9是让程序认为需要更新
}
var url = $"http://127.0.0.1/WpfClient_1_24.1.5.1218.zip";//更新包的下载地址
var url = $"http://192.168.1.7/WpfClient_1_24.1.5.1218.zip";//更新包的下载地址
var name = "update";
versions.Add(new VersionDTO(hash, pubTime, version, url, name));
return updateService.Update(clientType, clientVersion, version, clientAppKey, GetAppSecretKey(), false, versions);
Expand Down
95 changes: 93 additions & 2 deletions src/c#/GeneralUpdate.Client/MySample.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,18 @@
using GeneralUpdate.Core.Events.CommonArgs;
using GeneralUpdate.Differential;
using System.IO;
using GeneralUpdate.Core.Driver;
using Microsoft.VisualBasic;
using System.Diagnostics;
using GeneralUpdate.Core.WillMessage;

namespace GeneralUpdate.Client
{
internal class MySample
{
#region 推送功能

private const string baseUrl = @"http://127.0.0.1:5001";
private const string baseUrl = @"http://127.0.0.1:5000";
private const string hubName = "versionhub";

internal MySample()
Expand Down Expand Up @@ -72,7 +76,7 @@ public async Task Upgrade()
.Option(UpdateOption.Encoding, Encoding.Default)
.Option(UpdateOption.Format, Format.ZIP)
//开启驱动更新
.Option(UpdateOption.Drive, true)
//.Option(UpdateOption.Drive, true)
//开启遗言功能,需要部署GeneralUpdate.SystemService Windows服务。
.Option(UpdateOption.WillMessage, true)
.Strategy<WindowsStrategy>()
Expand Down Expand Up @@ -231,5 +235,92 @@ public async Task TestDifferentialDirty()
}

#endregion

#region 测试驱动功能

public void TestDrive()
{
var path1 = "D:\\packet\\source";
var path2 = "D:\\packet\\target";

var drivers = GetAllDriverDirectories(path1);

var information = new DriverInformation.Builder()
.SetInstallDirectory(path1)
.SetOutPutDirectory(path2)
.SetDriverNames(drivers)
.Build();

var processor = new DriverProcessor();
processor.AddCommand(new BackupDriverCommand(information));
processor.AddCommand(new DeleteDriverCommand(information));
processor.AddCommand(new InstallDriverCommand(information));
processor.ProcessCommands();
}

/// <summary>
/// Identifies all folders containing driver files in the specified directory and returns the directory collection.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
private List<string> GetAllDriverDirectories(string path)
{
var driverDirectories = new HashSet<string>();
try
{
foreach (string filePath in Directory.GetFiles(path))
{
if (IsDriverFile(filePath))
driverDirectories.Add(filePath);
}

foreach (string directory in Directory.GetDirectories(path))
{
driverDirectories.UnionWith(GetAllDriverDirectories(directory));
}
}
catch (UnauthorizedAccessException)
{
Trace.WriteLine("No access directory:" + path);
}
catch (PathTooLongException)
{
Trace.WriteLine("Path overlength:" + path);
}

return new List<string>(driverDirectories);
}

/// <summary>
/// Match the driver installation boot file.
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
private bool IsDriverFile(string filePath) =>
string.Equals(Path.GetExtension(filePath), ".inf", StringComparison.OrdinalIgnoreCase);

#endregion

#region 测试WillMessage

public void TestWillMessage()
{
var path1 = "D:\\packet\\source";
var path2 = "D:\\packet\\target";
var hash = "";

for (int i = 0; i < 1; i++)
{
var version = "1.0.0" + i;
WillMessageManager.Instance.Backup(path1,path2, version, hash, 1);
}
WillMessageManager.Instance.Builder();
WillMessageManager.Instance.GetWillMessage();
WillMessageManager.Instance.Check();
WillMessageManager.Instance.Restore();
WillMessageManager.Instance.Clear();
}

#endregion
}
}
19 changes: 13 additions & 6 deletions src/c#/GeneralUpdate.Core/Bootstrap/AbstractBootstrap.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,8 @@ public virtual TBootstrap LaunchAsync()
Packet.DownloadTimeOut = GetOption(UpdateOption.DownloadTimeOut);
Packet.AppName = $"{Packet.AppName ?? GetOption(UpdateOption.MainApp)}{EXECUTABLE_FILE}";
Packet.TempPath = $"{FileUtil.GetTempDirectory(Packet.LastVersion)}{Path.DirectorySeparatorChar}";
Packet.DriveEnabled = GetOption(UpdateOption.Drive);
Packet.WillMessageEnabled = GetOption(UpdateOption.WillMessage);
Packet.DriveEnabled = GetOption(UpdateOption.Drive) ?? false;
Packet.WillMessageEnabled = GetOption(UpdateOption.WillMessage) ?? false;
var manager = new DownloadManager<VersionInfo>(Packet.TempPath, Packet.Format, Packet.DownloadTimeOut);
manager.MultiAllDownloadCompleted += OnMultiAllDownloadCompleted;
manager.MultiDownloadCompleted += OnMultiDownloadCompleted;
Expand Down Expand Up @@ -156,10 +156,17 @@ public virtual TBootstrap Option<T>(UpdateOption<T> option, T value)

public virtual T GetOption<T>(UpdateOption<T> option)
{
if (_options == null || _options.Count == 0) return default(T);
var val = _options[option];
if (val != null) return (T)val.GetValue();
return default(T);
try
{
if (_options == null || _options.Count == 0) return default(T);
var val = _options[option];
if (val != null) return (T)val.GetValue();
return default(T);
}
catch
{
return default(T);
}
}

#endregion Config option.
Expand Down
4 changes: 2 additions & 2 deletions src/c#/GeneralUpdate.Core/Bootstrap/UpdateOption.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,12 @@ private class UpdateOptionPool : ConstantPool
/// <summary>
/// Whether to enable the driver upgrade function.
/// </summary>
public static readonly UpdateOption<bool> Drive = ValueOf<bool>("DRIVE");
public static readonly UpdateOption<bool?> Drive = ValueOf<bool?>("DRIVE");

/// <summary>
/// Whether open note function, if you want to start needs to be synchronized to deploy 'GeneralUpdate. SystemService' service.
/// </summary>
public static readonly UpdateOption<bool> WillMessage = ValueOf<bool>("WILLMESSAGE");
public static readonly UpdateOption<bool?> WillMessage = ValueOf<bool?>("WILLMESSAGE");

#endregion parameter configuration

Expand Down
5 changes: 3 additions & 2 deletions src/c#/GeneralUpdate.Core/Driver/CommandExecutor.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using GeneralUpdate.Core.Exceptions;
using System;
using System.Diagnostics;

namespace GeneralUpdate.Core.Driver
Expand Down Expand Up @@ -38,7 +39,7 @@ Update the driver regularly to ensure that the driver is compatible with the cur
process.WaitForExit();

if (process.ExitCode != 0)
throw new Exception($"Operation failed code: {process.ExitCode}");
ThrowExceptionUtility.Throw<Exception>($"Operation failed code: {process.ExitCode}");
}
}
}
Expand Down
5 changes: 3 additions & 2 deletions src/c#/GeneralUpdate.Core/Driver/DriverInformation.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using GeneralUpdate.Core.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;

Expand Down Expand Up @@ -59,7 +60,7 @@ public DriverInformation Build()
string.IsNullOrWhiteSpace(_information.OutPutDirectory) ||
!_information.Drivers.Any())
{
throw new InvalidOperationException("Cannot create DriverInformation, not all fields are set.");
ThrowExceptionUtility.ThrowIfNull("Cannot create DriverInformation, not all fields are set.");
}

return _information;
Expand Down
2 changes: 1 addition & 1 deletion src/c#/GeneralUpdate.Core/Driver/DriverProcessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ namespace GeneralUpdate.Core.Driver
/// </summary>
public class DriverProcessor
{
private List<IDriverCommand> _commands = new List<IDriverCommand>();
private readonly List<IDriverCommand> _commands = new List<IDriverCommand>();

public void AddCommand(IDriverCommand command)
{
Expand Down
5 changes: 3 additions & 2 deletions src/c#/GeneralUpdate.Core/Driver/InstallDriverCommand.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using GeneralUpdate.Core.Exceptions;
using System;
using System.IO;
using System.Text;

Expand Down Expand Up @@ -38,7 +39,7 @@ public void Execute()
{
//restore all the drivers in the backup directory.
new RestoreDriverCommand(_information).Execute();
throw new Exception($"Failed to execute install command for {_information.InstallDirectory}", ex);
ThrowExceptionUtility.Throw<Exception>($"Failed to execute install command for {_information.InstallDirectory}", ex);
}
}
}
Expand Down
3 changes: 2 additions & 1 deletion src/c#/GeneralUpdate.Core/Driver/RestoreDriverCommand.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System.IO;
using System;
using System.Text;
using GeneralUpdate.Core.Exceptions;

namespace GeneralUpdate.Core.Driver
{
Expand All @@ -26,7 +27,7 @@ public void Execute()
}
catch (Exception ex)
{
throw new Exception($"Failed to execute restore command for {_information.OutPutDirectory}", ex);
ThrowExceptionUtility.Throw<Exception>($"Failed to execute restore command for {_information.OutPutDirectory}", ex);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,11 @@ public static void ThrowGeneralUpdateException(ExceptionArgs args)

public static void ThrowFileNotFound(string file) => Throw<FileNotFoundException>($"File cannot be accessed {file}!");

public static void ThrowIfNull()=> Throw<ArgumentException>("Parameter cannot be null");
public static void ThrowIfNull(string errorMessage = null)
{
errorMessage = errorMessage ?? "Parameter cannot be null";
Throw<ArgumentException>(errorMessage);
}

/// <summary>
/// Checks if an object is empty and throws an exception if it is
Expand Down
5 changes: 1 addition & 4 deletions src/c#/GeneralUpdate.Core/Pipelines/Context/BaseContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -81,10 +81,7 @@ public Builder SetAppType(int type)
return this;
}

public BaseContext Build()
{
return _context;
}
public BaseContext Build() => _context;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public static class MiddlewareExtensions

public static IPipelineBuilder UseMiddleware<[DynamicallyAccessedMembers(MiddlewareAccessibility)] TMiddleware>(this IPipelineBuilder pipeline) => pipeline.UseMiddleware(typeof(TMiddleware),true);

public static IPipelineBuilder UseMiddlewareIf<[DynamicallyAccessedMembers(MiddlewareAccessibility)] TMiddleware>(this IPipelineBuilder pipeline,bool condition) => pipeline.UseMiddleware(typeof(TMiddleware), condition);
public static IPipelineBuilder UseMiddlewareIf<[DynamicallyAccessedMembers(MiddlewareAccessibility)] TMiddleware>(this IPipelineBuilder pipeline,bool condition = false) => pipeline.UseMiddleware(typeof(TMiddleware), condition);

public static IPipelineBuilder UseMiddleware(
this IPipelineBuilder pipeline,
Expand Down
24 changes: 12 additions & 12 deletions src/c#/GeneralUpdate.Core/WillMessage/WillMessageManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,18 @@

namespace GeneralUpdate.Core.WillMessage
{
internal class WillMessageManager
public class WillMessageManager
{
#region Private Members

internal const string DEFULT_WILL_MESSAGE_DIR = @"C:\generalupdate_willmessages";
internal const string DEFULT_WILL_MESSAGE_FILE = "will_message.json";
public const string DEFULT_WILL_MESSAGE_DIR = @"C:\generalupdate_willmessages";
public const string DEFULT_WILL_MESSAGE_FILE = "will_message.json";

internal const string BACKUP_ROOT_PATH = @"C:\generalupdate_backup";
public const string BACKUP_ROOT_PATH = @"C:\generalupdate_backup";
private string _packetPath;
private string _appPath;
private string _backupPath;
private Stack<BackupPO> _backupStack = new Stack<BackupPO>();
private readonly Stack<BackupPO> _backupStack = new Stack<BackupPO>();

private string _willMessageFile;
private WillMessagePO _willMessage;
Expand All @@ -37,7 +37,7 @@ private WillMessageManager() { }

#region Public Properties

internal static WillMessageManager Instance
public static WillMessageManager Instance
{
get
{
Expand All @@ -59,13 +59,13 @@ internal static WillMessageManager Instance

#region Public Methods

internal WillMessagePO GetWillMessage(string path = null)
public WillMessagePO GetWillMessage(string path = null)

Check warning on line 62 in src/c#/GeneralUpdate.Core/WillMessage/WillMessageManager.cs

View workflow job for this annotation

GitHub Actions / build

Cannot convert null literal to non-nullable reference type.
{
_willMessageFile = string.IsNullOrWhiteSpace(path) ? GetWillMessagePath() : path;
return _willMessage = FileUtil.GetJson<WillMessagePO>(_willMessageFile);
}

internal void Clear()
public void Clear()
{
_packetPath = null;
_appPath = null;
Expand All @@ -77,7 +77,7 @@ internal void Clear()
FileUtil.DeleteDir(BACKUP_ROOT_PATH);
}

internal void Backup(string appPath, string packetPath, string version,string hash,int appType)
public void Backup(string appPath, string packetPath, string version,string hash,int appType)
{
if (!Directory.Exists(BACKUP_ROOT_PATH))
Directory.CreateDirectory(BACKUP_ROOT_PATH);
Expand All @@ -93,7 +93,7 @@ internal void Backup(string appPath, string packetPath, string version,string ha
_backupStack.Push(new BackupPO { Version = version, AppType = appType, AppPath = _appPath, BackupPath = _backupPath , Hash = hash });
}

internal void Restore()
public void Restore()
{
if (_willMessage == null || _willMessage.Message == null) return;
while (_willMessage.Message.Any())
Expand All @@ -105,7 +105,7 @@ internal void Restore()
}
}

internal void Builder()
public void Builder()
{
if (!_backupStack.Any()) return;

Expand All @@ -118,7 +118,7 @@ internal void Builder()
FileUtil.CreateJson(Path.Combine(DEFULT_WILL_MESSAGE_DIR, DateTime.Now.ToString("yyyyMMdd")), DEFULT_WILL_MESSAGE_FILE, _willMessage);
}

internal void Check()
public void Check()
{
var message = GetWillMessage();
if (message == null) return;
Expand Down
Empty file.
Loading

0 comments on commit 7a1ae7c

Please sign in to comment.