Compare commits

..

2 Commits

@ -1,7 +1,7 @@
namespace OMS.NET.DbClass namespace OMS.NET.DbClass
{ {
[Table("map_data")] [Table("map_data")]
public class Map : BaseObject public class Map : SqlTable
{ {
[Column("id", true)] // Primary Key and Identity false [Column("id", true)] // Primary Key and Identity false
public string Id { get; set; } public string Id { get; set; }

@ -27,15 +27,22 @@ namespace OMS.NET.DbClass
IsIdentity = isIdentity; IsIdentity = isIdentity;
} }
} }
public class BaseObject
public class SqlHelper
{ {
private static string GetTableName(Type type) public static string GetTableName(Type type)
{ {
var attr = type.GetCustomAttribute<TableAttribute>(); var attr = type.GetCustomAttribute<TableAttribute>();
return attr?.TableName ?? throw new Exception($"{type.Name} 没有指定数据表"); return attr?.TableName ?? throw new Exception($"{type.Name} 没有指定数据表");
} }
private static IEnumerable<PropertyInfo> GetProperties(Type type) public static bool IsIdentity(Type type)
{
var primaryKey = GetPrimaryKeyProperties(type);
return primaryKey.GetCustomAttribute<ColumnAttribute>()!.IsIdentity;
}
public static IEnumerable<PropertyInfo> GetProperties(Type type)
{ {
return type.GetProperties() return type.GetProperties()
.Where(p => p.GetCustomAttribute<ColumnAttribute>() != null); .Where(p => p.GetCustomAttribute<ColumnAttribute>() != null);
@ -72,7 +79,7 @@ namespace OMS.NET.DbClass
return (primaryKey.GetCustomAttribute<ColumnAttribute>()!.IsIdentity == true) ? null : primaryKey; return (primaryKey.GetCustomAttribute<ColumnAttribute>()!.IsIdentity == true) ? null : primaryKey;
} }
private static string GetInsertSql(Type type) public static string GetInsertSql(Type type)
{ {
var tableName = GetTableName(type); var tableName = GetTableName(type);
var identityKey = GetIdentityKeyProperty(type); var identityKey = GetIdentityKeyProperty(type);
@ -91,7 +98,7 @@ namespace OMS.NET.DbClass
return $"INSERT INTO {tableName} ({string.Join(", ", columns)}) VALUES ({string.Join(", ", values)})"; return $"INSERT INTO {tableName} ({string.Join(", ", columns)}) VALUES ({string.Join(", ", values)})";
} }
private static string GetUpdateSql(Type type) public static string GetUpdateSql(Type type)
{ {
var tableName = GetTableName(type); var tableName = GetTableName(type);
var setClause = string.Join(", ", var setClause = string.Join(", ",
@ -103,7 +110,7 @@ namespace OMS.NET.DbClass
return $"UPDATE {tableName} SET {setClause} WHERE {whereClause}"; return $"UPDATE {tableName} SET {setClause} WHERE {whereClause}";
} }
private static string GetDeleteSql(Type type) public static string GetDeleteSql(Type type)
{ {
var tableName = GetTableName(type); var tableName = GetTableName(type);
var primaryKey = GetPrimaryKeyProperties(type); var primaryKey = GetPrimaryKeyProperties(type);
@ -112,7 +119,7 @@ namespace OMS.NET.DbClass
return $"DELETE FROM {tableName} WHERE {whereClause}"; return $"DELETE FROM {tableName} WHERE {whereClause}";
} }
private static string GetSelectSql(Type type) public static string GetSelectSql(Type type)
{ {
var tableName = GetTableName(type); var tableName = GetTableName(type);
var columns = string.Join(", ", var columns = string.Join(", ",
@ -122,7 +129,7 @@ namespace OMS.NET.DbClass
return $"SELECT {columns} FROM {tableName}"; return $"SELECT {columns} FROM {tableName}";
} }
private static string GetSelectSqlWithPrimaryKey(Type type) public static string GetSelectSqlWithPrimaryKey(Type type)
{ {
var tableName = GetTableName(type); var tableName = GetTableName(type);
var columns = string.Join(", ", var columns = string.Join(", ",
@ -134,59 +141,7 @@ namespace OMS.NET.DbClass
return $"SELECT {columns} FROM {tableName} WHERE {whereClause}"; return $"SELECT {columns} FROM {tableName} WHERE {whereClause}";
} }
public void Test() public static IEnumerable<T> SelectAll<T>() where T : SqlTable, new()
{
Console.WriteLine("===========this is a test area=================");
Console.WriteLine(GetInsertSql(GetType()));
Console.WriteLine(GetDeleteSql(GetType()));
Console.WriteLine(GetUpdateSql(GetType()));
Console.WriteLine(GetSelectSql(GetType()));
Console.WriteLine(GetSelectSqlWithPrimaryKey(GetType()));
Console.WriteLine("===========this is a test area=================");
}
public virtual void Insert()
{
var type = GetType();
var insertSql = GetInsertSql(GetType());
using MySqlConnection connection = new(GlobalArea.ConnectionStringWithDbName);
connection.Open(); // 确保在执行命令之前打开连接
using var command = new MySqlCommand(insertSql, connection);
AddParameters(command);
Console.WriteLine($"SQL: {command.CommandText}");
foreach (MySqlParameter param in command.Parameters)
{
Console.WriteLine($"Parameter: {param.ParameterName}, Value: {param.Value}");
}
command.ExecuteNonQuery();
Log.Info($"{GetTableName(type)}数据表插入({string.Join(',', ShowDetail())})");
}
public virtual void Update()
{
var type = GetType();
var updateSql = GetUpdateSql(GetType());
using MySqlConnection connection = new(GlobalArea.ConnectionStringWithDbName);
connection.Open(); // 确保在执行命令之前打开连接
using var command = new MySqlCommand(updateSql, connection);
AddParameters(command);
command.ExecuteNonQuery();
Log.Info($"{GetTableName(type)}数据表修改({string.Join(',', ShowDetail())})");
}
public virtual void Delete()
{
var type = GetType();
var deleteSql = GetDeleteSql(GetType());
using MySqlConnection connection = new(GlobalArea.ConnectionStringWithDbName);
connection.Open(); // 确保在执行命令之前打开连接
using var command = new MySqlCommand(deleteSql, connection);
AddParameters(command);
command.ExecuteNonQuery();
Log.Info($"{GetTableName(type)}数据表删除({string.Join(',', ShowDetail())})");
}
public static IEnumerable<T> SelectAll<T>() where T : BaseObject, new()
{ {
var type = typeof(T); var type = typeof(T);
var selectSql = GetSelectSql(type); var selectSql = GetSelectSql(type);
@ -205,7 +160,21 @@ namespace OMS.NET.DbClass
return results; return results;
} }
public static T? Get<T>(object key) where T : BaseObject, new() private static void PopulateObject(MySqlDataReader reader, SqlTable obj)
{
var type = obj.GetType();
foreach (var property in GetProperties(type))
{
var columnAttr = property.GetCustomAttribute<ColumnAttribute>()!;
var value = reader[columnAttr.ColumnName];
if (value != DBNull.Value)
{
property.SetValue(obj, Convert.ChangeType(value, property.PropertyType));
}
}
}
public static T? Get<T>(object key) where T : SqlTable, new()
{ {
var type = typeof(T); var type = typeof(T);
var selectSql = GetSelectSqlWithPrimaryKey(type); var selectSql = GetSelectSqlWithPrimaryKey(type);
@ -223,33 +192,5 @@ namespace OMS.NET.DbClass
} }
return null; return null;
} }
private void AddParameters(MySqlCommand command)
{
foreach (var property in GetProperties(GetType()))
{
//var columnAttr = property.GetCustomAttribute<ColumnAttribute>()!;
command.Parameters.AddWithValue("@" + property.Name, property.GetValue(this));
}
}
private IEnumerable<string> ShowDetail()
{
return GetProperties(GetType()).Select(p => $"{p.Name}={p.GetValue(this)}");
}
private static void PopulateObject(MySqlDataReader reader, BaseObject obj)
{
var type = obj.GetType();
foreach (var property in GetProperties(type))
{
var columnAttr = property.GetCustomAttribute<ColumnAttribute>()!;
var value = reader[columnAttr.ColumnName];
if (value != DBNull.Value)
{
property.SetValue(obj, Convert.ChangeType(value, property.PropertyType));
}
}
}
} }
} }

@ -0,0 +1,81 @@
using System.Reflection;
using MySql.Data.MySqlClient;
using OMS.NET.Common;
namespace OMS.NET.DbClass
{
public class SqlTable
{
public void Test()
{
Console.WriteLine("===========this is a test area=================");
Console.WriteLine(SqlHelper.GetInsertSql(GetType()));
Console.WriteLine(SqlHelper.GetDeleteSql(GetType()));
Console.WriteLine(SqlHelper.GetUpdateSql(GetType()));
Console.WriteLine(SqlHelper.GetSelectSql(GetType()));
Console.WriteLine(SqlHelper.GetSelectSqlWithPrimaryKey(GetType()));
Console.WriteLine("===========this is a test area=================");
}
/// <summary>
/// 将对象本身插入到数据库中
/// </summary>
public virtual void Insert()
{
var type = GetType();
var insertSql = SqlHelper.GetInsertSql(GetType());
using MySqlConnection connection = new(GlobalArea.ConnectionStringWithDbName);
connection.Open(); //确保在执行命令之前打开连接
using var command = new MySqlCommand(insertSql, connection);
AddParameters(command);
Console.WriteLine($"SQL: {command.CommandText}");
foreach (MySqlParameter param in command.Parameters)
{
Console.WriteLine($"Parameter: {param.ParameterName}, Value: {param.Value}");
}
command.ExecuteNonQuery();
Log.Info($"{SqlHelper.GetTableName(type)}数据表插入({string.Join(',', ShowDetail())})");
}
public virtual void Update()
{
var type = GetType();
var updateSql = SqlHelper.GetUpdateSql(GetType());
using MySqlConnection connection = new(GlobalArea.ConnectionStringWithDbName);
connection.Open();
using var command = new MySqlCommand(updateSql, connection);
AddParameters(command);
command.ExecuteNonQuery();
Log.Info($"{SqlHelper.GetTableName(type)}数据表修改({string.Join(',', ShowDetail())})");
}
public virtual void Delete()
{
var deleteSql = SqlHelper.GetDeleteSql(GetType());
using MySqlConnection connection = new(GlobalArea.ConnectionStringWithDbName);
connection.Open();
using var command = new MySqlCommand(deleteSql, connection);
AddParameters(command);
command.ExecuteNonQuery();
Log.Info($"{SqlHelper.GetTableName(GetType())}数据表删除({string.Join(',', ShowDetail())})");
}
private void AddParameters(MySqlCommand command)
{
//bool IsIdentity = SqlHelper.IsIdentity(GetType());
foreach (var property in SqlHelper.GetProperties(GetType()))
{
if (property.GetCustomAttribute<ColumnAttribute>()!.IsIdentity)
{
continue;
}
command.Parameters.AddWithValue("@" + property.Name, property.GetValue(this));
}
}
public IEnumerable<string> ShowDetail()
{
return SqlHelper.GetProperties(GetType()).Select(p => $"{p.Name}={p.GetValue(this)}");
}
}
}

@ -6,7 +6,7 @@ namespace OMS.NET.Instructs
{ {
public GetMapDataInstruct() public GetMapDataInstruct()
{ {
this.Type = "get_mapData"; Type = "get_mapData";
} }
public override Task Handler(string wsid) public override Task Handler(string wsid)
@ -25,7 +25,7 @@ namespace OMS.NET.Instructs
{ {
public SendMapDataInstruct() public SendMapDataInstruct()
{ {
this.Type = "send_mapData"; Type = "send_mapData";
} }
} }
} }

@ -6,7 +6,7 @@ namespace OMS.NET.Instructs
{ {
public GetMapLayerInstruct() public GetMapLayerInstruct()
{ {
this.Type = "get_mapLayer"; Type = "get_mapLayer";
} }
public override Task Handler(string wsid) public override Task Handler(string wsid)
@ -25,7 +25,7 @@ namespace OMS.NET.Instructs
{ {
public SendMapLayerInstruct() public SendMapLayerInstruct()
{ {
this.Type = "send_mapLayer"; Type = "send_mapLayer";
} }
} }
} }

@ -6,14 +6,14 @@ namespace OMS.NET.Instructs
{ {
public GetPublickeyInstruct() public GetPublickeyInstruct()
{ {
this.Type = "get_publickey"; Type = "get_publickey";
} }
public override Task Handler(string wsid) public override Task Handler(string wsid)
{ {
return Task.Run(() => return Task.Run(() =>
{ {
this.ResponseOrBroadcastInstructs.Add(new PublickeyInstruct() ResponseOrBroadcastInstructs.Add(new PublickeyInstruct()
{ {
Data = GlobalArea.GetRsaPublickKey(), Data = GlobalArea.GetRsaPublickKey(),
IsResponse = true IsResponse = true
@ -27,7 +27,7 @@ namespace OMS.NET.Instructs
{ {
public PublickeyInstruct() public PublickeyInstruct()
{ {
this.Type = "publickey"; Type = "publickey";
} }
} }

@ -6,7 +6,7 @@ namespace OMS.NET.Instructs
{ {
public GetUserDataInstruct() public GetUserDataInstruct()
{ {
this.Type = "get_userData"; Type = "get_userData";
} }
public override Task Handler(string wsid) public override Task Handler(string wsid)
@ -25,7 +25,7 @@ namespace OMS.NET.Instructs
{ {
public SendUserDataInstruct() public SendUserDataInstruct()
{ {
this.Type = "send_userData"; Type = "send_userData";
} }
} }
} }

@ -112,7 +112,7 @@ namespace OMS.NET.Instructs
public Instruct() public Instruct()
{ {
this.Type = ""; Type = "";
} }
/// <summary> /// <summary>
@ -130,7 +130,7 @@ namespace OMS.NET.Instructs
stopWatch.Start(); stopWatch.Start();
await Handler(wsid); await Handler(wsid);
stopWatch.Stop(); stopWatch.Stop();
Log.Debug($"处理{this.GetType()}耗时:{stopWatch.ElapsedMilliseconds}ms"); Log.Debug($"处理{GetType()}耗时:{stopWatch.ElapsedMilliseconds}ms");
} }
public string ToJsonString() public string ToJsonString()

@ -11,17 +11,17 @@ namespace OMS.NET.Instructs
{ {
public LoginInstruct() public LoginInstruct()
{ {
this.Type = "login"; Type = "login";
} }
public override Task Handler(string wsid) public override Task Handler(string wsid)
{ {
return Task.Run(() => return Task.Run(() =>
{ {
if (this.Data?.GetType() == typeof(JsonElement)) if (Data?.GetType() == typeof(JsonElement))
{ {
string email = this.Data.GetProperty("email").GetString(); string email = Data.GetProperty("email").GetString();
string password = this.Data.GetProperty("password").GetString(); string password = Data.GetProperty("password").GetString();
if (string.IsNullOrEmpty(email) || string.IsNullOrEmpty(password)) if (string.IsNullOrEmpty(email) || string.IsNullOrEmpty(password))
{ {
Log.Warn("登录信息不能为空!"); Log.Warn("登录信息不能为空!");
@ -36,7 +36,7 @@ namespace OMS.NET.Instructs
{ {
public LoginStatusInstuct() public LoginStatusInstuct()
{ {
this.Type = "loginStatus"; Type = "loginStatus";
} }
} }
} }

@ -1,4 +1,7 @@
using System.Text.Json;
using OMS.NET.Common; using OMS.NET.Common;
using OMS.NET.DbClass;
using ZstdSharp.Unsafe;
namespace OMS.NET.Instructs namespace OMS.NET.Instructs
{ {
@ -9,7 +12,7 @@ namespace OMS.NET.Instructs
{ {
public TestInstruct() public TestInstruct()
{ {
this.Type = "test"; Type = "test";
} }
public override Task Handler(string wsid) public override Task Handler(string wsid)
@ -17,8 +20,47 @@ namespace OMS.NET.Instructs
return Task.Run(() => return Task.Run(() =>
{ {
//GlobalArea.UserConnects.Where(x => x.ID == wsid).First().UserEmail = "xxx@xx.com";//login //GlobalArea.UserConnects.Where(x => x.ID == wsid).First().UserEmail = "xxx@xx.com";//login
Log.Info("当前客户端连接数:" + GlobalArea.ConnectClientsCount); // Log.Info("当前客户端连接数:" + GlobalArea.ConnectClientsCount);
Log.Info("当前登录用户数:" + GlobalArea.LoginUserCount); // Log.Info("当前登录用户数:" + GlobalArea.LoginUserCount);
//测试数据表连接
if (Data?.GetType() != typeof(JsonElement)) return;//Data 非空和JsonElement类型检查
try
{
int op = Data.GetInt32();
Map map = new()
{
Id = "map1",
Name = "test",
Description = "haksjhdkasd"
};
switch (op)
{
case 0:
map.Test();
break;
case 1:
map.Insert();
Log.Debug($"插入测试成功,新的id为{map.Id}");
break;
case 2:
Log.Debug(string.Join(',', map.ShowDetail()));
break;
case 3:
map.Description = "随便写一个有意义的字符串";
map.Update();
break;
case 4:
map.Delete();
Log.Debug($"删除测试成功");
break;
default:
throw new Exception("do nothing");
}
}
catch (Exception ex)
{
Log.Warn($"处理{Type}指令出错:" + ex.Message);
}
}); });
} }
} }

@ -11,11 +11,11 @@ namespace OMS.NET
private IPEndPoint iPEndPoint = new(IPAddress.Any, 0); private IPEndPoint iPEndPoint = new(IPAddress.Any, 0);
protected override async void OnMessage(MessageEventArgs e) protected override async void OnMessage(MessageEventArgs e)
{ {
Log.Debug(this.ID + " " + this.Context.UserEndPoint.ToString() + ":" + e.Data); Log.Debug(ID + " " + Context.UserEndPoint.ToString() + ":" + e.Data);
Instruct? instruct = Instruct.JsonStringParse(e.Data); Instruct? instruct = Instruct.JsonStringParse(e.Data);
if (instruct != null) if (instruct != null)
{ {
await instruct.HandlerAndMeasure(this.ID); await instruct.HandlerAndMeasure(ID);
if (instruct.ResponseOrBroadcastInstructs.Count > 0) if (instruct.ResponseOrBroadcastInstructs.Count > 0)
{ {
instruct.ResponseOrBroadcastInstructs.ForEach(res => instruct.ResponseOrBroadcastInstructs.ForEach(res =>
@ -28,7 +28,7 @@ namespace OMS.NET
if (res.IsBroadcast) if (res.IsBroadcast)
{ {
string str = res.ToJsonString(); string str = res.ToJsonString();
foreach (IWebSocketSession session in this.Sessions.Sessions) foreach (IWebSocketSession session in Sessions.Sessions)
{ {
//看起来只有登录后的连接才能收到广播,这里添加下过滤 //看起来只有登录后的连接才能收到广播,这里添加下过滤
if (GlobalArea.LoginCheckByID(session.ID)) if (GlobalArea.LoginCheckByID(session.ID))
@ -44,23 +44,23 @@ namespace OMS.NET
protected override void OnOpen() protected override void OnOpen()
{ {
this.iPEndPoint = this.Context.UserEndPoint; iPEndPoint = Context.UserEndPoint;
GlobalArea.AddUserConnect(this.ID, this.iPEndPoint); GlobalArea.AddUserConnect(ID, iPEndPoint);
// Console.WriteLine(this.ID + " " + this.iPEndPoint.ToString() + " Conection Open"); Log.Info(ID + " " + iPEndPoint.ToString() + " Conection Open");
// Console.WriteLine($"当前连接客户端数量: {GlobalArea.ConnectClientsCount}"); // Console.WriteLine($"当前连接客户端数量: {GlobalArea.ConnectClientsCount}");
} }
protected override void OnClose(CloseEventArgs e) protected override void OnClose(CloseEventArgs e)
{ {
GlobalArea.RemoveUserConnectByID(this.ID); GlobalArea.RemoveUserConnectByID(ID);
// Console.WriteLine(this.ID + " " + this.iPEndPoint.ToString() + " Conection Close" + e.Reason); Log.Info(this.ID + " " + this.iPEndPoint.ToString() + " Conection Close" + e.Reason);
// Console.WriteLine($"当前连接客户端数量: {GlobalArea.ConnectClientsCount}"); // Console.WriteLine($"当前连接客户端数量: {GlobalArea.ConnectClientsCount}");
} }
protected override void OnError(ErrorEventArgs e) protected override void OnError(ErrorEventArgs e)
{ {
GlobalArea.RemoveUserConnectByID(this.ID); GlobalArea.RemoveUserConnectByID(ID);
// Console.WriteLine(this.ID + " " + this.iPEndPoint.ToString() + " Conection Error Close" + e.Message); Log.Info(this.ID + " " + this.iPEndPoint.ToString() + " Conection Error Close" + e.Message);
// Console.WriteLine($"当前连接客户端数量: {GlobalArea.ConnectClientsCount}"); // Console.WriteLine($"当前连接客户端数量: {GlobalArea.ConnectClientsCount}");
} }
} }

Loading…
Cancel
Save