diff --git a/SunlightAggregationManager.csproj b/SunlightAggregationManager.csproj index 9ec952f..4b37532 100644 --- a/SunlightAggregationManager.csproj +++ b/SunlightAggregationManager.csproj @@ -15,7 +15,8 @@ - + + diff --git a/UserClass/AsyncHttpServer.cs b/UserClass/AsyncHttpServer.cs new file mode 100644 index 0000000..cf61710 --- /dev/null +++ b/UserClass/AsyncHttpServer.cs @@ -0,0 +1,205 @@ +using SunlightAggregationManager.ViewModel; +using System; +using System.Collections.Generic; +using System.Data; +using System.Text; +using System.Text.Json; +using TouchSocket.Core; +using TouchSocket.Http; +using TouchSocket.Http.WebSockets; +using TouchSocket.Sockets; +using static SunlightAggregationManager.UserClass.AsyncTcpServer; + + +namespace SunlightAggregationManager.UserClass +{ + public class AsyncHttpServer + { + public static HttpService httpservice = new HttpService(); + + public static async Task HttpMain(int port1) + { + NetFwManger.AllowPort(port1, "TCP");//开放端口 + await httpservice.SetupAsync(new TouchSocketConfig()//加载配置 + .SetListenIPHosts(port1) + .ConfigureContainer(a => + { + a.AddConsoleLogger(); + }) + .ConfigurePlugins(a => + { + a.Add(); + //default插件应该最后添加,其作用是 + //1、为找不到的路由返回404 + //2、处理 header 为Option的探视跨域请求。 + a.UseDefaultHttpServicePlugin(); + })); + await httpservice.StartAsync(); + Console.WriteLine("HTTP Port:" + port1.ToString()); + } + + public class MyHttpPlug1 : PluginBase, IHttpPlugin + { + public async Task OnHttpRequest(IHttpSessionClient client, HttpContextEventArgs e) + { + #region HttpContext生命周期 + //var request = e.Context.Request;//http请求体 + var response = e.Context.Response;//http响应体 + #endregion + + var bodyString = await e.Context.Request.GetBodyAsync(); + try + { + Person? deserializedPerson = JsonSerializer.Deserialize(bodyString); + + var _user = MainWindowViewModel.Selet_Memory(MainWindowViewModel._userData, "State", "User='" + + deserializedPerson?.User + "' and Password ='" + deserializedPerson?.Password + "'"); + if (_user != null) + { + string _dat = _user?.ToString() ?? "0"; + if (_dat != "99") + { + //行为 + Dictionary myDict = new Dictionary(); + myDict.Add("LinkID", client.Id); + 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); + + Console.WriteLine("[Log on]User[" + deserializedPerson?.User + "]Note[" + (deserializedPerson?.Dat ?? "unknown") + "]"); + + var dt = await Command(deserializedPerson!); + + e.Context.Response.Headers.Add("SUNLIGHT", "SUNLIGHT"); + e.Context.Response.SetStatus(200, "success"); + e.Context.Response.SetContent(Encoding.UTF8.GetBytes(dt.ToCharArray())); + await e.Context.Response.AnswerAsync(); + } + else + {//停用账号关闭连接 + //client.SendAsync("Account Deactivated"); + e.Context.Response.Headers.Add("SUNLIGHT", "SUNLIGHT"); + e.Context.Response.SetStatus(200, "success"); + e.Context.Response.SetContent("Account Deactivated"); + await e.Context.Response.AnswerAsync(); + } + } + else + { //无效账号关闭连接 + //client.SendAsync("Invalid Account"); + e.Context.Response.Headers.Add("SUNLIGHT", "SUNLIGHT"); + e.Context.Response.SetStatus(200, "success"); + e.Context.Response.SetContent("Invalid Account"); + await e.Context.Response.AnswerAsync(); + } + } + catch (Exception ex) + {//错误 + Console.WriteLine("Http:" + ex.ToString()); + //client.SendAsync("Target instruction parsing error manager will close connection"); + } + + + /* if (request.IsGet() && request.UrlEquals("/success")) + { + //直接响应文字 + await response + .SetStatus(200, "success") + .FromText("Success") + .AnswerAsync();//直接回应 + Console.WriteLine("处理/success"); + return; + } + + + //无法处理,调用下一个插件 + await e.InvokeNext();*/ + } + } + + public static async Task Command(Person deserializedPerson)// + { + string Command = "", ret = ""; + + Dictionary data_ = new Dictionary(); + var deserialized = JsonSerializer.Deserialize>(deserializedPerson.Dat)!; + if (deserialized.TryGetValue("Command", out var val) && val != null) Command = val.ToString()!; + if (Command == "Log")//回复请求的信息 + { + DataRow? _user = MainWindowViewModel.Selet_Row(MainWindowViewModel._userData, "User='" + + deserializedPerson?.User + "' and Password ='" + deserializedPerson?.Password + "'"); + + data_.Add("Enterprise", _user?.Field("Enterprise") ?? ""); + data_.Add("Department", _user?.Field("Department") ?? ""); + data_.Add("Groups", _user?.Field("Groups") ?? ""); + data_.Add("UserId", _user?.Field("UserID") ?? ""); + data_.Add("UserName", _user?.Field("Name") ?? ""); + ret = JsonSerializer.Serialize(data_); + } + if (Command == "Info")//回复info请求的信息 + { + var t = ToList(MainWindowViewModel._machines).ToJsonString(); + //格式化返回信息 + data_.Add("Info", t); + 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")//回复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_); + } + + return ret; + } + + public static List>? ToList(DataTable table)//datatable转list + { + if (table == null) return null; + + // 使用 AsEnumerable() 将 DataTable 转换为 IEnumerable + // 然后投影为 Dictionary + return table.AsEnumerable().Select(row => + table.Columns.Cast().ToDictionary( + col => col.ColumnName, + col => { + var value = row[col]; + // 核心修改:如果是数据库空值 DBNull.Value,则转为 C# 的 null,否则保持原值 + return value == DBNull.Value ? null : value; + } + ) + ).ToList(); + } + + } +} diff --git a/UserClass/AsyncTcpServer.cs b/UserClass/AsyncTcpServer.cs index d49ef2a..e2d7f04 100644 --- a/UserClass/AsyncTcpServer.cs +++ b/UserClass/AsyncTcpServer.cs @@ -9,7 +9,6 @@ using System.Windows.Markup; using System.Xml.Linq; using TouchSocket.Core; using TouchSocket.Sockets; -using static System.Runtime.InteropServices.JavaScript.JSType; namespace SunlightAggregationManager.UserClass { @@ -236,64 +235,7 @@ namespace SunlightAggregationManager.UserClass ) ).ToList(); } - - - - } - - class MyTcpService : TcpService - { - protected override MyTcpSessionClient NewClient() - { - return new MyTcpSessionClient(); - } } - class MyTcpSessionClient : TcpSessionClient - { - internal void SetDataHandlingAdapter(SingleStreamDataHandlingAdapter adapter) - { - base.SetAdapter(adapter); - } - } - - /// - /// 此插件实现,按照不同端口,使用不同适配器。 - /// - /// 7789端口:使用"**"结尾的数据 - /// 7790端口:使用"##"结尾的数据 - /// - /// - internal class DifferentProtocolPlugin : PluginBase, ITcpConnectingPlugin, ITcpReceivedPlugin - { - public async Task OnTcpConnecting(ITcpSession client, ConnectingEventArgs e) - { - if (client is MyTcpSessionClient sessionClient) - { - if (sessionClient.ServicePort == 7789) - { - sessionClient.SetDataHandlingAdapter(new TerminatorPackageAdapter("**")); - } - else - { - sessionClient.SetDataHandlingAdapter(new TerminatorPackageAdapter("##")); - } - } - - await e.InvokeNext(); - } - - public async Task OnTcpReceived(ITcpSession client, ReceivedDataEventArgs e) - { - //如果是自定义适配器,此处解析时,可以判断e.RequestInfo的类型 - - if (client is ITcpSessionClient sessionClient) - { - sessionClient.Logger.Info($"{sessionClient.GetIPPort()}收到数据,服务器端口:{sessionClient.ServicePort},数据:{e.Memory.Span.ToString(Encoding.UTF8)}"); - } - - await e.InvokeNext(); - } - - } + } diff --git a/ViewModel/MainWindowViewModel.cs b/ViewModel/MainWindowViewModel.cs index 913d0b0..ac3a202 100644 --- a/ViewModel/MainWindowViewModel.cs +++ b/ViewModel/MainWindowViewModel.cs @@ -80,8 +80,10 @@ namespace SunlightAggregationManager.ViewModel } //运行数据库 - dataBase.Config(SQLIP, SQLNAME, SQMOD, SQLUSER, SQLPASWORD); + dataBase.Config(SQLIP, SQLNAME, SQMOD, SQLUSER, SQLPASWORD); + + Console.WriteLine(GetLocalIP.GetLocalIPv4Address().ToString()); if (TCP_E == "1")//启动tcp(内网直连) { int P1, P2; @@ -96,9 +98,18 @@ namespace SunlightAggregationManager.ViewModel } catch (Exception) { P2 = 7790; } - Console.WriteLine(GetLocalIP.GetLocalIPv4Address().ToString()); _ = AsyncTcpServer.TcpMain(P1,P2); } + if (HTTP_E == "1")//启动tcp(内网直连) + { + int P1; + try + { + P1 = int.Parse(Configini.IniReadvalue("NETWORK", "HTTP_PORT")); + } + catch (Exception) { P1 = 7791; } + _ = AsyncHttpServer.HttpMain(P1); + } } private void Machines_Updata(object sender, DataRowChangeEventArgs e)