升级项目

This commit is contained in:
Falcon 2026-10-21 14:50:49 +08:00
parent 3fe2d0fea4
commit 495e52c2e6
9 changed files with 258 additions and 32 deletions

View File

@ -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

View File

@ -0,0 +1,126 @@
using SqlSugar;
namespace PrivateBox.DataContext
{
/// <summary>
/// 数据库备份扩展类
/// </summary>
public static class DbBackupExtended
{
/// <summary>
/// 备份数据库【扩展方法】
/// </summary>
/// <param name="db">DbContext(ISqlSugarClient)</param>
/// <param name="options">备份选项配置委托</param>
public static void Backup(this ISqlSugarClient db,Action<DbBackupOptions>? 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}");
}
}
/// <summary>
/// 从SQLite连接字符串解析DataSource路径
/// </summary>
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;
}
/// <summary>
/// 清理过期备份,只保留最新MaxBackupFileCount个
/// </summary>
/// <param name="backupDir">备份目录</param>
/// <param name="maxCount">最大保留数量</param>
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}");
}
}
}
}
}
/// <summary>
/// 备份选项
/// </summary>
public class DbBackupOptions
{
/// <summary>
/// 源SQLite数据库文件完整路径,不设置则自动从SqlSugar连接串读取
/// </summary>
public string? SourceDbFilePath { get; set; }
/// <summary>
/// 备份存放目录
/// </summary>
public string? BackupDirectory { get; set; }
/// <summary>
/// 备份文件最大数量
/// </summary>
public int MaxBackupFileCount { get; set; }
}
}

View File

@ -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
/// <summary>
/// 数据库上下文
/// </summary>
public class DbContext:SqlSugarClient
public class DbContext:Falcon.SugarCore.DbContextExtensions.DbContext
{
public AppConfig Config { get; init; }
@ -18,16 +17,20 @@ namespace PrivateBox
/// </summary>
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();
//}
/// <summary>
/// 初始化数据库
/// </summary>

View File

@ -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);

View File

@ -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; }
/// <summary>
/// 默认分组名
/// </summary>
@ -30,6 +34,7 @@ namespace PrivateBox
this.Db = provider.GetRequiredService<DbContext>();
this.Settings = provider.GetRequiredService<AppRunTimeSettings>();
this.CrytionKey = this.Db.GetCrytionKey();
this.Logger = provider.GetRequiredService<ILogger<MainForm>>();
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<CrytionItem>().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<CrytionItem>()
.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<CrytionItem>()
.Where(a => a.ItemName == sItem)
.SetColumns(a => a.Group == dlg.Msg)
.SetColumns(a => a.Group == msg)
.ExecuteCommand();
this.Logger.LogInformation($"修改分组:[{sItem}]{msg}");
}
RefreshGroupList();
}

View File

@ -117,12 +117,33 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="toolStripContainer1.Locked" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="splitContainer1.Locked" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="splitContainer3.Locked" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="clb_group.Locked" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="lbKeyList.Locked" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="menuKeyList.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>127, 17</value>
</metadata>
<metadata name="splitContainer2.Locked" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="toolStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="toolStrip1.Locked" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<assembly alias="System.Drawing" name="System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<data name="btSave.Image" type="System.Drawing.Bitmap, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>
@ -142,4 +163,10 @@
AAAAAElFTkSuQmCC
</value>
</data>
<metadata name="tbMessage.Locked" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="$this.Locked" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
</root>

View File

@ -10,7 +10,10 @@
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="SqlSugarCore" Version="5.1.4.162" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Module\Falcon.SugarCore\Falcon.SugarCore\Falcon.SugarCore.csproj" />
</ItemGroup>
<ItemGroup>

View File

@ -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<AppRunTimeSettings>();
AddServices(services,appConfig);
using ServiceProvider provider = GetServiceProvider(services);
var mainForm = provider.GetRequiredService<MainForm>();
using var providerScope = services.BuildServiceProviderWithSelf().CreateScope();
var sp = providerScope.ServiceProvider;
var logger = sp.GetRequiredService<ILoggerFactory>().CreateLogger("PrivateBoxMain");
var mainForm = sp.GetRequiredService<MainForm>();
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<IEncryptionService,AesEncryptionServiceV1>();
services.AddSingleton<DbContext>();
services.AddSqlLiteDbContext<DbContext>(config.SqliteFileName);
services.AddNLogger();
}
static ServiceProvider GetServiceProvider(IServiceCollection services) {
ServiceProvider? provider = null;
services.AddSingleton<IServiceProvider>(sp => provider!);
provider = services.BuildServiceProvider();
return provider;
}
}
}

View File

@ -0,0 +1,41 @@
namespace PrivateBox.SettingsBind
{
/// <summary>
/// 观察对象属性,并且可以进行读写
/// </summary>
public static class SettingsWatchExtend
{
/// <summary>
/// 观察列表
/// </summary>
private static List<object> _watchList { get; set; } = new();
/// <summary>
/// 添加观察对象属性
/// </summary>
/// <param name="settings">配置对象</param>
/// <param name="bindProc">要观察的对象属性</param>
public static void Watch(this AppRunTimeSettings settings,Action<object> watchProc) {
//1、把属性绑定加入绑定列表
}
/// <summary>
/// 读取观察列表,将现有属性值保存到数据库
/// </summary>
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);
//设置绑定对象的属性值
}
}
}
}