Compare commits
26
Commits
f838e3e0c5
..
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8aa295779c | ||
|
|
c3f574d5cf | ||
|
|
9c767ec551 | ||
|
|
c6676266af | ||
|
|
92f9e76536 | ||
|
|
fc50d39309 | ||
|
|
b37e5d7a14 | ||
|
|
776a42f510 | ||
|
|
372080590c | ||
|
|
34b7771efb | ||
|
|
13fcedcae5 | ||
|
|
07e98cec21 | ||
|
|
77c852ecf4 | ||
|
|
8d8c9902d3 | ||
|
|
1899a5da3d | ||
|
|
e078178352 | ||
|
|
a2c9f4ce80 | ||
|
|
567694e2e3 | ||
|
|
8a405eae29 | ||
|
|
bbdf6cf75f | ||
|
|
ad5a888816 | ||
|
|
09d572abce | ||
|
|
2cddbb204f | ||
|
|
5cd476f1d7 | ||
|
|
7286b3f9af | ||
|
|
2be238be8b |
No files matched your search
@@ -0,0 +1,79 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Runtime.Intrinsics.X86;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace ForwardingServerUI.Class
|
||||
{
|
||||
public class AES
|
||||
{
|
||||
public static string AesEncipher(string Key, string dat) //加密
|
||||
{
|
||||
//压缩
|
||||
byte[] plainBytes = Compress( Encoding.UTF8.GetBytes(dat));
|
||||
|
||||
using var sha256 = System.Security.Cryptography.SHA256.Create();
|
||||
using var aes = System.Security.Cryptography.Aes.Create();
|
||||
|
||||
aes.Key = sha256.ComputeHash(Encoding.UTF8.GetBytes(Key));
|
||||
aes.Mode = CipherMode.CBC;
|
||||
aes.Padding = PaddingMode.PKCS7;
|
||||
aes.GenerateIV(); // 生成随机 IV
|
||||
|
||||
using var enc = aes.CreateEncryptor();
|
||||
byte[] cipherBytes = enc.TransformFinalBlock(plainBytes, 0, plainBytes.Length);
|
||||
|
||||
//将 IV (16字节) 和 密文 拼接成一个完整的字节数组
|
||||
byte[] combinedBytes = new byte[aes.IV.Length + cipherBytes.Length];
|
||||
Buffer.BlockCopy(aes.IV, 0, combinedBytes, 0, aes.IV.Length);
|
||||
Buffer.BlockCopy(cipherBytes, 0, combinedBytes, aes.IV.Length, cipherBytes.Length);
|
||||
|
||||
return Convert.ToBase64String(combinedBytes);
|
||||
}
|
||||
|
||||
public static string AesDecrypt(string Key, string dat)//解密
|
||||
{
|
||||
// 解码Base64
|
||||
byte[] cipherBytes = Convert.FromBase64String(dat);
|
||||
|
||||
using var sha256 = System.Security.Cryptography.SHA256.Create();
|
||||
using var aes = System.Security.Cryptography.Aes.Create();
|
||||
|
||||
aes.Key = sha256.ComputeHash(Encoding.UTF8.GetBytes(Key));
|
||||
aes.Mode = CipherMode.CBC;
|
||||
aes.Padding = PaddingMode.PKCS7;
|
||||
// 从字节数组中提取前 16 字节作为 IV
|
||||
aes.IV = cipherBytes.AsSpan(0, 16).ToArray();
|
||||
using var dec = aes.CreateDecryptor();
|
||||
|
||||
// 解密
|
||||
byte[] bytes = dec.TransformFinalBlock(cipherBytes, 16, cipherBytes.Length - 16);
|
||||
//解压缩并返回
|
||||
return Encoding.UTF8.GetString(Decompress(bytes));
|
||||
}
|
||||
|
||||
// 3. Brotli 压缩辅助方法
|
||||
private static byte[] Compress(byte[] data)
|
||||
{
|
||||
using var output = new MemoryStream();
|
||||
using (var brotli = new BrotliStream(output, CompressionLevel.Optimal))
|
||||
{
|
||||
brotli.Write(data, 0, data.Length);
|
||||
}
|
||||
return output.ToArray();
|
||||
}
|
||||
|
||||
// 4. Brotli 解压辅助方法
|
||||
private static byte[] Decompress(byte[] data)
|
||||
{
|
||||
using var input = new MemoryStream(data);
|
||||
using var brotli = new BrotliStream(input, CompressionMode.Decompress);
|
||||
using var output = new MemoryStream();
|
||||
brotli.CopyTo(output);
|
||||
return output.ToArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
+22
-11
@@ -73,11 +73,30 @@ namespace ForwardingServerUI.Class
|
||||
await AsyncTcpServer.service.SendAsync(s_, bodyString);
|
||||
|
||||
MainWindowViewModel.Person deserializedPerson = JsonSerializer.Deserialize<MainWindowViewModel.Person>(bodyString)!;
|
||||
|
||||
|
||||
Application.Current.Dispatcher.Invoke(() => {
|
||||
MainWindowViewModel._userTable.Rows.Add(client.Id, client.IP, deserializedPerson.User,
|
||||
"", deserializedPerson.Terminal, "", "");
|
||||
URL, deserializedPerson.Terminal, "", "");
|
||||
});
|
||||
//记录请求指令
|
||||
string AESDATA = Regex.Replace(
|
||||
AES.AesDecrypt(deserializedPerson.Terminal, deserializedPerson.Dat)
|
||||
, @"\\u[0-9A-Fa-f]{4}", match =>
|
||||
{
|
||||
return Regex.Unescape(match.Value);
|
||||
});
|
||||
//记录
|
||||
Dictionary<string, object> userlog = new Dictionary<string, object>();
|
||||
userlog.Add("User", deserializedPerson.User);
|
||||
userlog.Add("LastLoginIP", deserializedPerson.IP);
|
||||
userlog.Add("IP", client.IP);
|
||||
userlog.Add("LastLoginTerminal", deserializedPerson.Terminal);
|
||||
userlog.Add("Note", AESDATA);
|
||||
userlog.Add("Enterprise", URL);
|
||||
userlog.Add("Time", DateTime.Now.ToString("yyyy-MM-dd dd:HH:mm:ss:fff"));
|
||||
MainWindowViewModel.SQLiteHelpers.InsertData("ActionLog", userlog);
|
||||
LogGing.LINKDATA(URL, "[COMMAND]" + deserializedPerson.User, AESDATA);
|
||||
|
||||
// 创建一个 秒的延时任务
|
||||
Task delayTask = Task.Delay(15000);
|
||||
// 创建一个监测任务,不断检查变量
|
||||
@@ -142,15 +161,7 @@ namespace ForwardingServerUI.Class
|
||||
await e.InvokeNext();*/
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
+156
-43
@@ -4,11 +4,14 @@ using System.Data;
|
||||
using System.Security.Cryptography.Pkcs;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading.Channels;
|
||||
using System.Windows;
|
||||
using System.Windows.Markup;
|
||||
using System.Xml.Linq;
|
||||
using TouchSocket.Core;
|
||||
using TouchSocket.Sockets;
|
||||
using static ForwardingServerUI.MainWindowViewModel;
|
||||
using static System.Runtime.InteropServices.JavaScript.JSType;
|
||||
|
||||
namespace ForwardingServerUI.Class
|
||||
@@ -24,25 +27,40 @@ namespace ForwardingServerUI.Class
|
||||
public required string SERRVERPASWORD { get; set; }
|
||||
public required string MachineVer { get; set; }
|
||||
}
|
||||
public class PersonUser
|
||||
{
|
||||
public required string User { get; set; }
|
||||
public required string Password { get; set; }
|
||||
public required string IP { get; set; }
|
||||
public required string Terminal { get; set; }
|
||||
public required string Dat { get; set; }
|
||||
}
|
||||
|
||||
private static Timer? _timer;
|
||||
public static TcpService service = new TcpService();
|
||||
|
||||
public static async Task TcpMain()
|
||||
{
|
||||
//TcpService service = new TcpService();
|
||||
service.Connecting = (client, e) => { return EasyTask.CompletedTask; };//有客户端正在连接
|
||||
service.Connected = (client, e) => {return EasyTask.CompletedTask;};//有客户端成功连接
|
||||
service.Closing = (client, e) => {return EasyTask.CompletedTask; };//有客户端正在断开连接,只有当主动断开时才有效。
|
||||
service.Closed = (client, e) => {
|
||||
service.Connected = (client, e) => { return EasyTask.CompletedTask;};//有客户端成功连接
|
||||
service.Closing = (client, e) => { return EasyTask.CompletedTask; };//有客户端正在断开连接,只有当主动断开时才有效。
|
||||
service.Closed = (client, e) =>
|
||||
{
|
||||
//离线记录
|
||||
DataRow[] dat = MainWindowViewModel._machineTable.Select("ID='"+client.Id+"'");
|
||||
foreach (DataRow row in dat)
|
||||
Console.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "] NOT ID " +
|
||||
client.Id + " IP " + client.IP);
|
||||
Application.Current.Dispatcher.Invoke(() =>
|
||||
{
|
||||
Application.Current.Dispatcher.Invoke(() => {
|
||||
MainWindowViewModel._machineTable.Rows.Remove(row);
|
||||
});
|
||||
}
|
||||
Console.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-DD HH:mm:ss:fff") + "] NOT ID " + client.Id + " IP " + client.IP);
|
||||
DataRow row = MainWindowViewModel._machineTable.Select("ID='" + client.Id + "'").First();
|
||||
|
||||
return EasyTask.CompletedTask;
|
||||
Console.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "] BREAK LINK ID = " +
|
||||
row["ID"] + " IP = " + row["IP"] + " Enterprise = " + row["Enterprise"] +
|
||||
" MachineName = " + row["MachineName"]);
|
||||
|
||||
MainWindowViewModel._machineTable.Rows.Remove(row);
|
||||
});
|
||||
|
||||
return EasyTask.CompletedTask;
|
||||
};//有客户端断开连接
|
||||
service.Received = (client, e) =>{
|
||||
string DAT = e.Memory.Span.ToString(Encoding.UTF8);
|
||||
@@ -57,51 +75,88 @@ namespace ForwardingServerUI.Class
|
||||
|
||||
if (s_ == 30)
|
||||
{
|
||||
if (DAT.StartsWith("{") || DAT.StartsWith("["))
|
||||
string trimmedDat = DAT.Trim();
|
||||
if (!string.IsNullOrEmpty(trimmedDat) &&
|
||||
(trimmedDat[0] == '{' || trimmedDat[0] == '['))
|
||||
{
|
||||
MainWindowViewModel.Person deserializedPerson = JsonSerializer.Deserialize<MainWindowViewModel.Person>(DAT)!;
|
||||
MainWindowViewModel.Person deserializedPerson = JsonSerializer.Deserialize<MainWindowViewModel.Person>(trimmedDat)!;
|
||||
|
||||
//转发逻辑
|
||||
var dr = MainWindowViewModel._userTable.Select("Terminal='" + deserializedPerson.Terminal + "'");
|
||||
if (dr.Length > 0)
|
||||
{
|
||||
DataRow drEmployee = dr.First();
|
||||
drEmployee.BeginEdit();
|
||||
drEmployee["RDAT"] = DAT;
|
||||
drEmployee["RDAT"] = trimmedDat;
|
||||
drEmployee.EndEdit();
|
||||
drEmployee.AcceptChanges();
|
||||
|
||||
PersonUser deserializedPersonuser = JsonSerializer.Deserialize<PersonUser>(trimmedDat)!;
|
||||
string data = AES.AesDecrypt(deserializedPersonuser.Terminal, deserializedPersonuser.Dat);
|
||||
string decodedData = Regex.Replace(data, @"\\u[0-9A-Fa-f]{4}", match =>
|
||||
{
|
||||
return Regex.Unescape(match.Value);
|
||||
});
|
||||
|
||||
Dictionary<string, object> userlog = new Dictionary<string, object>();
|
||||
userlog.Add("User", drEmployee["User"]);
|
||||
userlog.Add("LastLoginIP", drEmployee["IP"]);
|
||||
userlog.Add("LastLoginTerminal", drEmployee["Terminal"]);
|
||||
userlog.Add("Note", decodedData);
|
||||
userlog.Add("Enterprise", drEmployee["Enterprise"]);
|
||||
userlog.Add("Time", DateTime.Now.ToString("yyyy-MM-dd dd:HH:mm:ss:fff"));
|
||||
SQLiteHelpers.InsertData("ActionLog", userlog);
|
||||
|
||||
LogGing.LINKDATA(drEmployee["Enterprise"].ToString()!,"[REPLY]"+ drEmployee["User"].ToString()!, decodedData);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
else if (s_ == 90)
|
||||
{ }
|
||||
Application.Current.Dispatcher.Invoke(() =>
|
||||
{
|
||||
DataRow drEmployee = r_.First();
|
||||
drEmployee.BeginEdit();
|
||||
drEmployee["HeartbeatTime"] = DateTime.Now.ToString();
|
||||
drEmployee.EndEdit();
|
||||
drEmployee.AcceptChanges();
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
Personm deserializedPerson = JsonSerializer.Deserialize<Personm>(DAT)!;
|
||||
Application.Current.Dispatcher.Invoke(() => {
|
||||
var mach = MainWindowViewModel._machineTable.Select("Enterprise='" + deserializedPerson.SERVEREnterprise +
|
||||
"'and MachineName='" + deserializedPerson.SERVERMachineName + "'");
|
||||
if (mach.Length > 0)
|
||||
string trimmedDat = DAT.Trim();
|
||||
if (!string.IsNullOrEmpty(trimmedDat) &&
|
||||
(trimmedDat[0] == '{' || trimmedDat[0] == '['))
|
||||
{
|
||||
Personm deserializedPerson = JsonSerializer.Deserialize<Personm>(trimmedDat)!;
|
||||
Application.Current.Dispatcher.Invoke(() =>
|
||||
{
|
||||
DataRow dataRow = mach.First();
|
||||
dataRow.BeginEdit();
|
||||
dataRow["ID"] = client.Id;
|
||||
dataRow["IP"] = client.IP;
|
||||
dataRow["Start"] = 30;
|
||||
dataRow["Enterprise"] = "/" + deserializedPerson.SERVEREnterprise;
|
||||
dataRow["MachineName"] = deserializedPerson.SERVERMachineName;
|
||||
dataRow["MachineVer"] = deserializedPerson.MachineVer;
|
||||
dataRow.EndEdit();
|
||||
dataRow.AcceptChanges();
|
||||
}
|
||||
else
|
||||
{
|
||||
MainWindowViewModel._machineTable.Rows.Add(client.Id, client.IP, 30, "/" + deserializedPerson.SERVEREnterprise,
|
||||
deserializedPerson.SERVERMachineName, deserializedPerson.MachineVer);
|
||||
|
||||
}
|
||||
});
|
||||
Console.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-DD HH:mm:ss:fff") + " [LINK ID " + client.Id + " IP " + client.IP + "]\nDATA =" + DAT);
|
||||
|
||||
var mach = MainWindowViewModel._machineTable.Select("Enterprise='" + deserializedPerson.SERVEREnterprise +
|
||||
"'and MachineName='" + deserializedPerson.SERVERMachineName + "'");
|
||||
if (mach.Length > 0)
|
||||
{
|
||||
//刷新设备信息表
|
||||
DataRow dataRow = mach.First();
|
||||
dataRow.BeginEdit();
|
||||
dataRow["ID"] = client.Id;
|
||||
dataRow["IP"] = client.IP;
|
||||
dataRow["Start"] = 30;
|
||||
dataRow["Enterprise"] = "/" + deserializedPerson.SERVEREnterprise;
|
||||
dataRow["MachineName"] = deserializedPerson.SERVERMachineName;
|
||||
dataRow["MachineVer"] = deserializedPerson.MachineVer;
|
||||
dataRow.EndEdit();
|
||||
dataRow.AcceptChanges();
|
||||
}
|
||||
else
|
||||
{
|
||||
//添加设备信息表
|
||||
MainWindowViewModel._machineTable.Rows.Add(client.Id, client.IP, 30, "/" + deserializedPerson.SERVEREnterprise,
|
||||
deserializedPerson.SERVERMachineName, DateTime.Now.ToString(), deserializedPerson.MachineVer);
|
||||
}
|
||||
});
|
||||
}
|
||||
Console.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " LINK ID " + client.Id + " IP " + client.IP + "]\nDATA =" + DAT);
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -131,7 +186,65 @@ namespace ForwardingServerUI.Class
|
||||
await service.StartAsync();//启动
|
||||
|
||||
Console.WriteLine("TcpServer:Run");
|
||||
}
|
||||
|
||||
|
||||
//启动检查循环定时器
|
||||
_timer = new Timer(TimerCallback, null, TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(30));
|
||||
}
|
||||
|
||||
private static async void TimerCallback(object? state)
|
||||
{
|
||||
try
|
||||
{
|
||||
DataRow[] row = MainWindowViewModel._machineTable.Select("HeartbeatTime<'" + DateTime.Now.AddSeconds(-30).ToString() + "'");
|
||||
|
||||
Application.Current.Dispatcher.Invoke(() =>
|
||||
{
|
||||
foreach (var dataRow in row)
|
||||
{
|
||||
if ((int)dataRow["Start"] == 30)
|
||||
{
|
||||
dataRow.BeginEdit();
|
||||
dataRow["Start"] = 999;
|
||||
dataRow.EndEdit();
|
||||
dataRow.AcceptChanges();
|
||||
|
||||
Console.WriteLine($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}] NOT LINK ID = {dataRow["ID"]} " +
|
||||
$"IP = {dataRow["IP"]} Enterprise = {dataRow["Enterprise"]} " +
|
||||
$"MachineName = {dataRow["MachineName"]}");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
DataRow[] rowout = MainWindowViewModel._machineTable.Select("HeartbeatTime<'" + DateTime.Now.AddSeconds(-120).ToString() + "'");
|
||||
|
||||
Application.Current.Dispatcher.Invoke(() =>
|
||||
{
|
||||
foreach (var dataRow in rowout)
|
||||
{
|
||||
dataRow.BeginEdit();
|
||||
dataRow["Start"] = 999;
|
||||
dataRow.EndEdit();
|
||||
dataRow.AcceptChanges();
|
||||
|
||||
foreach (var item in service.Clients)
|
||||
{
|
||||
if (item.Id == dataRow["ID"].ToString())
|
||||
{
|
||||
item.CloseAsync(); // 关闭完成
|
||||
item.Dispose(); // 释放资源
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine(ex.ToString());
|
||||
LogGing.ERRDATA(ex);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,25 @@ namespace ForwardingServerUI.Class
|
||||
{
|
||||
public class LogGing
|
||||
{
|
||||
public static void LINKDATA(string path,string User, string dat)
|
||||
{
|
||||
string logpath = System.Environment.CurrentDirectory + "\\DB\\"+path;//日志文件目录
|
||||
string logPath = logpath +"\\" + DateTime.Now.ToString(" yyyy-MM-dd HH-mm-ss-ffff") + User + ".txt";//日志文件
|
||||
|
||||
if (Directory.Exists(logpath))//检查日志路径
|
||||
{
|
||||
FileStream fs = new FileStream(logPath, FileMode.CreateNew, FileAccess.Write);//创建写入文件
|
||||
StreamWriter wr = new StreamWriter(fs);//创建文件
|
||||
wr.WriteLine(dat);
|
||||
wr.Close();
|
||||
}
|
||||
else
|
||||
{
|
||||
DirectoryInfo directoryInfo = new DirectoryInfo(logpath);
|
||||
directoryInfo.Create();//创建日志路径
|
||||
}
|
||||
}
|
||||
|
||||
public static void LogGingDATA(string dat)
|
||||
{
|
||||
string logpath = System.Environment.CurrentDirectory + "\\Log";//日志文件目录
|
||||
|
||||
@@ -0,0 +1,504 @@
|
||||
using Microsoft.Data.Sqlite;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Data.Common;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
|
||||
namespace ForwardingServerUI.Class
|
||||
{
|
||||
public class ClsLock : IDisposable
|
||||
{
|
||||
private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();
|
||||
|
||||
public IDisposable Read()
|
||||
{
|
||||
_lock.EnterReadLock();
|
||||
return new DisposableAction(() => _lock.ExitReadLock());
|
||||
}
|
||||
|
||||
public void Dispose() => _lock?.Dispose();
|
||||
|
||||
private class DisposableAction : IDisposable
|
||||
{
|
||||
private readonly Action _action;
|
||||
public DisposableAction(Action action) => _action = action;
|
||||
public void Dispose() => _action?.Invoke();
|
||||
}
|
||||
}
|
||||
|
||||
public class SqliteHelper
|
||||
{
|
||||
#region 字段
|
||||
private SqliteTransaction? dbTrans = null!;
|
||||
private static readonly Dictionary<string, ClsLock> RWL = new Dictionary<string, ClsLock>();
|
||||
private readonly string mDataFile;
|
||||
private readonly string mPassWord = "";
|
||||
private readonly string lockName = "";
|
||||
private SqliteConnection mConn = null!;
|
||||
#endregion
|
||||
|
||||
#region 构造函数
|
||||
public SqliteHelper(string dataFile)
|
||||
{
|
||||
this.mDataFile = dataFile ?? throw new ArgumentNullException(nameof(dataFile));
|
||||
this.mDataFile = dataFile; // 注意:原代码有两次赋值,保留逻辑
|
||||
if (!RWL.ContainsKey(dataFile))
|
||||
{
|
||||
lockName = dataFile;
|
||||
RWL.Add(dataFile, new ClsLock());
|
||||
}
|
||||
}
|
||||
|
||||
public SqliteHelper(string dataFile, string PassWord)
|
||||
{
|
||||
this.mDataFile = dataFile ?? throw new ArgumentNullException(nameof(dataFile));
|
||||
this.mPassWord = PassWord ?? throw new ArgumentNullException(nameof(PassWord));
|
||||
this.mDataFile = dataFile;
|
||||
if (!RWL.ContainsKey(dataFile))
|
||||
{
|
||||
lockName = dataFile;
|
||||
RWL.Add(dataFile, new ClsLock());
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 打开/关闭 数据库
|
||||
// 注意:Microsoft.Data.Sqlite.Core 不支持连接字符串构建器,需手动拼接
|
||||
// 加密支持通常需要 Microsoft.Data.Sqlite.Core + SQLitePCLRaw.bundle_green (且加密功能可能受限)
|
||||
|
||||
public void Open()
|
||||
{
|
||||
// 构建连接字符串
|
||||
var connectionString = $"Data Source={mDataFile}";
|
||||
if (!string.IsNullOrWhiteSpace(mPassWord))
|
||||
{
|
||||
connectionString += $";Password={mPassWord}"; // 注意:原生 Microsoft.Data.Sqlite 不支持加密
|
||||
// 如果需要加密,通常需要使用 SQLitePCLRaw 的特定提供程序或第三方库
|
||||
}
|
||||
|
||||
mConn = new SqliteConnection(connectionString);
|
||||
|
||||
// 如果文件不存在,Open() 会自动创建数据库文件
|
||||
// 但表结构需要你自己执行 CREATE TABLE
|
||||
mConn.Open();
|
||||
|
||||
Console.WriteLine("The database was opened successfully");
|
||||
}
|
||||
|
||||
public void Close()
|
||||
{
|
||||
if (this.mConn != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
this.mConn.Close();
|
||||
// 注意:不要在这里移除 RWL,因为这是静态的,可能影响其他实例
|
||||
// if (RWL.ContainsKey(LockName)) { RWL.Remove(LockName); }
|
||||
}
|
||||
catch
|
||||
{
|
||||
Console.WriteLine("Shutdown failed");
|
||||
}
|
||||
}
|
||||
Console.WriteLine("The database was shut down successfully");
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 事务
|
||||
public void BeginTrain()
|
||||
{
|
||||
EnsureConnection();
|
||||
dbTrans = mConn.BeginTransaction();
|
||||
}
|
||||
|
||||
public void DBCommit()
|
||||
{
|
||||
try
|
||||
{
|
||||
dbTrans?.Commit();
|
||||
dbTrans?.Dispose();
|
||||
dbTrans = null; // 提交后置空
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
dbTrans?.Rollback();
|
||||
dbTrans?.Dispose();
|
||||
dbTrans = null;
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 工具
|
||||
// OpenConnection 逻辑已合并到 Open() 方法中,因为 SqliteConnection 构造函数只接受字符串
|
||||
|
||||
public SqliteConnection Connection
|
||||
{
|
||||
get { return mConn; }
|
||||
private set { mConn = value ?? throw new ArgumentNullException(); }
|
||||
}
|
||||
|
||||
protected void EnsureConnection()
|
||||
{
|
||||
if (this.mConn == null)
|
||||
{
|
||||
throw new Exception("SQLiteManager.Connection=null");
|
||||
}
|
||||
if (mConn.State != ConnectionState.Open)
|
||||
{
|
||||
mConn.Open();
|
||||
}
|
||||
}
|
||||
|
||||
public string GetDataFile() => this.mDataFile;
|
||||
|
||||
public bool TableExists(string table)
|
||||
{
|
||||
if (string.IsNullOrEmpty(table)) return false;
|
||||
EnsureConnection();
|
||||
|
||||
// 注意:参数化查询在表名/列名上无效,这里使用字符串拼接(需确保table变量安全)
|
||||
// 或者使用 PRAGMA table_info(table_name)
|
||||
var sql = $"SELECT count(*) FROM sqlite_master WHERE type='table' AND name='{table}'";
|
||||
|
||||
using (var cmd = new SqliteCommand(sql, Connection))
|
||||
{
|
||||
var result = cmd.ExecuteScalar();
|
||||
return Convert.ToInt32(result) > 0;
|
||||
}
|
||||
}
|
||||
|
||||
public bool Vacuum()
|
||||
{
|
||||
try
|
||||
{
|
||||
using (var Command = new SqliteCommand("VACUUM", Connection))
|
||||
{
|
||||
Command.ExecuteNonQuery();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
catch (Exception) // SqliteException
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将 IDataReader 转换为 DataSet
|
||||
/// </summary>
|
||||
/// <param name="reader">已经执行了查询的 DataReader</param>
|
||||
/// <returns>包含数据的 DataSet</returns>
|
||||
public DataSet ReaderToDataSet(IDataReader reader)
|
||||
{
|
||||
DataSet ds = new DataSet();
|
||||
|
||||
do
|
||||
{
|
||||
DataTable schemaTable = reader.GetSchemaTable()!;
|
||||
DataTable dataTable = new DataTable();
|
||||
|
||||
if (schemaTable != null)
|
||||
{
|
||||
// 创建列
|
||||
foreach (DataRow schemaRow in schemaTable.Rows)
|
||||
{
|
||||
string colName = schemaRow["ColumnName"].ToString()!;
|
||||
Type dataType = (Type)schemaRow["DataType"];
|
||||
|
||||
// 防止列名重复
|
||||
string uniqueColName = colName;
|
||||
int i = 1;
|
||||
while (dataTable.Columns.Contains(uniqueColName))
|
||||
{
|
||||
uniqueColName = colName + i++;
|
||||
}
|
||||
|
||||
DataColumn column = new DataColumn(uniqueColName, dataType);
|
||||
dataTable.Columns.Add(column);
|
||||
}
|
||||
|
||||
// 读取行
|
||||
while (reader.Read())
|
||||
{
|
||||
object[] values = new object[dataTable.Columns.Count];
|
||||
for (int i = 0; i < dataTable.Columns.Count; i++)
|
||||
{
|
||||
values[i] = reader.IsDBNull(i) ? DBNull.Value : reader.GetValue(i);
|
||||
}
|
||||
dataTable.Rows.Add(values);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// 如果没有 Schema (例如 "SELECT 1" 这种标量查询)
|
||||
// 需要手动创建列
|
||||
for (int i = 0; i < reader.FieldCount; i++)
|
||||
{
|
||||
dataTable.Columns.Add("Column" + i);
|
||||
}
|
||||
while (reader.Read())
|
||||
{
|
||||
object[] values = new object[reader.FieldCount];
|
||||
reader.GetValues(values);
|
||||
dataTable.Rows.Add(values);
|
||||
}
|
||||
}
|
||||
|
||||
ds.Tables.Add(dataTable);
|
||||
} while (reader.NextResult()); // 处理多个结果集
|
||||
|
||||
return ds;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
|
||||
#region 执行SQL (Reader & Scalar)
|
||||
|
||||
public SqliteDataReader? ExecuteReader(string sql, SqliteParameter[]? paramArr)
|
||||
{
|
||||
if (string.IsNullOrEmpty(sql)) throw new ArgumentNullException(nameof(sql));
|
||||
EnsureConnection();
|
||||
|
||||
// 注意:using 语句会立即释放 Reader,导致无法读取
|
||||
// 这里的 RWL 锁在 using 外部处理,或者调用方自己处理锁
|
||||
// 这里简化逻辑,直接返回 Reader,调用方需自行管理连接状态
|
||||
var cmd = new SqliteCommand(sql, Connection);
|
||||
|
||||
if (paramArr != null)
|
||||
{
|
||||
cmd.Parameters.AddRange(paramArr);
|
||||
}
|
||||
|
||||
// CommandBehavior.CloseConnection 确保 Reader 关闭时连接也关闭
|
||||
// 但这里我们管理连接,所以不加
|
||||
try
|
||||
{
|
||||
// 注意:不要在这里 Dispose Command,否则 Reader 会失效
|
||||
// 返回 Reader,由调用方在读取完毕后关闭
|
||||
return cmd.ExecuteReader();
|
||||
}
|
||||
catch(Exception ex)
|
||||
{
|
||||
Console.WriteLine("[SQLITE_ExecuteReader:err]" + ex.ToString());
|
||||
cmd?.Dispose();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public DataSet? ExecuteDataSet(string sql, SqliteParameter[]? paramArr)
|
||||
{
|
||||
var dat = ExecuteReader(sql, paramArr);
|
||||
if (dat == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
return ReaderToDataSet(dat);
|
||||
}
|
||||
|
||||
// ExecuteScalar
|
||||
public object? ExecuteScalar(string sql, SqliteParameter[]? paramArr)
|
||||
{
|
||||
if (string.IsNullOrEmpty(sql)) throw new ArgumentNullException(nameof(sql));
|
||||
EnsureConnection();
|
||||
|
||||
using (RWL[lockName].Read())
|
||||
{
|
||||
using (var cmd = new SqliteCommand(sql, Connection))
|
||||
{
|
||||
if (paramArr != null)
|
||||
{
|
||||
cmd.Parameters.AddRange(paramArr);
|
||||
}
|
||||
try
|
||||
{
|
||||
return cmd.ExecuteScalar();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine("[SQLITE_ExecuteScalar:err]" + ex.ToString());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// QueryOne (返回字典或对象)
|
||||
public Dictionary<string, object?>? QueryOne(string table, string conditionCol, object conditionVal)
|
||||
{
|
||||
if (string.IsNullOrEmpty(table)) return null;
|
||||
EnsureConnection();
|
||||
|
||||
string sql = $"SELECT * FROM [{table}]"; // 使用 [] 防止关键字冲突
|
||||
var parameters = new List<SqliteParameter>();
|
||||
|
||||
if (!string.IsNullOrEmpty(conditionCol))
|
||||
{
|
||||
sql += $" WHERE [{conditionCol}] = @{conditionCol}";
|
||||
parameters.Add(new SqliteParameter($"@{conditionCol}", conditionVal));
|
||||
}
|
||||
|
||||
using (var cmd = new SqliteCommand(sql, Connection))
|
||||
{
|
||||
cmd.Parameters.AddRange(parameters.ToArray());
|
||||
using (var reader = cmd.ExecuteReader())
|
||||
{
|
||||
if (reader.Read())
|
||||
{
|
||||
var dict = new Dictionary<string, object?>();
|
||||
for (int i = 0; i < reader.FieldCount; i++)
|
||||
{
|
||||
var value = reader.GetValue(i);
|
||||
if (value == DBNull.Value) value = null;
|
||||
dict[reader.GetName(i)] = value;
|
||||
}
|
||||
return dict;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 增 删 改
|
||||
// 注意:参数前缀统一为 @
|
||||
|
||||
public int InsertData(string table, Dictionary<string, object> entity)
|
||||
{
|
||||
if (string.IsNullOrEmpty(table)) throw new ArgumentNullException(nameof(table));
|
||||
EnsureConnection();
|
||||
|
||||
string sql = BuildInsert(table, entity);
|
||||
var parameters = BuildParamArray(entity);
|
||||
return ExecuteNonQuery(sql, parameters);
|
||||
}
|
||||
|
||||
public int Update(string table, Dictionary<string, object> entity, string where, SqliteParameter[]? whereParams)
|
||||
{
|
||||
if (string.IsNullOrEmpty(table)) throw new ArgumentNullException(nameof(table));
|
||||
EnsureConnection();
|
||||
|
||||
string sql = BuildUpdate(table, entity);
|
||||
var parameters = BuildParamArray(entity);
|
||||
|
||||
if (!string.IsNullOrEmpty(where))
|
||||
{
|
||||
sql += " WHERE " + where;
|
||||
if (whereParams != null)
|
||||
{
|
||||
var combined = new SqliteParameter[parameters.Length + whereParams.Length];
|
||||
parameters.CopyTo(combined, 0);
|
||||
whereParams.CopyTo(combined, parameters.Length);
|
||||
parameters = combined;
|
||||
}
|
||||
}
|
||||
|
||||
return ExecuteNonQuery(sql, parameters);
|
||||
}
|
||||
|
||||
public int Delete(string table, string where, SqliteParameter[]? whereParams)
|
||||
{
|
||||
if (string.IsNullOrEmpty(table)) return 0;
|
||||
EnsureConnection();
|
||||
|
||||
string sql = $"DELETE FROM [{table}]";
|
||||
if (!string.IsNullOrEmpty(where))
|
||||
{
|
||||
sql += " WHERE " + where;
|
||||
}
|
||||
|
||||
return ExecuteNonQuery(sql, whereParams);
|
||||
}
|
||||
|
||||
public int ExecuteNonQuery(string sql, SqliteParameter[]? paramArr)
|
||||
{
|
||||
if (string.IsNullOrEmpty(sql)) throw new ArgumentNullException(nameof(sql));
|
||||
EnsureConnection();
|
||||
|
||||
using (RWL[lockName].Read()) // 注意:写操作通常建议用 Write 锁
|
||||
{
|
||||
using (var cmd = new SqliteCommand(sql, Connection))
|
||||
{
|
||||
if (paramArr != null)
|
||||
{
|
||||
cmd.Parameters.AddRange(paramArr);
|
||||
}
|
||||
try
|
||||
{
|
||||
return cmd.ExecuteNonQuery();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine("[SQLITE_ExecuteScalar:err]" + ex.ToString());
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 构建 SQL 和 参数的方法保持不变,仅泛型类型变更
|
||||
private SqliteParameter[] BuildParamArray(Dictionary<string, object> entity)
|
||||
{
|
||||
var list = new List<SqliteParameter>();
|
||||
foreach (string key in entity.Keys)
|
||||
{
|
||||
// 注意:参数名必须包含 @ 前缀
|
||||
list.Add(new SqliteParameter($"@{key}", entity[key]));
|
||||
}
|
||||
return list.ToArray();
|
||||
}
|
||||
|
||||
private string BuildInsert(string table, Dictionary<string, object> entity)
|
||||
{
|
||||
var buf = new StringBuilder();
|
||||
buf.Append("INSERT INTO ").Append(table).Append(" (");
|
||||
var cols = new List<string>();
|
||||
var vals = new List<string>();
|
||||
foreach (string key in entity.Keys)
|
||||
{
|
||||
cols.Add(key);
|
||||
vals.Add($"@{key}");
|
||||
}
|
||||
buf.Append(string.Join(",", cols)).Append(") VALUES (");
|
||||
buf.Append(string.Join(",", vals)).Append(")");
|
||||
return buf.ToString();
|
||||
}
|
||||
|
||||
private string BuildUpdate(string table, Dictionary<string, object> entity)
|
||||
{
|
||||
var buf = new StringBuilder();
|
||||
buf.Append("UPDATE ").Append(table).Append(" SET ");
|
||||
var sets = new List<string>();
|
||||
foreach (string key in entity.Keys)
|
||||
{
|
||||
sets.Add($"{key} = @{key}");
|
||||
}
|
||||
buf.Append(string.Join(",", sets));
|
||||
return buf.ToString();
|
||||
}
|
||||
|
||||
// 辅助方法:DataRow 转 Dictionary (由于没有 DataTable,通常直接从 Reader 转)
|
||||
// 这里保留原方法签名,但实际使用中可能需要调整
|
||||
public Dictionary<string, object?> DataTableToDictionary(DataTable dataTable)
|
||||
{
|
||||
var result = new Dictionary<string, object?>();
|
||||
if (dataTable.Rows.Count > 0)
|
||||
{
|
||||
var row = dataTable.Rows[0];
|
||||
foreach (DataColumn column in dataTable.Columns)
|
||||
{
|
||||
var value = row[column];
|
||||
if (value == DBNull.Value) value = null;
|
||||
result[column.ColumnName] = value;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,8 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.2" />
|
||||
<PackageReference Include="Microsoft.Data.Sqlite" Version="10.0.10" />
|
||||
<PackageReference Include="Microsoft.Data.Sqlite.Core" Version="10.0.10" />
|
||||
<PackageReference Include="TouchSocket" Version="4.2.16" />
|
||||
<PackageReference Include="TouchSocket.Http" Version="4.2.16" />
|
||||
</ItemGroup>
|
||||
|
||||
+13
-1
@@ -5,7 +5,9 @@ using ForwardingServerUI.Class;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Reflection.PortableExecutable;
|
||||
using System.Text;
|
||||
using TouchSocket.Sockets;
|
||||
|
||||
namespace ForwardingServerUI
|
||||
{
|
||||
@@ -25,16 +27,24 @@ namespace ForwardingServerUI
|
||||
[ObservableProperty]
|
||||
public static DataTable _userTable = new();
|
||||
|
||||
public static SqliteHelper SQLiteHelpers = null!; //定义数据库
|
||||
private readonly string DBAddress = Environment.CurrentDirectory + "\\DB\\DB.db"; //数据库路径
|
||||
public static DataTable ActionLog = new DataTable();
|
||||
public static readonly object TableLock = new object();
|
||||
|
||||
public async void Data()
|
||||
{
|
||||
SQLiteHelpers = new SqliteHelper(DBAddress); //数据库连接路径
|
||||
SQLiteHelpers.Open(); //打开数据库
|
||||
|
||||
_machineTable.Columns.Add("ID", typeof(string));
|
||||
_machineTable.Columns.Add("IP", typeof(string));
|
||||
_machineTable.Columns.Add("Start", typeof(int));
|
||||
_machineTable.Columns.Add("Enterprise", typeof(string));
|
||||
_machineTable.Columns.Add("MachineName", typeof(string));
|
||||
_machineTable.Columns.Add("HeartbeatTime", typeof(string));
|
||||
_machineTable.Columns.Add("MachineVer", typeof(string));
|
||||
|
||||
|
||||
_userTable.Columns.Add("ID", typeof(string));
|
||||
_userTable.Columns.Add("IP", typeof(string));
|
||||
_userTable.Columns.Add("User", typeof(string));
|
||||
@@ -52,5 +62,7 @@ namespace ForwardingServerUI
|
||||
{
|
||||
Data();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user