From 495e52c2e6705d6787cd1f149f3f0dd3d464c3d9 Mon Sep 17 00:00:00 2001 From: Falcon <12919280+falconfly@user.noreply.gitee.com> Date: Wed, 21 Oct 2026 14:50:49 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8D=87=E7=BA=A7=E9=A1=B9=E7=9B=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- PrivateBox.sln | 8 +- PrivateBox/DataContext/DbBackupOptions.cs | 126 ++++++++++++++++++ PrivateBox/DataContext/DbContext.cs | 23 ++-- PrivateBox/Forms/MainForm.Designer.cs | 20 +-- PrivateBox/Forms/MainForm.cs | 20 ++- PrivateBox/Forms/MainForm.resx | 27 ++++ PrivateBox/PrivateBox.csproj | 5 +- PrivateBox/Program.cs | 20 +-- .../SettingsBind/SettingsWatchExtend.cs | 41 ++++++ 9 files changed, 258 insertions(+), 32 deletions(-) create mode 100644 PrivateBox/DataContext/DbBackupOptions.cs create mode 100644 PrivateBox/SettingsBind/SettingsWatchExtend.cs diff --git a/PrivateBox.sln b/PrivateBox.sln index 908b2d5..72da955 100644 --- a/PrivateBox.sln +++ b/PrivateBox.sln @@ -3,7 +3,9 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.6.33829.357 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PrivateBox", "PrivateBox\PrivateBox.csproj", "{CE1A4FB9-53F4-49C8-B22B-232A673093EB}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PrivateBox", "PrivateBox\PrivateBox.csproj", "{CE1A4FB9-53F4-49C8-B22B-232A673093EB}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Falcon.SugarCore", "..\Module\Falcon.SugarCore\Falcon.SugarCore\Falcon.SugarCore.csproj", "{04375A7C-AA4A-4B47-B938-C00E18680C25}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -15,6 +17,10 @@ Global {CE1A4FB9-53F4-49C8-B22B-232A673093EB}.Debug|Any CPU.Build.0 = Debug|Any CPU {CE1A4FB9-53F4-49C8-B22B-232A673093EB}.Release|Any CPU.ActiveCfg = Release|Any CPU {CE1A4FB9-53F4-49C8-B22B-232A673093EB}.Release|Any CPU.Build.0 = Release|Any CPU + {04375A7C-AA4A-4B47-B938-C00E18680C25}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {04375A7C-AA4A-4B47-B938-C00E18680C25}.Debug|Any CPU.Build.0 = Debug|Any CPU + {04375A7C-AA4A-4B47-B938-C00E18680C25}.Release|Any CPU.ActiveCfg = Release|Any CPU + {04375A7C-AA4A-4B47-B938-C00E18680C25}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/PrivateBox/DataContext/DbBackupOptions.cs b/PrivateBox/DataContext/DbBackupOptions.cs new file mode 100644 index 0000000..592e691 --- /dev/null +++ b/PrivateBox/DataContext/DbBackupOptions.cs @@ -0,0 +1,126 @@ +using SqlSugar; + +namespace PrivateBox.DataContext +{ + /// + /// 数据库备份扩展类 + /// + public static class DbBackupExtended + { + /// + /// 备份数据库【扩展方法】 + /// + /// DbContext(ISqlSugarClient) + /// 备份选项配置委托 + public static void Backup(this ISqlSugarClient db,Action? options = null) { + var op = new DbBackupOptions(); + options?.Invoke(op); + + // 从SqlSugar连接串自动读取SQLite源文件路径,如果Options没手动指定SourceDbFilePath + if(string.IsNullOrWhiteSpace(op.SourceDbFilePath)) { + var connStr = db.Ado.Connection.ConnectionString; + // 解析 DataSource=xxx + op.SourceDbFilePath = GetSqliteDataSourcePath(connStr); + } + + // 参数校验 + if(string.IsNullOrWhiteSpace(op.SourceDbFilePath)) + throw new ArgumentNullException(nameof(op.SourceDbFilePath),"无法获取源SQLite数据库文件路径,请在DbBackupOptions中手动指定SourceDbFilePath"); + if(string.IsNullOrWhiteSpace(op.BackupDirectory)) + throw new ArgumentNullException(nameof(op.BackupDirectory),"必须指定备份存放目录"); + if(op.MaxBackupFileCount <= 0) + op.MaxBackupFileCount = 3; // 默认最多保留3个备份 + + try { + if(!File.Exists(op.SourceDbFilePath)) { + Console.WriteLine($"源数据库文件不存在:{op.SourceDbFilePath},跳过备份"); + return; + } + + // 创建备份目录 + if(!Directory.Exists(op.BackupDirectory)) { + Directory.CreateDirectory(op.BackupDirectory); + } + + // WAL刷盘,保证数据完整 + db.Ado.ExecuteCommand("PRAGMA wal_checkpoint(FULL);"); + + // 生成带时间戳备份文件名 + string backupFileName = $"db_backup_{DateTime.Now:yyyyMMdd_HHmmss}.sqlite"; + string fullBackupFile = Path.Combine(op.BackupDirectory,backupFileName); + + // 复制数据库文件 + File.Copy(op.SourceDbFilePath,fullBackupFile,overwrite: false); + Console.WriteLine($"备份成功:{fullBackupFile}"); + + // 清理旧备份 + CleanOldBackupFiles(op.BackupDirectory,op.MaxBackupFileCount); + } + catch(Exception ex) { + Console.WriteLine($"数据库备份异常:{ex.Message}"); + } + } + + /// + /// 从SQLite连接字符串解析DataSource路径 + /// + private static string GetSqliteDataSourcePath(string connectionString) { + var pairs = connectionString.Split(';') + .Select(s => s.Trim()) + .Where(s => !string.IsNullOrEmpty(s)) + .Select(s => { + var kv = s.Split('='); + return new { Key = kv[0].Trim(),Value = kv.Length > 1 ? kv[1].Trim() : "" }; + }); + var item = pairs.FirstOrDefault(p => p.Key.Equals("DataSource",StringComparison.OrdinalIgnoreCase)); + return item?.Value; + } + + /// + /// 清理过期备份,只保留最新MaxBackupFileCount个 + /// + /// 备份目录 + /// 最大保留数量 + private static void CleanOldBackupFiles(string backupDir,int maxCount) { + var backupFiles = Directory.GetFiles(backupDir,"db_backup_*.sqlite") + .Select(f => new FileInfo(f)) + .OrderBy(x => x.CreationTime) // 旧文件在前 + .ToList(); + + if(backupFiles.Count > maxCount) { + var deleteList = backupFiles.Take(backupFiles.Count - maxCount).ToList(); + foreach(var file in deleteList) { + try { + file.Delete(); + Console.WriteLine($"删除过期备份:{file.FullName}"); + } + catch(Exception ex) { + Console.WriteLine($"删除旧备份失败 {file.FullName}:{ex.Message}"); + } + } + } + } + } + + /// + /// 备份选项 + /// + public class DbBackupOptions + { + /// + /// 源SQLite数据库文件完整路径,不设置则自动从SqlSugar连接串读取 + /// + public string? SourceDbFilePath { get; set; } + + /// + /// 备份存放目录 + /// + public string? BackupDirectory { get; set; } + + /// + /// 备份文件最大数量 + /// + public int MaxBackupFileCount { get; set; } + } + +} diff --git a/PrivateBox/DataContext/DbContext.cs b/PrivateBox/DataContext/DbContext.cs index c049ea1..cf32b01 100644 --- a/PrivateBox/DataContext/DbContext.cs +++ b/PrivateBox/DataContext/DbContext.cs @@ -1,7 +1,6 @@ -using Microsoft.Extensions.DependencyInjection; +using Falcon.SugarCore.DbContextExtensions; using PrivateBox.DataContext; using SqlSugar; -using System.Runtime.CompilerServices; using System.Text; namespace PrivateBox @@ -9,7 +8,7 @@ namespace PrivateBox /// /// 数据库上下文 /// - public class DbContext:SqlSugarClient + public class DbContext:Falcon.SugarCore.DbContextExtensions.DbContext { public AppConfig Config { get; init; } @@ -18,16 +17,20 @@ namespace PrivateBox /// private static bool IsInited = false; - public DbContext(AppConfig config) : base(new ConnectionConfig { - DbType = DbType.Sqlite, - ConnectionString = config.SqliteFileName, - IsAutoCloseConnection = false, - - }) { - this.Config = config; + public DbContext(DbContextConfig config):base(config) { DbInit(); } + //public DbContext(AppConfig config) : base(new ConnectionConfig { + // DbType = DbType.Sqlite, + // ConnectionString = config.SqliteFileName, + // IsAutoCloseConnection = false, + + //}) { + // this.Config = config; + // DbInit(); + //} + /// /// 初始化数据库 /// diff --git a/PrivateBox/Forms/MainForm.Designer.cs b/PrivateBox/Forms/MainForm.Designer.cs index 3a4ce13..9fbd1f2 100644 --- a/PrivateBox/Forms/MainForm.Designer.cs +++ b/PrivateBox/Forms/MainForm.Designer.cs @@ -35,13 +35,13 @@ menuKeyList = new ContextMenuStrip(components); KeyListAddNew = new ToolStripMenuItem(); KeyListRemove = new ToolStripMenuItem(); + toolStripMenuItem1 = new ToolStripSeparator(); KeyListGroup = new ToolStripMenuItem(); splitContainer2 = new SplitContainer(); toolStrip1 = new ToolStrip(); btSave = new ToolStripButton(); btCancel = new ToolStripButton(); tbMessage = new RichTextBox(); - toolStripMenuItem1 = new ToolStripSeparator(); toolStripContainer1.ContentPanel.SuspendLayout(); toolStripContainer1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)splitContainer1).BeginInit(); @@ -135,26 +135,31 @@ // menuKeyList.Items.AddRange(new ToolStripItem[] { KeyListAddNew,KeyListRemove,toolStripMenuItem1,KeyListGroup }); menuKeyList.Name = "menuKeyList"; - menuKeyList.Size = new Size(181,98); + menuKeyList.Size = new Size(101,76); // // KeyListAddNew // KeyListAddNew.Name = "KeyListAddNew"; - KeyListAddNew.Size = new Size(180,22); + KeyListAddNew.Size = new Size(100,22); KeyListAddNew.Text = "新增"; KeyListAddNew.Click += KeyListAddNew_Click; // // KeyListRemove // KeyListRemove.Name = "KeyListRemove"; - KeyListRemove.Size = new Size(180,22); + KeyListRemove.Size = new Size(100,22); KeyListRemove.Text = "删除"; KeyListRemove.Click += KeyListRemove_Click; // + // toolStripMenuItem1 + // + toolStripMenuItem1.Name = "toolStripMenuItem1"; + toolStripMenuItem1.Size = new Size(97,6); + // // KeyListGroup // KeyListGroup.Name = "KeyListGroup"; - KeyListGroup.Size = new Size(180,22); + KeyListGroup.Size = new Size(100,22); KeyListGroup.Text = "分组"; KeyListGroup.Click += KeyListGroup_Click; // @@ -216,11 +221,6 @@ tbMessage.TabIndex = 0; tbMessage.Text = "tbMessage"; // - // toolStripMenuItem1 - // - toolStripMenuItem1.Name = "toolStripMenuItem1"; - toolStripMenuItem1.Size = new Size(177,6); - // // MainForm // AutoScaleDimensions = new SizeF(7F,17F); diff --git a/PrivateBox/Forms/MainForm.cs b/PrivateBox/Forms/MainForm.cs index dbd8325..646e55a 100644 --- a/PrivateBox/Forms/MainForm.cs +++ b/PrivateBox/Forms/MainForm.cs @@ -1,6 +1,8 @@ using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; using PrivateBox.DataContext; using PrivateBox.Encryption; +using System.Text; using System.Windows.Forms; namespace PrivateBox @@ -12,6 +14,8 @@ namespace PrivateBox public string CrytionKey { get; init; } public AppRunTimeSettings Settings { get; set; } + public ILogger Logger { get; set; } + /// /// 默认分组名 /// @@ -30,6 +34,7 @@ namespace PrivateBox this.Db = provider.GetRequiredService(); this.Settings = provider.GetRequiredService(); this.CrytionKey = this.Db.GetCrytionKey(); + this.Logger = provider.GetRequiredService>(); this.Load += (s,d) => { RefreshGroupList(); @@ -138,6 +143,7 @@ namespace PrivateBox this.Db.Insertable(new CrytionItem { ItemName = key,ItemValue = "", }).ExecuteCommand(); + this.Logger.LogInformation($"新增项目:{key}"); RefreshKeyList(); } } @@ -151,21 +157,31 @@ namespace PrivateBox return; } this.Db.Deleteable().Where(a => a.ItemName == sItem).ExecuteCommand(); + this.Logger.LogInformation($"删除项目:{sItem}"); RefreshKeyList(); } private void btSave_Click(object sender,EventArgs e) { var tag = this.tbMessage.Tag as CrytionItem; + var itemName = tag.ItemName; + var oldVal = tag.ItemValue; if(tag == null) { return; } tag.ItemValue = this.tbMessage.Text; + var newVal = tag.ItemValue; var val = this.Encrytion.Encrypt(tag.ItemValue,this.CrytionKey); this.Db.Updateable() .Where(a => a.ItemName == tag.ItemName) .SetColumns(a => a.ItemValue == val) .SetColumns(a => a.CreateTime == DateTime.Now) .ExecuteCommand(); + var sb = new StringBuilder(); + sb.AppendLine(); + sb.AppendLine($"修改键值:{itemName}"); + sb.AppendLine($"旧键值:{oldVal}"); + sb.AppendLine($"新键值:{newVal}"); + this.Logger.LogInformation(sb.ToString()); } private void btCancel_Click(object sender,EventArgs e) { @@ -185,10 +201,12 @@ namespace PrivateBox } var dlg = new InputDlgBox("更新分组",qu.FirstOrDefault().Group); if(dlg.ShowDialog() == DialogResult.OK) { + var msg = dlg.Msg; this.Db.Updateable() .Where(a => a.ItemName == sItem) - .SetColumns(a => a.Group == dlg.Msg) + .SetColumns(a => a.Group == msg) .ExecuteCommand(); + this.Logger.LogInformation($"修改分组:[{sItem}]{msg}"); } RefreshGroupList(); } diff --git a/PrivateBox/Forms/MainForm.resx b/PrivateBox/Forms/MainForm.resx index 6a50d3a..b7cd8d4 100644 --- a/PrivateBox/Forms/MainForm.resx +++ b/PrivateBox/Forms/MainForm.resx @@ -117,12 +117,33 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + True + + + True + + + True + + + True + + + True + 127, 17 + + True + 17, 17 + + True + @@ -142,4 +163,10 @@ AAAAAElFTkSuQmCC + + True + + + True + \ No newline at end of file diff --git a/PrivateBox/PrivateBox.csproj b/PrivateBox/PrivateBox.csproj index f89cb0b..8f44458 100644 --- a/PrivateBox/PrivateBox.csproj +++ b/PrivateBox/PrivateBox.csproj @@ -10,7 +10,10 @@ - + + + + diff --git a/PrivateBox/Program.cs b/PrivateBox/Program.cs index 2469f44..ad96f72 100644 --- a/PrivateBox/Program.cs +++ b/PrivateBox/Program.cs @@ -1,6 +1,9 @@ +using Falcon.SugarCore.DbContextExtensions; using Microsoft.Extensions.DependencyInjection; using PrivateBox.Encryption; using System.Reflection; +using Falcon.SugarCore; +using Microsoft.Extensions.Logging; namespace PrivateBox { @@ -18,9 +21,13 @@ namespace PrivateBox services.AddSingleton(appConfig); services.AddSingleton(); AddServices(services,appConfig); - using ServiceProvider provider = GetServiceProvider(services); - var mainForm = provider.GetRequiredService(); + using var providerScope = services.BuildServiceProviderWithSelf().CreateScope(); + var sp = providerScope.ServiceProvider; + var logger = sp.GetRequiredService().CreateLogger("PrivateBoxMain"); + var mainForm = sp.GetRequiredService(); + logger.LogInformation($"Application will run main:{mainForm.GetType().FullName}"); Application.Run(mainForm); + logger.LogInformation($"Application closed main:{mainForm.GetType().FullName}"); } static void AddServices(IServiceCollection services,AppConfig config) { @@ -33,14 +40,9 @@ namespace PrivateBox } } services.AddSingleton(); - services.AddSingleton(); + services.AddSqlLiteDbContext(config.SqliteFileName); + services.AddNLogger(); } - static ServiceProvider GetServiceProvider(IServiceCollection services) { - ServiceProvider? provider = null; - services.AddSingleton(sp => provider!); - provider = services.BuildServiceProvider(); - return provider; - } } } \ No newline at end of file diff --git a/PrivateBox/SettingsBind/SettingsWatchExtend.cs b/PrivateBox/SettingsBind/SettingsWatchExtend.cs new file mode 100644 index 0000000..803f95a --- /dev/null +++ b/PrivateBox/SettingsBind/SettingsWatchExtend.cs @@ -0,0 +1,41 @@ +namespace PrivateBox.SettingsBind +{ + /// + /// 观察对象属性,并且可以进行读写 + /// + public static class SettingsWatchExtend + { + /// + /// 观察列表 + /// + private static List _watchList { get; set; } = new(); + + /// + /// 添加观察对象属性 + /// + /// 配置对象 + /// 要观察的对象属性 + public static void Watch(this AppRunTimeSettings settings,Action watchProc) { + //1、把属性绑定加入绑定列表 + } + + /// + /// 读取观察列表,将现有属性值保存到数据库 + /// + public static void Save(this AppRunTimeSettings settings) { + foreach(var item in _watchList) { + var key = ""; + var val = ""; + settings.SetValue(key,val); + } + } + + public static void Load(this AppRunTimeSettings settings) { + foreach(var item in _watchList) { + var key = ""; + var val = settings.GetValue(key); + //设置绑定对象的属性值 + } + } + } +}