Compare commits

...
46 Commits
Author SHA1 Message Date
Administrator 9afd362de6 Merge branch 'master' of http://www.scserverddns.top:13000/sc/SunlightAggregationManager 2026-08-14 17:55:49 +08:00
Administrator 5b9cf5a538 Merge branch 'master' of http://www.scserverddns.top:13000/sc/SunlightAggregationManager 2026-08-14 17:55:48 +08:00
Administrator db203d01e1 Merge branch 'master' of http://www.scserverddns.top:13000/sc/SunlightAggregationManager 2026-08-14 17:10:32 +08:00
Administrator 8690824663 Merge branch 'master' of http://www.scserverddns.top:13000/sc/SunlightAggregationManager 2026-08-14 17:10:29 +08:00
Administrator 5ca8148c42 Merge branch 'master' of http://www.scserverddns.top:13000/sc/SunlightAggregationManager 2026-08-14 16:17:59 +08:00
Administrator e54cafd16b Merge branch 'master' of http://www.scserverddns.top:13000/sc/SunlightAggregationManager 2026-08-14 16:17:53 +08:00
Administrator c21504993f Merge branch 'master' of http://www.scserverddns.top:13000/sc/SunlightAggregationManager 2026-08-14 11:49:07 +08:00
Administrator 8e90c904ee Merge branch 'master' of http://www.scserverddns.top:13000/sc/SunlightAggregationManager 2026-08-14 11:49:04 +08:00
Administrator 85e60c01bc Merge branch 'master' of http://www.scserverddns.top:13000/sc/SunlightAggregationManager 2026-08-06 11:44:55 +08:00
sc 0ce1a57a53 查询逻辑修改,调整aes解码时机日志记录有密文改为明文 2026-08-06 11:44:53 +08:00
sc c2451be4a2 Merge branch 'master' of http://192.168.0.12:13000/sc/SunlightAggregationManager 2026-07-18 00:45:38 +08:00
sc 8aa79a46e3 Merge branch 'master' of http://192.168.0.12:13000/sc/SunlightAggregationManager 2026-07-18 00:45:36 +08:00
sc 654f73aca8 Merge branch 'master' of http://192.168.0.12:13000/sc/SunlightAggregationManager 2026-07-17 23:00:36 +08:00
Administrator a0eeb9c8c4 Merge branch 'master' of http://www.scserverddns.top:13000/sc/SunlightAggregationManager 2026-07-17 23:00:34 +08:00
Administrator ebbb44b132 Merge branch 'master' of http://www.scserverddns.top:13000/sc/SunlightAggregationManager 2026-07-03 16:53:40 +08:00
Administrator c94fe5c62f Merge branch 'master' of http://www.scserverddns.top:13000/sc/SunlightAggregationManager 2026-07-03 16:53:39 +08:00
Administrator ffc9b3d425 Merge branch 'master' of http://www.scserverddns.top:13000/sc/SunlightAggregationManager 2026-07-03 15:51:20 +08:00
Administrator d9d00cc9fa Merge branch 'master' of http://www.scserverddns.top:13000/sc/SunlightAggregationManager 2026-07-03 15:51:18 +08:00
Administrator e28be80856 Merge branch 'master' of http://www.scserverddns.top:13000/sc/SunlightAggregationManager 2026-07-03 15:31:15 +08:00
Administrator db73d606e8 Merge branch 'master' of http://www.scserverddns.top:13000/sc/SunlightAggregationManager 2026-07-03 15:31:13 +08:00
Administrator 7fb76a9d12 Merge branch 'master' of http://www.scserverddns.top:13000/sc/SunlightAggregationManager 2026-07-03 14:48:14 +08:00
Administrator 7437355573 Merge branch 'master' of http://www.scserverddns.top:13000/sc/SunlightAggregationManager 2026-07-03 14:48:11 +08:00
Administrator 65cfef8d02 Merge branch 'master' of http://www.scserverddns.top:13000/sc/SunlightAggregationManager 2026-06-25 17:34:26 +08:00
Administrator ea2e55787c 添加字符串加密 2026-06-25 17:34:17 +08:00
Administrator 85a4630020 Merge branch 'master' of http://www.scserverddns.top:13000/sc/SunlightAggregationManager 2026-06-25 13:36:30 +08:00
Administrator 5aca5ad39f Merge branch 'master' of http://www.scserverddns.top:13000/sc/SunlightAggregationManager 2026-06-25 13:36:27 +08:00
Administrator fd88cca4c6 Merge branch 'master' of http://www.scserverddns.top:13000/sc/SunlightAggregationManager 2026-06-25 12:42:38 +08:00
Administrator cb1e7a2e65 Merge branch 'master' of http://www.scserverddns.top:13000/sc/SunlightAggregationManager 2026-06-25 12:42:35 +08:00
Administrator ee65be0f93 Merge branch 'master' of http://www.scserverddns.top:13000/sc/SunlightAggregationManager 2026-06-25 12:38:04 +08:00
Administrator 59e1272cdb Merge branch 'master' of http://www.scserverddns.top:13000/sc/SunlightAggregationManager 2026-06-25 12:38:00 +08:00
sc 474093d2f2 Merge branch 'master' of http://192.168.0.12:13000/sc/SunlightAggregationManager 2026-06-21 18:19:14 +08:00
sc d39aadc98d Merge branch 'master' of http://192.168.0.12:13000/sc/SunlightAggregationManager 2026-06-21 18:19:12 +08:00
sc eb3e13c63a Merge branch 'master' of http://192.168.0.12:13000/sc/SunlightAggregationManager 2026-06-21 17:07:31 +08:00
Administrator 610c9c31ac Merge branch 'master' of http://www.scserverddns.top:13000/sc/SunlightAggregationManager 2026-06-21 17:07:30 +08:00
Administrator e38418500d Merge branch 'master' of http://www.scserverddns.top:13000/sc/SunlightAggregationManager 2026-06-12 00:11:00 +08:00
Administrator b70596cf31 Merge branch 'master' of http://www.scserverddns.top:13000/sc/SunlightAggregationManager 2026-06-12 00:10:59 +08:00
Administrator 5c8071f1f4 Merge branch 'master' of http://www.scserverddns.top:13000/sc/SunlightAggregationManager 2026-06-11 23:09:55 +08:00
Administrator 3bbfe20f84 Merge branch 'master' of http://www.scserverddns.top:13000/sc/SunlightAggregationManager 2026-06-11 23:09:25 +08:00
Administrator 9a5195cb0a Merge branch 'master' of http://www.scserverddns.top:13000/sc/SunlightAggregationManager 2026-06-11 00:36:15 +08:00
Administrator 683f8ac880 Merge branch 'master' of http://www.scserverddns.top:13000/sc/SunlightAggregationManager 2026-06-11 00:36:14 +08:00
Administrator 0b444636a4 Merge branch 'master' of http://www.scserverddns.top:13000/sc/SunlightAggregationManager 2026-06-10 20:23:08 +08:00
Administrator 710672bfc0 机台信息管理页面修改 2026-06-10 20:23:06 +08:00
Administrator a92610c2f4 Merge branch 'master' of http://www.scserverddns.top:13000/sc/SunlightAggregationManager 2026-06-08 23:24:38 +08:00
Administrator c43531c206 Merge branch 'master' of http://www.scserverddns.top:13000/sc/SunlightAggregationManager 2026-06-08 23:24:35 +08:00
Administrator f1085c0291 Merge branch 'master' of http://www.scserverddns.top:13000/sc/SunlightAggregationManager 2026-06-08 18:12:31 +08:00
Administrator 7860fe088b Merge branch 'master' of http://www.scserverddns.top:13000/sc/SunlightAggregationManager 2026-06-08 18:12:28 +08:00
13 changed files with 997 additions and 256 deletions

No files matched your search

+23
View File
@@ -0,0 +1,23 @@
[SYS]
Language=zh-CN
Name=YZ
Enterprise=YONGZHAO
[SQL_SERVER]
SQL1=192.168.15.248
SQL2=BatchDyeingCentral
SQL3=SQL SERVER
SQL4=sa
SQL5=yf888999
[NETWORK]
TCP=1
HTTP=1
TLS=0
TCP_PORT1=7789
TCP_PORT2=7790
HTTP_PORT=7791
[SERVER]
SERVERIP=www.scserverddns.top:7795
SERVERNAME=SUNLIGHT
SERVERUSER=SUNLIGHT
SERRVERPASWORD=SUNLIGHT
Binary file not shown.
+79
View File
@@ -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 SunlightAggregationManager.UserClass
{
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();
}
}
}
+121 -6
View File
@@ -136,18 +136,31 @@ namespace SunlightAggregationManager.UserClass
DataRow? _user = MainWindowViewModel.Selet_Row(MainWindowViewModel._userData, "User='" +
deserializedPerson?.User + "' and Password ='" + deserializedPerson?.Password + "'");
data_.Add("Enterprise", _user?.Field<object>("Enterprise") ?? "");
data_.Add("Enterprise",MainWindowViewModel.Enterprise);
data_.Add("Department", _user?.Field<object>("Department") ?? "");
data_.Add("Groups", _user?.Field<object>("Groups") ?? "");
data_.Add("UserId", _user?.Field<object>("UserID") ?? "");
data_.Add("UserName", _user?.Field<object>("Name") ?? "");
ret = JsonSerializer.Serialize(data_);
}
if (Command == "SysData")//回复请求的信息
{
ret = JsonSerializer.Serialize(data_);
}
if (Command == "ChemicalStatistics")//回复请求的信息
{
data_.Add("ChemicalStatistics", Newtonsoft.Json.JsonConvert.SerializeObject(MainWindowViewModel.ChemicalStatistics));
ret = JsonSerializer.Serialize(data_);
}
if (Command == "Info")//回复info请求的信息
{
var t = ToList(MainWindowViewModel._machines).ToJsonString();
//格式化返回信息
data_.Add("Info", t);
data_.Add("DyeMeasurementNumber", MainWindowViewModel.DyeMeasurementNumber.ToString());
data_.Add("ChemicalNumber", MainWindowViewModel.ChemicalNumber.ToString());
data_.Add("PowderNumber", MainWindowViewModel.PowderNumber.ToString());
data_.Add("DyeDissolveNumber", MainWindowViewModel.DyeDissolveNumber.ToString());
ret = JsonSerializer.Serialize(data_);
}
if (Command == "Query")//回复Query请求的信息
@@ -173,7 +186,7 @@ namespace SunlightAggregationManager.UserClass
data_.Add("Query", Newtonsoft.Json.JsonConvert.SerializeObject(resultTable));
ret = JsonSerializer.Serialize(data_);
}
if (Command == "QueryDetail")//回复info请求的信息
if (Command == "QueryDetail")//回复QueryDetail请求的信息
{
string d_ = deserialized.GetValue("Dyelot").ToString()!;
string r_ = deserialized.GetValue("ReDye").ToString()!;
@@ -193,15 +206,117 @@ namespace SunlightAggregationManager.UserClass
var groups = MainWindowViewModel.Selet_Memory(MainWindowViewModel._userData,
"Groups", "User='" + deserializedPerson?.User + "'");
var resultTable = MainWindowViewModel.SQLiteHelpers.ExecuteDataSet("" +
"select * from Notification WHERE Groups='" + groups + "' and Time>'" +
s_ + "' and Time<'" + e_ + "'", null)?.Tables[0] ?? new DataTable();
DataTable resultTable = MainWindowViewModel.SQLiteHelpers.ExecuteDataSet("" +
"select * from Notification WHERE Groups='" + groups + "' and Id>'" +
s_ + "'", null)?.Tables[0] ?? new DataTable();
if (resultTable.Rows.Count == 0) resultTable.Rows.Add();
//格式化返回信息
data_.Add("Notification", Newtonsoft.Json.JsonConvert.SerializeObject(resultTable));
ret = JsonSerializer.Serialize(data_);
}
if (Command == "InfoMachine")//回复InfoMachine请求的信息
{
string t_ = deserialized.GetValue("Type").ToString()!;
string? m_ = null, f_ = "*";
if (deserialized.TryGetValue("MachinName", out var MachinName) && MachinName != null) m_ = MachinName.ToString();
if (deserialized.TryGetValue("Field", out var Field) && Field != null) f_ = Field.ToString();
if (t_ == "10")
{
DataTable resultTable = await MainWindowViewModel.dataBase.ExecuteQueryAsync("SELECT " +
f_ + " FROM [dbo].[WaitDispenseDyestuff] WHERE DispenseMachine='" + m_ + "'");
data_.Add("Type", "10");
data_.Add("InfoMachine", Newtonsoft.Json.JsonConvert.SerializeObject(resultTable));
}
else if (t_ == "12")
{
DataTable resultTable = await MainWindowViewModel.dataBase.ExecuteQueryAsync("SELECT " +
f_ + " FROM [dbo].[ShelfInfo] ");
data_.Add("Type", "12");
data_.Add("InfoMachine", Newtonsoft.Json.JsonConvert.SerializeObject(resultTable));
}
else if (t_ == "20")
{
DataTable resultTable = await MainWindowViewModel.dataBase.ExecuteQueryAsync("SELECT " +
f_ + " FROM [dbo].[WaitChemical] WHERE DispenseMachine='" + m_ + "'");
data_.Add("Type", "20");
data_.Add("InfoMachine", Newtonsoft.Json.JsonConvert.SerializeObject(resultTable));
}
else
{
data_.Add("InfoMachine", "");
}
//格式化返回信息
ret = JsonSerializer.Serialize(data_);
}
if (Command == "InfoMachineHistory")//回复InfoMachineHistory请求的信息
{
string t_ = deserialized.GetValue("Type").ToString()!;
string? m_ = null, f_ = "*";
if (deserialized.TryGetValue("MachinName", out var MachinName) && MachinName != null) m_ = MachinName.ToString();
if (deserialized.TryGetValue("Field", out var Field) && Field != null) f_ = Field.ToString();
if (t_ == "80")
{
DataTable resultTable = await MainWindowViewModel.dataBase.ExecuteQueryAsync("SELECT " +
f_ + " FROM [dbo].[DyeSolutionHistory] WHERE DispenseStartTime >'" + DateTime.Now.AddDays(-3) +
"' and DispenseMachine='" + m_ + "'");
data_.Add("Type", "80");
data_.Add("InfoMachineHistory", Newtonsoft.Json.JsonConvert.SerializeObject(resultTable));
}
else if (t_ == "82")
{
DataTable resultTable = await MainWindowViewModel.dataBase.ExecuteQueryAsync("SELECT " +
f_ + " FROM [dbo].[inOutRecords] WHERE Createtime >'" + DateTime.Now.AddDays(-3) + "'");
data_.Add("Type", "82");
data_.Add("InfoMachineHistory", Newtonsoft.Json.JsonConvert.SerializeObject(resultTable));
}
else if (t_ == "90")
{
DataTable resultTable = await MainWindowViewModel.dataBase.ExecuteQueryAsync("SELECT " +
f_ + " FROM [dbo].[DyeSolutionHistory] WHERE DispenseStartTime >'" + DateTime.Now.AddDays(-3) +
"' and DispenseMachine='" + m_ + "'");
data_.Add("Type", "90");
data_.Add("InfoMachineHistory", Newtonsoft.Json.JsonConvert.SerializeObject(resultTable));
}
else
{
data_.Add("InfoMachineHistory", "");
}
//格式化返回信息
ret = JsonSerializer.Serialize(data_);
}
if (Command == "InfoMachinePipes")//回复Notification请求的信息
{
string? m_ = null, f_ = "*";
if (deserialized.TryGetValue("MachinName", out var MachinName) && MachinName != null) m_ = MachinName.ToString();
if (deserialized.TryGetValue("Field", out var Field) && Field != null) f_ = Field.ToString();
DataTable resultTable = await MainWindowViewModel.dataBase.ExecuteQueryAsync("SELECT " +
f_ + " FROM [dbo].[Pipes] WHERE Dispenser='" + m_ + "'");
data_.Add("InfoMachinePipes", Newtonsoft.Json.JsonConvert.SerializeObject(resultTable));
//格式化返回信息
ret = JsonSerializer.Serialize(data_);
}
if (Command == "SETUSER")//回复Notification请求的信息
{
MainWindowViewModel.Updata_Memory(MainWindowViewModel._userData,
"User='" + deserialized.GetValue("USER").ToString()! + "'",
deserialized.GetValue("VALUE").ToString(), deserialized.GetValue("KEY").ToString()!);
data_.Add("USER", deserialized.GetValue("USER").ToString()!);
data_.Add("VALUE", deserialized.GetValue("VALUE").ToString()!);
data_.Add("KEY", deserialized.GetValue("KEY").ToString()!);
data_.Add("SETUSER", "OK");
//格式化返回信息
ret = JsonSerializer.Serialize(data_);
}
return ret;
}
+143 -50
View File
@@ -1,12 +1,16 @@
using SunlightAggregationManager.ViewModel;
using SunlightAggregationManager.UserWindow;
using SunlightAggregationManager.ViewModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection.PortableExecutable;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using TouchSocket.Core;
using TouchSocket.Sockets;
using static SunlightAggregationManager.UserClass.AsyncTcpServer;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace SunlightAggregationManager.UserClass
{
@@ -91,10 +95,11 @@ namespace SunlightAggregationManager.UserClass
try
{
Person? deserializedPerson = JsonSerializer.Deserialize<Person>(mes);
Person? deserializedPerson = JsonSerializer.Deserialize<Person>(mes);
string password= AES.AesDecrypt(deserializedPerson?.Terminal!, deserializedPerson?.Password!);
var _user = MainWindowViewModel.Selet_Memory(MainWindowViewModel._userData, "State", "User='" +
deserializedPerson?.User + "' and Password ='" + deserializedPerson?.Password + "'");
deserializedPerson?.User + "' and Password ='" + password + "'");
if (_user != null)
{
string _dat = _user?.ToString() ?? "0";
@@ -103,19 +108,50 @@ namespace SunlightAggregationManager.UserClass
//行为
Dictionary<string, object> myDict = new Dictionary<string, object>();
//myDict.Add("LinkID", client.Id);
//AES解密
string dataAES = AES.AesDecrypt(deserializedPerson!.Terminal, deserializedPerson.Dat);
Console.WriteLine("[Log on]User[" + deserializedPerson?.User + "]COMMAND[" +
Regex.Replace(dataAES, @"\\u[0-9A-Fa-f]{4}", match =>
{ return Regex.Unescape(match.Value); }) + "]");
//记录
myDict.Add("LastLoginIP", deserializedPerson?.IP ?? client.IP);
myDict.Add("LastActionTime", DateTime.Now);
myDict.Add("Note", deserializedPerson?.Dat ?? "unknown");
MainWindowViewModel.Updata_Memory(MainWindowViewModel._userData, "User='" + deserializedPerson?.User + "'", myDict);
myDict.Add("Note", dataAES ?? "unknown");
Console.WriteLine("[Log on]User[" + deserializedPerson?.User + "]Note[" + (deserializedPerson?.Dat ?? "unknown") + "]");
CommandC(deserializedPerson?.Dat ?? "NOT", deserializedPerson!);
MainWindowViewModel.Updata_Memory(MainWindowViewModel._userData, "User='" +
deserializedPerson?.User + "'", myDict);
CommandC(dataAES ?? "NOT", deserializedPerson!);
}
else
{//停用账号关闭连接
client.SendAsync("Account Deactivated");
}
}
else if (password== MainWindowViewModel.SERRVERPASWORD && deserializedPerson?.User== MainWindowViewModel.SERVERUSER)
{
//行为
Dictionary<string, object> myDict = new Dictionary<string, object>();
//myDict.Add("LinkID", client.Id);
//AES解密
string dataAES = AES.AesDecrypt(deserializedPerson!.Terminal, deserializedPerson.Dat);
Console.WriteLine("[Log on]User[" + deserializedPerson?.User + "]COMMAND[" +
Regex.Replace(dataAES, @"\\u[0-9A-Fa-f]{4}", match =>
{ return Regex.Unescape(match.Value); }) + "]");
//记录
myDict.Add("LastLoginIP", deserializedPerson?.IP ?? client.IP);
myDict.Add("LastActionTime", DateTime.Now);
myDict.Add("Note", dataAES ?? "unknown");
MainWindowViewModel.Updata_Memory(MainWindowViewModel._userData, "User='" +
deserializedPerson?.User + "'", myDict);
CommandC(dataAES ?? "NOT", deserializedPerson!);
}
else
{ //无效账号关闭连接
client.SendAsync("Invalid Account");
@@ -135,31 +171,38 @@ namespace SunlightAggregationManager.UserClass
};
#endregion
try
// while (true)
{
await tcpClient.SetupAsync(new TouchSocketConfig()
.SetSingleStreamDataHandlingAdapter(() => new PeriodPackageAdapter())//以超时周期和包
.SetRemoteIPHost(ip)
.ConfigurePlugins(a =>
{
a.UseReconnection<TouchSocket.Sockets.TcpClient>(options =>
try
{
await tcpClient.SetupAsync(new TouchSocketConfig()
.SetSingleStreamDataHandlingAdapter(() => new PeriodPackageAdapter())//以超时周期和包
.SetRemoteIPHost(ip)
.ConfigurePlugins(a =>
{
options.PollingInterval = TimeSpan.FromSeconds(5);
});
})
.ConfigureContainer(a =>
{
}));
a.UseReconnection<TouchSocket.Sockets.TcpClient>(options =>
{
options.PollingInterval = TimeSpan.FromSeconds(5);
});
await tcpClient.ConnectAsync();//调用连接,当连接不成功时,会抛出异常。
})
.ConfigureContainer(a =>
{
}
catch (Exception ex)
{
LogGing.ERRDATA(ex);
Console.WriteLine("Tcp:" + ex.ToString());
}));
await tcpClient.ConnectAsync();//调用连接,当连接不成功时,会抛出异常。
// break;
}
catch (Exception ex)
{
// tcpClient.Dispose();//清
LogGing.ERRDATA(ex);
Console.WriteLine("Tcp:" + ex.ToString());
// await Task.Delay(TimeSpan.FromMinutes(1));
// Console.WriteLine("Tcp:重试连接...");
}
}
}
private static void TimerCallback(object? state)
@@ -187,26 +230,59 @@ namespace SunlightAggregationManager.UserClass
Dictionary<string, object> data_ = new Dictionary<string, object>();
var deserialized = JsonSerializer.Deserialize<Dictionary<string, object>>(dat)!;
if (deserialized.TryGetValue("Command", out var val) && val != null) Command = val.ToString()!;
if (Command == "Log")//回复请求的信息
if (Command == "SysCom")//回复指令的信息
{
ret = JsonSerializer.Serialize(data_);
}
else if (Command == "Log")//回复请求的信息
{
DataRow? _user = MainWindowViewModel.Selet_Row(MainWindowViewModel._userData, "User='" +
person?.User + "' and Password ='" + person?.Password + "'");
person?.User + "'");
data_.Add("Enterprise", _user?.Field<object>("Enterprise") ?? "");
data_.Add("Enterprise", MainWindowViewModel.Enterprise);
data_.Add("Department", _user?.Field<object>("Department") ?? "");
data_.Add("Groups", _user?.Field<object>("Groups") ?? "");
data_.Add("UserId", _user?.Field<object>("UserID") ?? "");
data_.Add("UserName", _user?.Field<object>("Name") ?? "");
ret = JsonSerializer.Serialize(data_);
}
else if (Command == "SysData")//特殊指令数据库查询
{
string com_ = deserialized.GetValue("Comm").ToString()!;
string da_ = deserialized.GetValue("Data").ToString()!;
if (com_ == "SYSDB")//本机sqlite数据库
{
DataTable resultTable = MainWindowViewModel.SQLiteHelpers.ExecuteDataSet(da_, null)?.Tables[0] ?? new DataTable();
data_.Add("DB", Newtonsoft.Json.JsonConvert.SerializeObject(resultTable));
data_.Add("Comm", "SYSDB");
data_.Add("Enterprise", MainWindowViewModel.Enterprise);
}
else if (com_ == "DBCDB")//系统dbc数据库
{
DataTable resultTable = await MainWindowViewModel.dataBase.ExecuteQueryAsync(da_);
data_.Add("DB", Newtonsoft.Json.JsonConvert.SerializeObject(resultTable));
data_.Add("Comm", "DBCDB");
data_.Add("Enterprise", MainWindowViewModel.Enterprise);
}
ret = JsonSerializer.Serialize(data_);
}
if (Command == "Info")//回复info请求的信息
else if (Command == "ChemicalStatistics")//回复请求的信息
{
data_.Add("ChemicalStatistics", Newtonsoft.Json.JsonConvert.SerializeObject(MainWindowViewModel.ChemicalStatistics));
ret = JsonSerializer.Serialize(data_);
}
else if (Command == "Info")//回复info请求的信息
{
var t = ToList(MainWindowViewModel._machines).ToJsonString();
//格式化返回信息
data_.Add("Info", t);
data_.Add("DyeMeasurementNumber", MainWindowViewModel.DyeMeasurementNumber.ToString());
data_.Add("ChemicalNumber", MainWindowViewModel.ChemicalNumber.ToString());
data_.Add("PowderNumber", MainWindowViewModel.PowderNumber.ToString());
data_.Add("DyeDissolveNumber", MainWindowViewModel.DyeDissolveNumber.ToString());
ret = JsonSerializer.Serialize(data_);
}
if (Command == "Query")//回复Query请求的信息
else if (Command == "Query")//回复Query请求的信息
{
string s_ = deserialized.GetValue("StartTime").ToString()!;
string e_ = deserialized.GetValue("EndTime").ToString()!;
@@ -218,7 +294,7 @@ namespace SunlightAggregationManager.UserClass
data_.Add("Query", Newtonsoft.Json.JsonConvert.SerializeObject(resultTable));
ret = JsonSerializer.Serialize(data_);
}
if (Command == "QueryDyelot")//回复QueryDyelot请求的信息
else if (Command == "QueryDyelot")//回复QueryDyelot请求的信息
{
string d_ = deserialized.GetValue("DyelotName").ToString()!;
string f_ = deserialized.GetValue("Field").ToString()!;
@@ -229,7 +305,7 @@ namespace SunlightAggregationManager.UserClass
data_.Add("Query", Newtonsoft.Json.JsonConvert.SerializeObject(resultTable));
ret = JsonSerializer.Serialize(data_);
}
if (Command == "QueryDetail")//回复QueryDetail请求的信息
else if (Command == "QueryDetail")//回复QueryDetail请求的信息
{
string d_ = deserialized.GetValue("Dyelot").ToString()!;
string r_ = deserialized.GetValue("ReDye").ToString()!;
@@ -241,24 +317,26 @@ namespace SunlightAggregationManager.UserClass
data_.Add("QueryDetail", Newtonsoft.Json.JsonConvert.SerializeObject(resultTable));
ret = JsonSerializer.Serialize(data_);
}
if (Command == "Notification")//回复Notification请求的信息
else if (Command == "Notification")//回复Notification请求的信息
{
string s_ = deserialized.GetValue("StartTime").ToString()!;
string s_; try { s_ = deserialized.GetValue("StartTime").ToString()!; } catch(Exception) { s_ = "0"; }
string e_ = deserialized.GetValue("EndTime").ToString()!;
var groups = MainWindowViewModel.Selet_Memory(MainWindowViewModel._userData,
"Groups", "User='" + person?.User + "'");
var department = MainWindowViewModel.Selet_Memory(MainWindowViewModel._userData,
"Department", "User='" + person?.User + "'");
DataTable resultTable = MainWindowViewModel.SQLiteHelpers.ExecuteDataSet("" +
"select * from Notification WHERE Groups='" + groups + "' and Time>'" +
s_ + "' and Time<'" + e_ + "'", null)?.Tables[0] ?? new DataTable();
DataTable resultTable = MainWindowViewModel.SQLiteHelpers.ExecuteDataSet("" +
"select * from Notification WHERE Groups='" + groups + "'and Department='" +
department + "' and Id>'" + s_ + "'", null)?.Tables[0] ?? new DataTable();
if(resultTable.Rows.Count==0) resultTable.Rows.Add();
//格式化返回信息
data_.Add("Notification", Newtonsoft.Json.JsonConvert.SerializeObject(resultTable));
ret = JsonSerializer.Serialize(data_);
}
if (Command == "InfoMachine")//回复InfoMachine请求的信息
else if (Command == "InfoMachine")//回复InfoMachine请求的信息
{
string t_ = deserialized.GetValue("Type").ToString()!;
string? m_ =null, f_ = "*";
@@ -295,7 +373,7 @@ namespace SunlightAggregationManager.UserClass
//格式化返回信息
ret = JsonSerializer.Serialize(data_);
}
if (Command == "InfoMachineHistory")//回复InfoMachineHistory请求的信息
else if (Command == "InfoMachineHistory")//回复InfoMachineHistory请求的信息
{
string t_ = deserialized.GetValue("Type").ToString()!;
string? m_ = null, f_ = "*";
@@ -309,32 +387,32 @@ namespace SunlightAggregationManager.UserClass
f_ + " FROM [dbo].[DyeSolutionHistory] WHERE DispenseStartTime >'" + DateTime.Now.AddDays(-3)+
"' and DispenseMachine='" + m_ + "'");
data_.Add("Type", "80");
data_.Add("InfoMachine", Newtonsoft.Json.JsonConvert.SerializeObject(resultTable));
data_.Add("InfoMachineHistory", Newtonsoft.Json.JsonConvert.SerializeObject(resultTable));
}
else if (t_ == "82")
{
DataTable resultTable = await MainWindowViewModel.dataBase.ExecuteQueryAsync("SELECT " +
f_ + " FROM [dbo].[inOutRecords] WHERE Createtime >'" + DateTime.Now.AddDays(-3)+"'");
data_.Add("Type", "82");
data_.Add("InfoMachine", Newtonsoft.Json.JsonConvert.SerializeObject(resultTable));
data_.Add("InfoMachineHistory", Newtonsoft.Json.JsonConvert.SerializeObject(resultTable));
}
else if (t_ == "90")
{
DataTable resultTable = await MainWindowViewModel.dataBase.ExecuteQueryAsync("SELECT " +
f_ + " FROM [dbo].[DyeSolutionHistory] WHERE DispenseStartTime >'" + DateTime.Now.AddDays(-3) +
"' and DispenseMachine='" + m_ + "'");
data_.Add("Type", "20");
data_.Add("InfoMachine", Newtonsoft.Json.JsonConvert.SerializeObject(resultTable));
data_.Add("Type", "90");
data_.Add("InfoMachineHistory", Newtonsoft.Json.JsonConvert.SerializeObject(resultTable));
}
else
{
data_.Add("InfoMachine", "");
data_.Add("InfoMachineHistory", "");
}
//格式化返回信息
ret = JsonSerializer.Serialize(data_);
}
if (Command == "InfoMachinePipes")//回复Notification请求的信息
else if (Command == "InfoMachinePipes")//回复Notification请求的信息
{
string? m_ = null, f_ = "*";
@@ -348,9 +426,24 @@ namespace SunlightAggregationManager.UserClass
//格式化返回信息
ret = JsonSerializer.Serialize(data_);
}
else if (Command == "SETUSER")//回复请求的信息
{
MainWindowViewModel.Updata_Memory(MainWindowViewModel._userData,
"User='" + deserialized.GetValue("USER").ToString()! + "'" ,
deserialized.GetValue("VALUE").ToString(), deserialized.GetValue("KEY").ToString()!);
data_.Add("USER", deserialized.GetValue("USER").ToString()!);
data_.Add("VALUE", deserialized.GetValue("VALUE").ToString()!);
data_.Add("KEY", deserialized.GetValue("KEY").ToString()!);
data_.Add("SETUSER", "OK");
//格式化返回信息
ret = JsonSerializer.Serialize(data_);
}
//加密回传
/*Console.WriteLine("[Log on]User[" + person?.User + "]REPLY[" +
Regex.Replace(ret, @"\\u[0-9A-Fa-f]{4}", match =>
{ return Regex.Unescape(match.Value); }) + "]");*/
person!.Dat = ret.ToString();
person!.Dat =AES.AesEncipher( person.Terminal, ret);
var jsdat = JsonSerializer.Serialize(person);
await tcpClient.SendAsync(jsdat);
}
+202 -66
View File
@@ -2,6 +2,7 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Net.Sockets;
using System.Security.Cryptography.Pkcs;
using System.Text;
using System.Text.Json;
@@ -174,77 +175,212 @@ namespace SunlightAggregationManager.UserClass
Console.WriteLine("TCP Port:"+ port2.ToString());
Console.WriteLine("TCP SERVER:START");
}
public static async void Command(string dat,string id , Person person)//
public static async void Command(string dat, string id, Person person)//
{
string Command="", ret ="";
Dictionary<string, object> data_ = new Dictionary<string, object>();
var deserialized = JsonSerializer.Deserialize<Dictionary<string, object>>(dat)!;
if (deserialized.TryGetValue("Command", out var val) && val != null) Command = val.ToString()!;
if (Command == "Info")//回复info请求的信息
try
{
var t = ToList(MainWindowViewModel._machines).ToJsonString();
//格式化返回信息
data_.Add("Info", t);
ret = JsonSerializer.Serialize(data_);
string Command = "", ret = "";
Dictionary<string, object> data_ = new Dictionary<string, object>();
var deserialized = JsonSerializer.Deserialize<Dictionary<string, object>>(dat)!;
if (deserialized.TryGetValue("Command", out var val) && val != null) Command = val.ToString()!;
if (Command == "Log")//回复请求的信息
{
DataRow? _user = MainWindowViewModel.Selet_Row(MainWindowViewModel._userData, "User='" +
person?.User + "' and Password ='" + person?.Password + "'");
data_.Add("Enterprise", _user?.Field<object>("Enterprise") ?? "");
data_.Add("Department", _user?.Field<object>("Department") ?? "");
data_.Add("Groups", _user?.Field<object>("Groups") ?? "");
data_.Add("UserId", _user?.Field<object>("UserID") ?? "");
data_.Add("UserName", _user?.Field<object>("Name") ?? "");
ret = JsonSerializer.Serialize(data_);
}
if (Command == "SysData")//回复请求的信息
{
ret = JsonSerializer.Serialize(data_);
}
if (Command == "ChemicalStatistics")//回复请求的信息
{
data_.Add("ChemicalStatistics", Newtonsoft.Json.JsonConvert.SerializeObject(MainWindowViewModel.ChemicalStatistics));
ret = JsonSerializer.Serialize(data_);
}
if (Command == "Info")//回复info请求的信息
{
var t = ToList(MainWindowViewModel._machines).ToJsonString();
//格式化返回信息
data_.Add("Info", t);
data_.Add("DyeMeasurementNumber", MainWindowViewModel.DyeMeasurementNumber.ToString());
data_.Add("ChemicalNumber", MainWindowViewModel.ChemicalNumber.ToString());
data_.Add("PowderNumber", MainWindowViewModel.PowderNumber.ToString());
data_.Add("DyeDissolveNumber", MainWindowViewModel.DyeDissolveNumber.ToString());
ret = JsonSerializer.Serialize(data_);
}
if (Command == "Query")//回复Query请求的信息
{
string s_ = deserialized.GetValue("StartTime").ToString()!;
string e_ = deserialized.GetValue("EndTime").ToString()!;
string f_ = deserialized.GetValue("Field").ToString()!;
DataTable resultTable = await MainWindowViewModel.dataBase.ExecuteQueryAsync("SELECT " +
f_ + " FROM [dbo].[Dyelots] " + "WHERE CreationTime>'" + s_ + "'and CreationTime<'" + e_ + "'");
//格式化返回信息
data_.Add("Query", Newtonsoft.Json.JsonConvert.SerializeObject(resultTable));
ret = JsonSerializer.Serialize(data_);
}
if (Command == "QueryDyelot")//回复QueryDyelot请求的信息
{
string d_ = deserialized.GetValue("DyelotName").ToString()!;
string f_ = deserialized.GetValue("Field").ToString()!;
DataTable resultTable = await MainWindowViewModel.dataBase.ExecuteQueryAsync("SELECT " +
f_ + " FROM [dbo].[Dyelots] " + "WHERE Dyelot LIKE '" + d_ + "%'");
//格式化返回信息
data_.Add("Query", Newtonsoft.Json.JsonConvert.SerializeObject(resultTable));
ret = JsonSerializer.Serialize(data_);
}
if (Command == "QueryDetail")//回复QueryDetail请求的信息
{
string d_ = deserialized.GetValue("Dyelot").ToString()!;
string r_ = deserialized.GetValue("ReDye").ToString()!;
string f_ = deserialized.GetValue("Field").ToString()!;
DataTable resultTable = await MainWindowViewModel.dataBase.ExecuteQueryAsync("SELECT " +
f_ + " FROM [dbo].[DyelotsBulkedRecipe] " + "WHERE Dyelot='" + d_ + "'and ReDye='" + r_ + "'");
//格式化返回信息
data_.Add("QueryDetail", Newtonsoft.Json.JsonConvert.SerializeObject(resultTable));
ret = JsonSerializer.Serialize(data_);
}
if (Command == "Notification")//回复Notification请求的信息
{
string s_ = deserialized.GetValue("StartTime").ToString()!;
string e_ = deserialized.GetValue("EndTime").ToString()!;
var groups = MainWindowViewModel.Selet_Memory(MainWindowViewModel._userData,
"Groups", "User='" + person?.User + "'");
DataTable resultTable = MainWindowViewModel.SQLiteHelpers.ExecuteDataSet("" +
"select * from Notification WHERE Groups='" + groups + "' and Id>'" +
s_ + "'", null)?.Tables[0] ?? new DataTable();
if (resultTable.Rows.Count == 0) resultTable.Rows.Add();
//格式化返回信息
data_.Add("Notification", Newtonsoft.Json.JsonConvert.SerializeObject(resultTable));
ret = JsonSerializer.Serialize(data_);
}
if (Command == "InfoMachine")//回复InfoMachine请求的信息
{
string t_ = deserialized.GetValue("Type").ToString()!;
string? m_ = null, f_ = "*";
if (deserialized.TryGetValue("MachinName", out var MachinName) && MachinName != null) m_ = MachinName.ToString();
if (deserialized.TryGetValue("Field", out var Field) && Field != null) f_ = Field.ToString();
if (t_ == "10")
{
DataTable resultTable = await MainWindowViewModel.dataBase.ExecuteQueryAsync("SELECT " +
f_ + " FROM [dbo].[WaitDispenseDyestuff] WHERE DispenseMachine='" + m_ + "'");
data_.Add("Type", "10");
data_.Add("InfoMachine", Newtonsoft.Json.JsonConvert.SerializeObject(resultTable));
}
else if (t_ == "12")
{
DataTable resultTable = await MainWindowViewModel.dataBase.ExecuteQueryAsync("SELECT " +
f_ + " FROM [dbo].[ShelfInfo] ");
data_.Add("Type", "12");
data_.Add("InfoMachine", Newtonsoft.Json.JsonConvert.SerializeObject(resultTable));
}
else if (t_ == "20")
{
DataTable resultTable = await MainWindowViewModel.dataBase.ExecuteQueryAsync("SELECT " +
f_ + " FROM [dbo].[WaitChemical] WHERE DispenseMachine='" + m_ + "'");
data_.Add("Type", "20");
data_.Add("InfoMachine", Newtonsoft.Json.JsonConvert.SerializeObject(resultTable));
}
else
{
data_.Add("InfoMachine", "");
}
//格式化返回信息
ret = JsonSerializer.Serialize(data_);
}
if (Command == "InfoMachineHistory")//回复InfoMachineHistory请求的信息
{
string t_ = deserialized.GetValue("Type").ToString()!;
string? m_ = null, f_ = "*";
if (deserialized.TryGetValue("MachinName", out var MachinName) && MachinName != null) m_ = MachinName.ToString();
if (deserialized.TryGetValue("Field", out var Field) && Field != null) f_ = Field.ToString();
if (t_ == "80")
{
DataTable resultTable = await MainWindowViewModel.dataBase.ExecuteQueryAsync("SELECT " +
f_ + " FROM [dbo].[DyeSolutionHistory] WHERE DispenseStartTime >'" + DateTime.Now.AddDays(-3) +
"' and DispenseMachine='" + m_ + "'");
data_.Add("Type", "80");
data_.Add("InfoMachineHistory", Newtonsoft.Json.JsonConvert.SerializeObject(resultTable));
}
else if (t_ == "82")
{
DataTable resultTable = await MainWindowViewModel.dataBase.ExecuteQueryAsync("SELECT " +
f_ + " FROM [dbo].[inOutRecords] WHERE Createtime >'" + DateTime.Now.AddDays(-3) + "'");
data_.Add("Type", "82");
data_.Add("InfoMachineHistory", Newtonsoft.Json.JsonConvert.SerializeObject(resultTable));
}
else if (t_ == "90")
{
DataTable resultTable = await MainWindowViewModel.dataBase.ExecuteQueryAsync("SELECT " +
f_ + " FROM [dbo].[DyeSolutionHistory] WHERE DispenseStartTime >'" + DateTime.Now.AddDays(-3) +
"' and DispenseMachine='" + m_ + "'");
data_.Add("Type", "90");
data_.Add("InfoMachineHistory", Newtonsoft.Json.JsonConvert.SerializeObject(resultTable));
}
else
{
data_.Add("InfoMachineHistory", "");
}
//格式化返回信息
ret = JsonSerializer.Serialize(data_);
}
if (Command == "InfoMachinePipes")//回复Notification请求的信息
{
string? m_ = null, f_ = "*";
if (deserialized.TryGetValue("MachinName", out var MachinName) && MachinName != null) m_ = MachinName.ToString();
if (deserialized.TryGetValue("Field", out var Field) && Field != null) f_ = Field.ToString();
DataTable resultTable = await MainWindowViewModel.dataBase.ExecuteQueryAsync("SELECT " +
f_ + " FROM [dbo].[Pipes] WHERE Dispenser='" + m_ + "'");
data_.Add("InfoMachinePipes", Newtonsoft.Json.JsonConvert.SerializeObject(resultTable));
//格式化返回信息
ret = JsonSerializer.Serialize(data_);
}
if (Command == "SETUSER")//回复Notification请求的信息
{
MainWindowViewModel.Updata_Memory(MainWindowViewModel._userData,
"User='" + deserialized.GetValue("USER").ToString()! + "'",
deserialized.GetValue("VALUE").ToString(), deserialized.GetValue("KEY").ToString()!);
data_.Add("USER", deserialized.GetValue("USER").ToString()!);
data_.Add("VALUE", deserialized.GetValue("VALUE").ToString()!);
data_.Add("KEY", deserialized.GetValue("KEY").ToString()!);
data_.Add("SETUSER", "OK");
//格式化返回信息
ret = JsonSerializer.Serialize(data_);
}
person!.Dat = ret.ToString();
var jsdat = JsonSerializer.Serialize(person);
await service.SendAsync(id, jsdat);
}
if (Command == "Query")//回复Query请求的信息
catch (Exception ex)
{
string s_ = deserialized.GetValue("StartTime").ToString()!;
string e_ = deserialized.GetValue("EndTime").ToString()!;
string f_ = deserialized.GetValue("Field").ToString()!;
DataTable resultTable = await MainWindowViewModel.dataBase.ExecuteQueryAsync("SELECT "+
f_+" FROM [dbo].[Dyelots] " + "WHERE CreationTime>'"+s_+"'and CreationTime<'"+e_+"'");
//格式化返回信息
data_.Add("Query", Newtonsoft.Json.JsonConvert.SerializeObject(resultTable));
ret = JsonSerializer.Serialize(data_);
LogGing.ERRDATA(ex);
Console.WriteLine(ex.ToString());
}
if (Command == "QueryDyelot")//回复QueryDyelot请求的信息
{
string d_ = deserialized.GetValue("DyelotName").ToString()!;
string f_ = deserialized.GetValue("Field").ToString()!;
DataTable resultTable = await MainWindowViewModel.dataBase.ExecuteQueryAsync("SELECT " +
f_ + " FROM [dbo].[Dyelots] " + "WHERE Dyelot LIKE '" + d_ + "%'");
//格式化返回信息
data_.Add("Query", Newtonsoft.Json.JsonConvert.SerializeObject(resultTable));
ret = JsonSerializer.Serialize(data_);
}
if (Command == "QueryDetail")//回复info请求的信息
{
string d_ = deserialized.GetValue("Dyelot").ToString()!;
string r_ = deserialized.GetValue("ReDye").ToString()!;
string f_ = deserialized.GetValue("Field").ToString()!;
DataTable resultTable = await MainWindowViewModel.dataBase.ExecuteQueryAsync("SELECT " +
f_ + " FROM [dbo].[DyelotsBulkedRecipe] " + "WHERE Dyelot='" + d_ + "'and ReDye='" + r_ + "'");
//格式化返回信息
data_.Add("QueryDetail", Newtonsoft.Json.JsonConvert.SerializeObject(resultTable));
ret = JsonSerializer.Serialize(data_);
}
if (Command == "Notification")//回复Notification请求的信息
{
string s_ = deserialized.GetValue("StartTime").ToString()!;
string e_ = deserialized.GetValue("EndTime").ToString()!;
var groups = MainWindowViewModel.Selet_Memory(MainWindowViewModel._userData,
"Groups", "User='" + person?.User + "'");
var resultTable = MainWindowViewModel.SQLiteHelpers.ExecuteDataSet("" +
"select * from Notification WHERE Groups='" + groups + "' and Time>'" +
s_ + "' and Time<'" + e_ + "'", null)?.Tables[0] ?? new DataTable();
//格式化返回信息
data_.Add("Notification", Newtonsoft.Json.JsonConvert.SerializeObject(resultTable));
ret = JsonSerializer.Serialize(data_);
}
person.Dat=ret.ToString();
var jsdat = JsonSerializer.Serialize(person);
await service.SendAsync(id, jsdat);
}
public static List<Dictionary<string, object?>>? ToList(DataTable table)//datatable转list
+47 -4
View File
@@ -64,7 +64,7 @@ namespace SunlightAggregationManager.UserClass
catch (Exception ex)
{
LogGing.ERRDATA(ex);
Console.WriteLine("DataBase Link timeout\n"+ex.ToString());
Console.WriteLine("DataBase Link timeout\n"+ ex.Message.ToString());
// 失败处理
return; // 直接返回,不执行后续代码
}
@@ -111,14 +111,57 @@ namespace SunlightAggregationManager.UserClass
catch (Exception ex)
{
LogGing.ERRDATA(ex);
Console.WriteLine("DataBase Query failed\n" + ex.ToString());
// 将异常抛出给调用方,或者返回一个空的 DataTable
throw;
Console.WriteLine("DataBase Query failed\n" + ex.Message.ToString());
}
return dataTable;
}
public async Task<int> ExecuteQueryAsyncCount(string sql)
{
// 创建一个空的 DataTable 用于存放查询结果
DataTable dataTable = new DataTable();
// 数据库连接字符串构建逻辑
var builder = new SqlConnectionStringBuilder
{
DataSource = DB_IP,
InitialCatalog = DB_NAME,
IntegratedSecurity = DB_TYPE == "Windows Authentication",
TrustServerCertificate = true,
ConnectTimeout = 5
};
if (!builder.IntegratedSecurity)
{
builder.UserID = DB_ID;
builder.Password = DB_PASSWORD;
}
try
{
using var conn = new SqlConnection(builder.ConnectionString);
await conn.OpenAsync(); // 使用异步方式打开连接<websource>source_group_web_2</websource>
using (var cmd = new SqlCommand(sql, conn))
{
// 执行查询并将结果直接加载到 DataTable 中
using (var reader = await cmd.ExecuteReaderAsync())
{
dataTable.Load(reader);
}
}
}
catch (Exception ex)
{
LogGing.ERRDATA(ex);
Console.WriteLine("DataBase Query failed\n" + ex.Message.ToString());
}
return dataTable.Rows.Count;
}
public void Database(string dat)
{
+107 -59
View File
@@ -1,85 +1,133 @@
using System;
using SunlightAggregationManager.View;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace SunlightAggregationManager.UserClass
{
public class LogGing
{
public class LOGinf
{
public required string Logpath { get; set; }
public required string LogPath { get; set; }
public required string Log_time { get; set; }
public required object DAT { get; set; }
}
static Queue<LOGinf> LogGingQueue = new Queue<LOGinf>();
static Queue<LOGinf> ERRQueue = new Queue<LOGinf>();
static Queue<LOGinf> ExchangeQueue = new Queue<LOGinf>();
public static void LogGingDATA(string dat)
{
string logpath = System.Environment.CurrentDirectory + "\\Log";//日志文件目录
string logPath = "" + System.Environment.CurrentDirectory + "\\Log\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";//日志文件
string Log_time = "[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "]:";
LOGinf ginf = new LOGinf
{
Logpath = System.Environment.CurrentDirectory + "\\Log",//日志文件目录
LogPath = "" + System.Environment.CurrentDirectory + "\\Log\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt",//日志文件
Log_time = "[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "]:",
DAT = dat
};
LogGingQueue.Enqueue(ginf);
if (Directory.Exists(logpath))//检查日志路径
if(LogGingQueue.Count==1) LogGingQueueW();
}
public static async void LogGingQueueW()
{
while (true)
{
if (!File.Exists(logPath))//检查日志文件并写入启动日志
try
{
FileStream fs = new FileStream(logPath, FileMode.CreateNew, FileAccess.Write);//创建写入文件
StreamWriter wr = new StreamWriter(fs);//创建文件
wr.WriteLine(Log_time + dat);
wr.Close();
}
else
{
try
LOGinf inf = LogGingQueue.Dequeue();
if (Directory.Exists(inf.Logpath))//检查日志路径
{
FileStream fs = new FileStream(logPath, FileMode.Append, FileAccess.Write);
StreamWriter wr = new StreamWriter(fs);//创建文件
wr.WriteLine(Log_time + dat);
wr.Close();
if (!File.Exists(inf.LogPath))//检查日志文件并写入启动日志
{
FileStream fs = new FileStream(inf.LogPath, FileMode.CreateNew, FileAccess.Write);//创建写入文件
StreamWriter wr = new StreamWriter(fs);//创建文件
wr.WriteLine(inf.Log_time + inf.DAT);
wr.Close();
}
else
{
FileStream fs = new FileStream(inf.LogPath, FileMode.Append, FileAccess.Write);
StreamWriter wr = new StreamWriter(fs);//创建文件
wr.WriteLine(inf.Log_time + inf.DAT);
wr.Close();
}
}
else
{
DirectoryInfo directoryInfo = new DirectoryInfo(inf.Logpath);
directoryInfo.Create();//创建日志路径
}
catch { }
}
}
else
{
DirectoryInfo directoryInfo = new DirectoryInfo(logpath);
directoryInfo.Create();//创建日志路径
catch (Exception ) { }
if (LogGingQueue.Count == 0) break;
}
}
public static void ERRDATA(System.Exception dat)
{
string Log_time = DateTime.Now.ToString("yyyy-MM-dd");
string logpath = System.Environment.CurrentDirectory + "\\ERR";//日志文件目录
// string logPathtxt = "" + System.Environment.CurrentDirectory + "\\Log\\"+ Log_time + "Log.txt";//日志文件
// System.IO.DirectoryInfo log = new System.IO.DirectoryInfo();//生成日志文件目录
string log_path = logpath + "\\ERR" + Log_time + ".txt";
string Log_timehms = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
if (Directory.Exists(logpath))//检查日志路径
{
LOGinf ginf = new LOGinf
{
if (!File.Exists(log_path))//检查文件并写入
{
// FileStream fs = new FileStream(log_path, FileMode.CreateNew, FileAccess.Write);//创建文件
// StreamWriter wr = new StreamWriter(fs);//创建文件
// wr.Close();
FileStream fil = new FileStream(log_path, FileMode.CreateNew, FileAccess.Write);//创建写入文件
StreamWriter wfil = new StreamWriter(fil);//创建文件
wfil.WriteLine("[" + Log_timehms + "];[Error] ||" + Environment.NewLine.ToString());
wfil.WriteLine("[" + Log_timehms + "];[Error source] ||" + dat.Source.ToString() + Environment.NewLine.ToString());
wfil.WriteLine("[" + Log_timehms + "];[Error message] ||" + dat.Message.ToString() + Environment.NewLine.ToString());
wfil.WriteLine("[" + Log_timehms + "];[Error area] ||" + dat.StackTrace.ToString());
wfil.Close();
}
else
{
FileStream fs = new FileStream(log_path, FileMode.Append, FileAccess.Write);//创建写入文件
StreamWriter wr = new StreamWriter(fs);//创建文件
wr.WriteLine("[" + Log_timehms + "];[Error] ||" + Environment.NewLine.ToString());
wr.WriteLine("[" + Log_timehms + "];[Error source] ||" + dat.ToString() + Environment.NewLine.ToString());
wr.WriteLine("[" + Log_timehms + "];[Error message] ||" + dat.Message.ToString() + Environment.NewLine.ToString());
wr.WriteLine("[" + Log_timehms + "];[Error area] ||" + dat.ToString());
wr.Close();
}
}
else
Logpath = System.Environment.CurrentDirectory + "\\ERR",//日志文件目录
LogPath = "" + System.Environment.CurrentDirectory + "\\ERR\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt",//日志文件
Log_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
DAT = dat
};
ERRQueue.Enqueue(ginf);
if (ERRQueue.Count == 1) ERRQueueW();
}
public static async void ERRQueueW()
{
while (true)
{
DirectoryInfo directoryInfo = new DirectoryInfo(logpath);
directoryInfo.Create();
try
{
LOGinf inf = ERRQueue.Dequeue();
Exception dat = (Exception)inf.DAT;
if (Directory.Exists(inf.Logpath))//检查日志路径
{
if (!File.Exists(inf.LogPath))//检查文件并写入
{
// FileStream fs = new FileStream(log_path, FileMode.CreateNew, FileAccess.Write);//创建文件
// StreamWriter wr = new StreamWriter(fs);//创建文件
// wr.Close();
FileStream fil = new FileStream(inf.LogPath, FileMode.CreateNew, FileAccess.Write);//创建写入文件
StreamWriter wfil = new StreamWriter(fil);//创建文件
wfil.WriteLine("[" + inf.Log_time + "];[Error] ||" + Environment.NewLine.ToString());
wfil.WriteLine("[" + inf.Log_time + "];[Error source] ||" + dat.Source.ToString() + Environment.NewLine.ToString());
wfil.WriteLine("[" + inf.Log_time + "];[Error message] ||" + dat.Message.ToString() + Environment.NewLine.ToString());
wfil.WriteLine("[" + inf.Log_time + "];[Error area] ||" + dat.StackTrace.ToString());
wfil.Close();
}
else
{
FileStream fs = new FileStream(inf.LogPath, FileMode.Append, FileAccess.Write);//创建写入文件
StreamWriter wr = new StreamWriter(fs);//创建文件
wr.WriteLine("[" + inf.Log_time + "];[Error] ||" + Environment.NewLine.ToString());
wr.WriteLine("[" + inf.Log_time + "];[Error source] ||" + dat.ToString() + Environment.NewLine.ToString());
wr.WriteLine("[" + inf.Log_time + "];[Error message] ||" + dat.Message.ToString() + Environment.NewLine.ToString());
wr.WriteLine("[" + inf.Log_time + "];[Error area] ||" + dat.ToString());
wr.Close();
}
}
else
{
DirectoryInfo directoryInfo = new DirectoryInfo(inf.Logpath);
directoryInfo.Create();
}
}
catch (Exception) { }
if (ERRQueue.Count == 0) break;
}
}
public static void ExchangeDATA(string dat)
{
string Log_time = DateTime.Now.ToString("yyyy-MM-dd");
+55 -42
View File
@@ -15,62 +15,75 @@ namespace SunlightAggregationManager.UserClass
public static void AllowPort(int port, string protocol)
{
DelPort(port, protocol);
//创建一个INetFwRule对象
Type type = Type.GetTypeFromProgID("HNetCfg.FwRule") ?? throw new
InvalidOperationException("Failed to retrieve HNetCfg.FwRule type. Ensure the COM component is registered.");
INetFwRule? rule = (INetFwRule?)Activator.CreateInstance(type);
//设置规则的属性
rule?.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW; //允许连接
rule?.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN; //入站规则
rule?.Enabled = true; //启用规则
rule?.InterfaceTypes = "All"; //适用于所有网络接口
rule?.Name = GetName(port, protocol); //规则名称
if (protocol.ToLower() == "tcp")
try
{
rule?.Protocol = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP; //TCP协议
DelPort(port, protocol);
//创建一个INetFwRule对象
Type type = Type.GetTypeFromProgID("HNetCfg.FwRule") ?? throw new
InvalidOperationException("Failed to retrieve HNetCfg.FwRule type. Ensure the COM component is registered.");
INetFwRule? rule = (INetFwRule?)Activator.CreateInstance(type);
//设置规则的属性
rule?.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW; //允许连接
rule?.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN; //入站规则
rule?.Enabled = true; //启用规则
rule?.InterfaceTypes = "All"; //适用于所有网络接口
rule?.Name = GetName(port, protocol); //规则名称
if (protocol.ToLower() == "tcp")
{
rule?.Protocol = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP; //TCP协议
}
else
{
rule?.Protocol = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_UDP; //UDP协议
}
rule?.LocalPorts = "" + port; //本地端口号
//获取FirewallPolicy对象
Type policyType = Type.GetTypeFromProgID("HNetCfg.FwPolicy2") ?? throw new
InvalidOperationException("Failed to retrieve HNetCfg.FwRule type. Ensure the COM component is registered.");
INetFwPolicy2? policy = (INetFwPolicy2?)Activator.CreateInstance(policyType);
//将规则添加到防火墙策略中
policy?.Rules.Add(rule);
Console.WriteLine("Add firewall port:" + port);
}
else
catch (Exception ex)
{
rule?.Protocol = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_UDP; //UDP协议
Console.WriteLine(ex.ToString());
}
rule?.LocalPorts = "" + port; //本地端口号
//获取FirewallPolicy对象
Type policyType = Type.GetTypeFromProgID("HNetCfg.FwPolicy2") ?? throw new
InvalidOperationException("Failed to retrieve HNetCfg.FwRule type. Ensure the COM component is registered.");
INetFwPolicy2? policy = (INetFwPolicy2?)Activator.CreateInstance(policyType);
//将规则添加到防火墙策略中
policy?.Rules.Add(rule);
Console.WriteLine("Add firewall port:"+port);
}
public static void DelPort(int port, string protocol)
{
//获取FirewallPolicy对象
Type policyType = Type.GetTypeFromProgID("HNetCfg.FwPolicy2") ?? throw new
InvalidOperationException("Failed to retrieve HNetCfg.FwRule type. Ensure the COM component is registered.");
INetFwPolicy2? policy = (INetFwPolicy2?)Activator.CreateInstance(policyType);
//获取现有的规则集合
INetFwRules? rules = policy?.Rules;
if (rules != null)
try
{
//查找名称的规则并删除它
foreach (INetFwRule rule in rules)
//获取FirewallPolicy对象
Type policyType = Type.GetTypeFromProgID("HNetCfg.FwPolicy2") ?? throw new
InvalidOperationException("Failed to retrieve HNetCfg.FwRule type. Ensure the COM component is registered.");
INetFwPolicy2? policy = (INetFwPolicy2?)Activator.CreateInstance(policyType);
//获取现有的规则集合
INetFwRules? rules = policy?.Rules;
if (rules != null)
{
if (rule.Name == GetName(port, protocol))
//查找名称的规则并删除它
foreach (INetFwRule rule in rules)
{
rules.Remove(rule.Name);
//Console.WriteLine(@"Firewall rule deleted successfully.");
break;
if (rule.Name == GetName(port, protocol))
{
rules.Remove(rule.Name);
//Console.WriteLine(@"Firewall rule deleted successfully.");
break;
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}
+34 -12
View File
@@ -23,26 +23,47 @@
<GridSplitter Grid.Row="1" Height="5" HorizontalAlignment="Stretch" Background="#FFCECECE"/>
<Grid Grid.Row="0">
<Grid.ColumnDefinitions>
<ColumnDefinition MinWidth="200" MaxWidth="500"/>
<ColumnDefinition Width="500"/>
<ColumnDefinition Width="5"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<GridSplitter Grid.Column="1" Width="5" HorizontalAlignment="Stretch" Background="#FFCECECE"/>
<Grid Grid.Column="0">
<!--用户-->
<TextBox x:Name="_User" Height="30" Margin="105,10,10,100" VerticalAlignment="Top" FontSize="16" MaxLines="1" InputMethod.IsInputMethodEnabled="False" />
<TextBox x:Name="_Name" Height="30" Margin="105,10,10,100" VerticalAlignment="Top" FontSize="16" MaxLines="1"/>
<TextBlock HorizontalAlignment="Left" Height="30" Margin="15,10,0,100" TextWrapping="Wrap"
Text="{x:Static lang:ResourceLanguage.user}" VerticalAlignment="Top" Width="85" FontSize="20"/>
<!--组-->
<ComboBox x:Name="GROUP" Height="30" Margin="105,190,10,100" VerticalAlignment="Top" FontSize="16" IsReadOnly="True">
<ComboBoxItem Content="CHIEF"></ComboBoxItem>
<ComboBoxItem Content="ENGINEER"></ComboBoxItem>
<ComboBoxItem Content="POWERUSER"></ComboBoxItem>
<ComboBoxItem Content="USER"></ComboBoxItem>
Text="归属信息" VerticalAlignment="Top" Width="85" FontSize="20"/>
<TextBox x:Name="_Machine" Height="30" Margin="105,55,10,100" VerticalAlignment="Top" FontSize="16" MaxLines="1"/>
<TextBlock HorizontalAlignment="Left" Height="30" Margin="15,55,0,100" TextWrapping="Wrap"
Text="设备名称" VerticalAlignment="Top" Width="85" FontSize="20"/>
<ComboBox x:Name="GROUP" Height="30" Margin="105,100,10,100" VerticalAlignment="Top" FontSize="16" IsReadOnly="True">
<ComboBoxItem Content="200"></ComboBoxItem>
<ComboBoxItem Content="202"></ComboBoxItem>
<ComboBoxItem Content="242W"></ComboBoxItem>
<ComboBoxItem Content="252"></ComboBoxItem>
<ComboBoxItem Content="252-2T"></ComboBoxItem>
<ComboBoxItem Content="252RB"></ComboBoxItem>
<ComboBoxItem Content="252RDRM"></ComboBoxItem>
<ComboBoxItem Content="252-2T"></ComboBoxItem>
<ComboBoxItem Content="301"></ComboBoxItem>
<ComboBoxItem Content="301P"></ComboBoxItem>
<ComboBoxItem Content="302"></ComboBoxItem>
<ComboBoxItem Content="303"></ComboBoxItem>
<ComboBoxItem Content="303PDW"></ComboBoxItem>
</ComboBox>
<TextBlock HorizontalAlignment="Left" Height="30" Margin="15,190,0,50" TextWrapping="Wrap"
Text="{x:Static lang:ResourceLanguage.Groups}" VerticalAlignment="Top" Width="80" FontSize="20"/>
<TextBlock HorizontalAlignment="Left" Height="30" Margin="15,100,0,50" TextWrapping="Wrap"
Text="系列型号" VerticalAlignment="Top" Width="80" FontSize="20"/>
<TextBox x:Name="_IP" Height="30" Margin="105,145,10,100" VerticalAlignment="Top" FontSize="16" MaxLines="1"/>
<TextBlock HorizontalAlignment="Left" Height="30" Margin="15,145,0,100" TextWrapping="Wrap"
Text="连接IP" VerticalAlignment="Top" Width="85" FontSize="20"/>
<TextBox x:Name="_MachineUser" Height="30" Margin="105,190,10,100" VerticalAlignment="Top" FontSize="16" MaxLines="1"/>
<TextBlock HorizontalAlignment="Left" Height="30" Margin="15,190,0,100" TextWrapping="Wrap"
Text="连接用户" VerticalAlignment="Top" Width="85" FontSize="20"/>
<TextBox x:Name="_MachinePassword" Height="30" Margin="105,235,10,100" VerticalAlignment="Top" FontSize="16" MaxLines="1"/>
<TextBlock HorizontalAlignment="Left" Height="30" Margin="15,235,0,100" TextWrapping="Wrap"
Text="连接密码" VerticalAlignment="Top" Width="85" FontSize="20"/>
<TextBox x:Name="_inf" Height="90" Margin="105,280,10,100" VerticalAlignment="Top" FontSize="16" MaxLines="1"/>
</Grid>
<Grid Grid.Column="2" Margin="0">
<ScrollViewer Margin="0" VerticalScrollBarVisibility="Auto">
@@ -92,6 +113,7 @@
</Style>
</DataGrid.CellStyle>
<DataGrid.Columns>
<DataGridTextColumn Width="0" FontSize="26" Binding="{Binding ID}" MaxWidth="0" CanUserReorder="False"/>
<DataGridTextColumn Header="{x:Static lang:ResourceLanguage.information}" Width="200" FontSize="26"
Binding="{Binding Name}" MaxWidth="200" MinWidth="200" CanUserReorder="False"/>
<DataGridTextColumn Header="{x:Static lang:ResourceLanguage.machine}" Width="200" FontSize="26"
+56 -5
View File
@@ -1,5 +1,8 @@
using System;
using Microsoft.VisualBasic;
using SunlightAggregationManager.ViewModel;
using System;
using System.Collections.Generic;
using System.Reflection.PortableExecutable;
using System.Text;
using System.Windows;
using System.Windows.Controls;
@@ -9,6 +12,8 @@ using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Xml.Linq;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace SunlightAggregationManager.UserWindow
{
@@ -17,29 +22,75 @@ namespace SunlightAggregationManager.UserWindow
/// </summary>
public partial class MachineSet : Window
{
private string _id = "";
public MachineSet()
{
InitializeComponent();
}
private void Button_Preservation(object sender, RoutedEventArgs e)
{
{
Dictionary<string, object> _new = new Dictionary<string, object>();//缓存函数
_new.Add("Name", _Name.Text);
_new.Add("Machine", _Machine.Text);
_new.Add("Model", GROUP.Text);
_new.Add("IP", _IP.Text);
_new.Add("MachineUser", _MachineUser.Text);
_new.Add("MachinePassword", _MachinePassword.Text);
_new.Add("Information", _inf.Text);
_new.Add("State", 0);
var rowdata = MainWindowViewModel.Selet_Memory(MainWindowViewModel._machines, "ID", "ID='" + _id + "'");
if (rowdata != null)
{
MainWindowViewModel.Updata_Memory(MainWindowViewModel._machines, "ID='" + _id + "'", _new);
}
else
{
MainWindowViewModel.Insert_Memory(MainWindowViewModel._machines, _new);// 执行插入
}
DataGridm.ItemsSource = MainWindowViewModel._machines.DefaultView;
_Name.Text = null;
_Machine.Text = null;
_id = "";
}
private void Button_Delete(object sender, RoutedEventArgs e)
{
try
{
MainWindowViewModel.Delete_Memory(MainWindowViewModel._machines, "ID='" + _id + "'");
}
catch (Exception) { }
finally
{
DataGridm.ItemsSource = MainWindowViewModel._machines.DefaultView;
_Name.Text = null;
_Machine.Text = null;
_id = "";
}
}
private void DataGridm_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
int rownum = DataGridm.SelectedIndex;//获取鼠标选中行并定义变量
if (rownum != -1)//判断鼠标定位是否有效
{
/*定位选中行及指定列单元格文本信息*/
_id = (DataGridm.Columns[0].GetCellContent(DataGridm.Items[rownum]) as TextBlock)!.Text.Trim();//定位第列
_Name.Text = (DataGridm.Columns[1].GetCellContent(DataGridm.Items[rownum]) as TextBlock)!.Text.Trim();//定位第列
_Machine.Text = (DataGridm.Columns[2].GetCellContent(DataGridm.Items[rownum]) as TextBlock)!.Text.Trim();//定位第列
GROUP.Text = (DataGridm.Columns[4].GetCellContent(DataGridm.Items[rownum]) as TextBlock)!.Text.Trim();
_IP.Text = (DataGridm.Columns[5].GetCellContent(DataGridm.Items[rownum]) as TextBlock)!.Text.Trim();
_MachineUser.Text = (DataGridm.Columns[6].GetCellContent(DataGridm.Items[rownum]) as TextBlock)!.Text.Trim();
_MachinePassword.Text = (DataGridm.Columns[7].GetCellContent(DataGridm.Items[rownum]) as TextBlock)!.Text.Trim();
_inf.Text = (DataGridm.Columns[8].GetCellContent(DataGridm.Items[rownum]) as TextBlock)!.Text.Trim();
}
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
DataGridm.ItemsSource = MainWindowViewModel._machines.DefaultView;
}
}
}
+1 -1
View File
@@ -99,7 +99,7 @@ namespace SunlightAggregationManager.View
{
string text_APP = "TEST"; //
string text_LINK = MainWindowViewModel.MachineIP + ":"+ MainWindowViewModel.MachineIPP1 +
"," + MainWindowViewModel.SERVERIP + "/"+ MainWindowViewModel.Enterprise;
"," + MainWindowViewModel.SERVERIP + ":7791/"+ MainWindowViewModel.Enterprise;
// 要生成二维码的内容
imgQR_CREATE(text_APP, imgQR_app);
+129 -11
View File
@@ -40,12 +40,15 @@ namespace SunlightAggregationManager.ViewModel
public static string SERVERNAME = "";
public static string SERVERUSER = "";
public static string SERRVERPASWORD = "";
public static int ChemicalNumber, DyeMeasurementNumber, DyeDissolveNumber, PowderNumber;
private static Timer? _timer;
public static DataTable ChemicalStatistics = new DataTable();
public static DataTable DBC_Machines = new DataTable();
public static DataBase dataBase = new DataBase();
public static UserClass.SqliteHelper SQLiteHelpers = null!; //定义数据库
private readonly string DBAddress = Environment.CurrentDirectory + "\\DataBase\\SunlightAggregationManager.db"; //数据库路径
public static DataTable ActionLog = new DataTable();
[ObservableProperty]
public static DataTable _machines = new DataTable(); //设备表缓存
[ObservableProperty]
@@ -87,6 +90,7 @@ namespace SunlightAggregationManager.ViewModel
}
Machines.RowChanged += Machines_Updata;
Machines.RowDeleting += Machines_Updata;
UserData.RowChanged += UserData_Updata;//注册userdata表更新事件
UserData.RowDeleting += UserData_Updata;
}
@@ -147,18 +151,63 @@ namespace SunlightAggregationManager.ViewModel
Console.WriteLine(MachineIP);
//连接sunlight服务器
Service.Rows.Add(3, "RUN", "Sunlight_Server_Link");
AsyncTcpClient.Configuration(SERVERIP, SERVERNAME, SERVERUSER, SERRVERPASWORD);
AsyncTcpClient.Configuration(SERVERIP + ":7795", SERVERNAME, SERVERUSER, SERRVERPASWORD);
Service.EndInit();
_timer = new Timer(TimeTask, null, TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(30));
}
//Machines操作数据库
private void Machines_Updata(object sender, DataRowChangeEventArgs e)
{
}
Dictionary<string, object> row_entity = new Dictionary<string, object>();
Dictionary<string, object> userlog = new Dictionary<string, object>();
if (e.Action == DataRowAction.Change)
{
//修改的行回传
foreach (DataColumn col in Machines.Columns)
{
row_entity.Add(col.ColumnName, e.Row.Field<object>(col.ColumnName) ?? DBNull.Value);//传入字段和值(值允许为空)
if (ActionLog.Columns.Contains(col.ColumnName))//添加到行为记录表
{
userlog.Add(col.ColumnName, e.Row.Field<object>(col.ColumnName) ?? DBNull.Value);//传入字段和值(值允许为空)
}
}
SQLiteHelpers.Update("Machines", row_entity, "ID='" + e.Row.Field<object>("ID") + "'", null);
userlog.Add("Action", "Command");
userlog.Add("Time", DateTime.Now.ToString("yyyy-MM-dd dd:HH:mm:ss:fff"));
userlog.Add("Note", "Machine = " + e.Row.Field<object>("Machine"));
SQLiteHelpers.InsertData("ActionLog", userlog);
}
if (e.Action == DataRowAction.Add)
{
//添加的行回传
foreach (DataColumn col in Machines.Columns)
{
row_entity.Add(col.ColumnName, e.Row.Field<object>(col.ColumnName) ?? DBNull.Value);//传入字段和值(值允许为空)
}
SQLiteHelpers.InsertData("Machines", row_entity);
userlog.Add("Time", DateTime.Now.ToString("yyyy-MM-dd dd:HH:mm:ss:fff"));
userlog.Add("Action", "New Account");
userlog.Add("Note", "Machine = " + e.Row.Field<object>("Machine"));
SQLiteHelpers.InsertData("ActionLog", userlog);
}
if (e.Action == DataRowAction.Delete)
{
//删除的行回传
SQLiteHelpers.Delete("Machines", "ID='" + e.Row.Field<object>("ID") + "'", null);
userlog.Add("Time", DateTime.Now.ToString("yyyy-MM-dd dd:HH:mm:ss:fff"));
userlog.Add("Action", "Delete Account");
userlog.Add("Note", "Machine = " + e.Row.Field<object>("Machine"));
SQLiteHelpers.InsertData("ActionLog", userlog);
}
}
//UserData操作数据库
private void UserData_Updata(object sender, DataRowChangeEventArgs e)
{
Dictionary<string, object> row_entity = new Dictionary<string, object>();
@@ -212,6 +261,8 @@ namespace SunlightAggregationManager.ViewModel
SQLiteHelpers.InsertData("ActionLog", userlog);
}
}
//数据表操作
public static void Insert_Memory(DataTable DB, Dictionary<string, object> Value)//插入数据
{
try
@@ -273,9 +324,14 @@ namespace SunlightAggregationManager.ViewModel
{
lock (DB)
{
DataRow drEmployee = DB.Select(key).First();
object? index = drEmployee.Field<object>(name);
return index;
DataRow[] dataRows = DB.Select(key);
if (dataRows.Count() > 0)
{
DataRow drEmployee = dataRows.First();
object? index = drEmployee.Field<object>(name);
return index;
}
else { return null; }
}
}
catch (Exception ex)
@@ -335,5 +391,67 @@ namespace SunlightAggregationManager.ViewModel
}
}
private static int EXTime = 120;
private static async void TimeTask(object? state)
{
if (EXTime == 120)//1小时
{
EXTask();//统计配送消息
EXTime = 0;
}
DBC_Machines = await dataBase.ExecuteQueryAsync("SELECT *FROM [BatchDyeingCentral].[dbo].[Machines]");
EXTime++;
}
private static async void EXTask()
{
try
{
string DyelotsBulkedRecipe_sql = "SELECT [ProductCode],[ProductName],SUM(DispenseGrams)" +
"as TotalDispenseGrams FROM [BatchDyeingCentral].[dbo].[DyelotsBulkedRecipe] " +
"where DispenseEndTime > '" + DateTime.Now.ToString("yyyy-MM-dd") + "' AND DispenseEndTime < '" +
DateTime.Now.AddDays(1).ToString("yyyy-MM-dd") + "' GROUP BY [ProductCode],[ProductName] " +
"ORDER BY TotalDispenseGrams DESC ";
string Dye_sql =
"SELECT [Dyelot],[ReDye],[StepNumber] FROM [BatchDyeingCentral].[dbo].[DyelotsBulkedRecipe] " +
"where ((DispenseEndTime >= '" + DateTime.Now.ToString("yyyy-MM-dd") + "' AND DispenseEndTime < '" +
DateTime.Now.AddDays(1).ToString("yyyy-MM-dd") + "') OR (DispenseTime >= '" + DateTime.Now.ToString("yyyy-MM-dd") +
"' AND DispenseTime < '" + DateTime.Now.AddDays(1).ToString("yyyy-MM-dd") + "')) " +
"AND ProductType = 1 GROUP BY [Dyelot],[ReDye],[StepNumber];";
string Chemical_sql =
"SELECT [Dyelot],[ReDye],[StepNumber] FROM [BatchDyeingCentral].[dbo].[DyelotsBulkedRecipe] " +
"where ((DispenseEndTime >= '" + DateTime.Now.ToString("yyyy-MM-dd") + "' AND DispenseEndTime < '" +
DateTime.Now.AddDays(1).ToString("yyyy-MM-dd") + "') OR (DispenseTime >= '" + DateTime.Now.ToString("yyyy-MM-dd") +
"' AND DispenseTime < '" + DateTime.Now.AddDays(1).ToString("yyyy-MM-dd") + "')) " +
"AND ProductType = 2 GROUP BY [Dyelot],[ReDye],[StepNumber];";
string Powder_sql =
"SELECT [Dyelot],[ReDye],[StepNumber] FROM [BatchDyeingCentral].[dbo].[DyelotsBulkedRecipe] " +
"where ((DispenseEndTime >= '" + DateTime.Now.ToString("yyyy-MM-dd") + "' AND DispenseEndTime < '" +
DateTime.Now.AddDays(1).ToString("yyyy-MM-dd") + "') OR (DispenseTime >= '" + DateTime.Now.ToString("yyyy-MM-dd") +
"' AND DispenseTime < '" + DateTime.Now.AddDays(1).ToString("yyyy-MM-dd") + "')) " +
"AND ProductType = 3 GROUP BY [Dyelot],[ReDye],[StepNumber];";
string DyeDissolve =
"SELECT *FROM [BatchDyeingCentral].[dbo].[DyeSolutionHistory] " + "where DispenseEndTime >= '" +
DateTime.Now.ToString("yyyy-MM-dd") + "' AND DispenseEndTime < '" + DateTime.Now.AddDays(1).ToString("yyyy-MM-dd") + "'";
ChemicalStatistics = await dataBase.ExecuteQueryAsync(DyelotsBulkedRecipe_sql);
DyeMeasurementNumber = await dataBase.ExecuteQueryAsyncCount(Dye_sql);
ChemicalNumber = await dataBase.ExecuteQueryAsyncCount(Chemical_sql);
PowderNumber = await dataBase.ExecuteQueryAsyncCount(Powder_sql);
DyeDissolveNumber = await dataBase.ExecuteQueryAsyncCount(DyeDissolve);
}
catch (Exception ex)
{//错误处理
LogGing.ERRDATA(ex);
Console.WriteLine(ex.ToString());
}
finally {
Console.WriteLine("当日染料称量["+ DyeMeasurementNumber+ "]染料输送["+ DyeDissolveNumber + "]" +
"助剂输送["+ ChemicalNumber + "]粉体输送["+ PowderNumber + "]");
}
}
}
}
}