From 277129373253fbce823b6dc5cf049086ae829223 Mon Sep 17 00:00:00 2001 From: nxiaoxiao <3247747442@qq.com> Date: Thu, 22 Aug 2024 00:49:42 +0800 Subject: [PATCH] =?UTF-8?q?=E5=88=9D=E6=AD=A5=E5=AE=9E=E7=8E=B0=E7=BB=9F?= =?UTF-8?q?=E4=B8=80=E7=9A=84=E6=95=B0=E6=8D=AE=E6=8E=A5=E5=85=A5=E5=B1=82?= =?UTF-8?q?=EF=BC=8C=E6=96=B9=E4=BE=BF=E5=90=8E=E9=9D=A2=E7=9A=84=E6=95=B0?= =?UTF-8?q?=E6=8D=AE=E8=A1=A8=E6=B7=BB=E5=8A=A0=E6=93=8D=E4=BD=9C=E3=80=82?= =?UTF-8?q?=E8=80=83=E8=99=91=E5=8F=AF=E5=A4=8D=E7=94=A8=E7=9A=84=E7=BB=9F?= =?UTF-8?q?=E4=B8=80=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Common/Logger.cs | 2 +- DbClass/AccountData.cs | 112 ------------- DbClass/BaseObject.cs | 255 ++++++++++++++++++++++++++++++ DbClass/Map.cs | 28 ++++ DbClass/MapData.cs | 155 ------------------ DbClass/MapLayer.cs | 142 ----------------- Instructs/GetMapDataInstruct.cs | 9 +- Instructs/GetMapLayerInstruct.cs | 9 +- Instructs/GetPublickeyInstruct.cs | 2 + Instructs/GetUserDataInstruct.cs | 19 +-- Instructs/Instruct.cs | 24 +-- Instructs/LoginInstruct.cs | 42 +---- Instructs/TestInstuct.cs | 6 +- OMS.NET.csproj | 3 - Program.cs | 64 ++++---- init.sql | 42 +---- 16 files changed, 341 insertions(+), 573 deletions(-) delete mode 100644 DbClass/AccountData.cs create mode 100644 DbClass/BaseObject.cs create mode 100644 DbClass/Map.cs delete mode 100644 DbClass/MapData.cs delete mode 100644 DbClass/MapLayer.cs diff --git a/Common/Logger.cs b/Common/Logger.cs index aef12ff..1e7b5eb 100644 --- a/Common/Logger.cs +++ b/Common/Logger.cs @@ -4,7 +4,7 @@ namespace OMS.NET.Common { private static readonly int _logLevel = 3; //debug private static int logCount = 0; - private static string logPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log", $"{DateTime.Now:yyyy-MM-dd-HH-mm-ss}.log"); + private static string logPath = GetNewLogFile(); private static readonly object LogLock = new(); private static void WriteLogToFile(string message) diff --git a/DbClass/AccountData.cs b/DbClass/AccountData.cs deleted file mode 100644 index 1bb5293..0000000 --- a/DbClass/AccountData.cs +++ /dev/null @@ -1,112 +0,0 @@ -using MySql.Data.MySqlClient; - -namespace OMS.NET.DbClass -{ - public class AccountData - { - #region base - public string UserEmail { get; set; } - public string UserName { get; set; } - public string Password { get; set; } - public int? MapLayer { get; set; } - public string? DefaultA1 { get; set; } - public string? SavePoint { get; set; } - public string? UserQQ { get; set; } - public string? HeadColor { get; set; } - public int Mode { get; set; } - public int Phase { get; set; } - public string? Custom { get; set; } - - public AccountData() - { - this.UserEmail = ""; - this.UserName = ""; - this.Password = ""; - this.Mode = 1; - this.Phase = 1; - //this.Custom = ""; - } - #endregion - public static void Add(AccountData accountData) - { - using MySqlConnection connection = new(GlobalArea.ConnectionStringWithDbName); - connection.Open(); - var query = @"INSERT INTO account_data (user_email, user_name, pass_word, map_layer, default_a1, save_point, user_qq, head_color, mode, phase, custom) - VALUES (@UserEmail, @UserName, @Password, @MapLayer, @DefaultA1, @SavePoint, @UserQQ, @HeadColor, @Mode, @Phase, @Custom)"; - using var command = new MySqlCommand(query, connection); - command.Parameters.AddWithValue("@UserEmail", accountData.UserEmail); - command.Parameters.AddWithValue("@UserName", accountData.UserName); - command.Parameters.AddWithValue("@Password", accountData.Password); - command.Parameters.AddWithValue("@MapLayer", accountData.MapLayer ?? (object)DBNull.Value); - command.Parameters.AddWithValue("@DefaultA1", accountData.DefaultA1 ?? (object)DBNull.Value); - command.Parameters.AddWithValue("@SavePoint", accountData.SavePoint ?? (object)DBNull.Value); - command.Parameters.AddWithValue("@UserQQ", accountData.UserQQ ?? (object)DBNull.Value); - command.Parameters.AddWithValue("@HeadColor", accountData.HeadColor ?? (object)DBNull.Value); - command.Parameters.AddWithValue("@Mode", accountData.Mode); - command.Parameters.AddWithValue("@Phase", accountData.Phase); - command.Parameters.AddWithValue("@Custom", accountData.Custom ?? (object)DBNull.Value); - command.ExecuteNonQuery(); - } - - public static void Update(AccountData accountData) - { - using MySqlConnection connection = new(GlobalArea.ConnectionStringWithDbName); - connection.Open(); - var query = @"UPDATE account_data SET user_name = @UserName, pass_word = @Password, map_layer = @MapLayer, default_a1 = @DefaultA1, save_point = @SavePoint, user_qq = @UserQQ, head_color = @HeadColor, mode = @Mode, phase = @Phase, custom = @Custom - WHERE user_email = @UserEmail"; - using var command = new MySqlCommand(query, connection); - command.Parameters.AddWithValue("@UserEmail", accountData.UserEmail); - command.Parameters.AddWithValue("@UserName", accountData.UserName); - command.Parameters.AddWithValue("@Password", accountData.Password); - command.Parameters.AddWithValue("@MapLayer", accountData.MapLayer ?? (object)DBNull.Value); - command.Parameters.AddWithValue("@DefaultA1", accountData.DefaultA1 ?? (object)DBNull.Value); - command.Parameters.AddWithValue("@SavePoint", accountData.SavePoint ?? (object)DBNull.Value); - command.Parameters.AddWithValue("@UserQQ", accountData.UserQQ ?? (object)DBNull.Value); - command.Parameters.AddWithValue("@HeadColor", accountData.HeadColor ?? (object)DBNull.Value); - command.Parameters.AddWithValue("@Mode", accountData.Mode); - command.Parameters.AddWithValue("@Phase", accountData.Phase); - command.Parameters.AddWithValue("@Custom", accountData.Custom ?? (object)DBNull.Value); - command.ExecuteNonQuery(); - } - - public static void Delete(string userEmail) - { - using MySqlConnection connection = new(GlobalArea.ConnectionStringWithDbName); - connection.Open(); - var query = @"DELETE FROM account_data WHERE user_email = @UserEmail"; - using var command = new MySqlCommand(query, connection); - command.Parameters.AddWithValue("@UserEmail", userEmail); - command.ExecuteNonQuery(); - } - - public static AccountData? Get(string userEmail) - { - using MySqlConnection connection = new(GlobalArea.ConnectionStringWithDbName); - connection.Open(); - var query = @"SELECT user_email, user_name, pass_word, map_layer, default_a1, save_point, user_qq, head_color, mode, phase, custom - FROM account_data WHERE user_email = @UserEmail"; - using var command = new MySqlCommand(query, connection); - command.Parameters.AddWithValue("@UserEmail", userEmail); - using var reader = command.ExecuteReader(); - if (reader.Read()) - { - return new AccountData - { - UserEmail = reader.GetString("user_email"), - UserName = reader.GetString("user_name"), - Password = reader.GetString("pass_word"), - MapLayer = reader["map_layer"] as int?, - DefaultA1 = reader["default_a1"] as string, - SavePoint = reader["save_point"] as string, - UserQQ = reader["user_qq"] as string, - HeadColor = reader["head_color"] as string, - Mode = reader.GetInt32("mode"), - Phase = reader.GetInt32("phase"), - Custom = reader["custom"] as string, - }; - } - return null; - } - - } -} \ No newline at end of file diff --git a/DbClass/BaseObject.cs b/DbClass/BaseObject.cs new file mode 100644 index 0000000..d913388 --- /dev/null +++ b/DbClass/BaseObject.cs @@ -0,0 +1,255 @@ +using System.Reflection; +using MySql.Data.MySqlClient; +using OMS.NET.Common; +namespace OMS.NET.DbClass +{ + [AttributeUsage(AttributeTargets.Class, Inherited = false)] + public class TableAttribute : Attribute + { + public string TableName { get; } + public TableAttribute(string tableName) + { + TableName = tableName; + } + } + + [AttributeUsage(AttributeTargets.Property, Inherited = false)] + public class ColumnAttribute : Attribute + { + public string ColumnName { get; } + public bool IsPrimaryKey { get; } + + public bool IsIdentity { get; } // 是否自增列 + public ColumnAttribute(string columnName, bool isPrimaryKey = false, bool isIdentity = false) + { + ColumnName = columnName; + IsPrimaryKey = isPrimaryKey; + IsIdentity = isIdentity; + } + } + public class BaseObject + { + private static string GetTableName(Type type) + { + var attr = type.GetCustomAttribute(); + return attr?.TableName ?? throw new Exception($"{type.Name} 没有指定数据表"); + } + + private static IEnumerable GetProperties(Type type) + { + return type.GetProperties() + .Where(p => p.GetCustomAttribute() != null); + } + + private static PropertyInfo GetPrimaryKeyProperties(Type type) + { + var primaryKeyProperties = GetProperties(type) + .Where(p => p.GetCustomAttribute()?.IsPrimaryKey == true) + .ToList(); + + if (primaryKeyProperties.Count == 0) + { + throw new InvalidOperationException("No primary key defined for the class."); + } + + if (primaryKeyProperties.Count != 1) + { + throw new InvalidOperationException("Multiple primary keys defined for the class. Only one primary key is allowed."); + } + + return primaryKeyProperties.First(); + } + + private static IEnumerable GetNonKeyProperties(Type type) + { + return GetProperties(type) + .Where(p => p.GetCustomAttribute()?.IsPrimaryKey == false); + } + + private static PropertyInfo? GetIdentityKeyProperty(Type type) + { + var primaryKey = GetPrimaryKeyProperties(type); + return (primaryKey.GetCustomAttribute()!.IsIdentity == true) ? null : primaryKey; + } + + private static string GetInsertSql(Type type) + { + var tableName = GetTableName(type); + var identityKey = GetIdentityKeyProperty(type); + var columns = GetNonKeyProperties(type) + .Select(p => p.GetCustomAttribute()!.ColumnName).ToList(); + var values = GetNonKeyProperties(type) + .Select(p => "@" + p.Name).ToList(); + + if (identityKey != null) + { + // Exclude the identity key from columns and values for insert statement + columns.Add(identityKey.GetCustomAttribute()!.ColumnName); + values.Add("@" + identityKey.Name); + } + + return $"INSERT INTO {tableName} ({string.Join(", ", columns)}) VALUES ({string.Join(", ", values)})"; + } + + private static string GetUpdateSql(Type type) + { + var tableName = GetTableName(type); + var setClause = string.Join(", ", + GetNonKeyProperties(type) + .Select(p => $"{p.GetCustomAttribute()!.ColumnName} = @{p.Name}")); + var primaryKey = GetPrimaryKeyProperties(type); + var whereClause = $"{primaryKey.GetCustomAttribute()!.ColumnName} = @{primaryKey.Name}"; + + return $"UPDATE {tableName} SET {setClause} WHERE {whereClause}"; + } + + private static string GetDeleteSql(Type type) + { + var tableName = GetTableName(type); + var primaryKey = GetPrimaryKeyProperties(type); + var whereClause = $"{primaryKey.GetCustomAttribute()!.ColumnName} = @{primaryKey.Name}"; + + return $"DELETE FROM {tableName} WHERE {whereClause}"; + } + + private static string GetSelectSql(Type type) + { + var tableName = GetTableName(type); + var columns = string.Join(", ", + GetProperties(type) + .Select(p => p.GetCustomAttribute()!.ColumnName)); + + return $"SELECT {columns} FROM {tableName}"; + } + + private static string GetSelectSqlWithPrimaryKey(Type type) + { + var tableName = GetTableName(type); + var columns = string.Join(", ", + GetProperties(type) + .Select(p => p.GetCustomAttribute()!.ColumnName)); + var primaryKey = GetPrimaryKeyProperties(type); + var whereClause = $"{primaryKey.GetCustomAttribute()!.ColumnName} = @{primaryKey.Name}"; + + return $"SELECT {columns} FROM {tableName} WHERE {whereClause}"; + } + + public void Test() + { + 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 SelectAll() where T : BaseObject, new() + { + var type = typeof(T); + var selectSql = GetSelectSql(type); + + using MySqlConnection connection = new(GlobalArea.ConnectionStringWithDbName); + connection.Open(); // 确保在执行命令之前打开连接 + using var command = new MySqlCommand(selectSql, connection); + using var reader = command.ExecuteReader(); + var results = new List(); + while (reader.Read()) + { + var item = new T(); + PopulateObject(reader, item); + results.Add(item); + } + return results; + } + + public static T? Get(object key) where T : BaseObject, new() + { + var type = typeof(T); + var selectSql = GetSelectSqlWithPrimaryKey(type); + using MySqlConnection connection = new(GlobalArea.ConnectionStringWithDbName); + connection.Open(); // 确保在执行命令之前打开连接 + using var command = new MySqlCommand(selectSql, connection); + var primaryKey = GetPrimaryKeyProperties(type); + command.Parameters.AddWithValue("@" + primaryKey.GetCustomAttribute()!.ColumnName, key); + using var reader = command.ExecuteReader(); + while (reader.Read()) + { + var item = new T(); + PopulateObject(reader, item); + return item; + } + return null; + } + + private void AddParameters(MySqlCommand command) + { + foreach (var property in GetProperties(GetType())) + { + //var columnAttr = property.GetCustomAttribute()!; + command.Parameters.AddWithValue("@" + property.Name, property.GetValue(this)); + } + } + + private IEnumerable 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()!; + var value = reader[columnAttr.ColumnName]; + if (value != DBNull.Value) + { + property.SetValue(obj, Convert.ChangeType(value, property.PropertyType)); + } + } + } + } +} \ No newline at end of file diff --git a/DbClass/Map.cs b/DbClass/Map.cs new file mode 100644 index 0000000..cb23cc9 --- /dev/null +++ b/DbClass/Map.cs @@ -0,0 +1,28 @@ +namespace OMS.NET.DbClass +{ + [Table("map_data")] + public class Map : BaseObject + { + [Column("id", true)] // Primary Key and Identity false + public string Id { get; set; } + + [Column("name")] + public string Name { get; set; } + + [Column("description")] + public string Description { get; set; } + + public Map() + { + Id = ""; + Name = ""; + Description = ""; + } + public Map(string key, string name, string description) + { + Id = key; + Name = name; + Description = description; + } + } +} \ No newline at end of file diff --git a/DbClass/MapData.cs b/DbClass/MapData.cs deleted file mode 100644 index 244674c..0000000 --- a/DbClass/MapData.cs +++ /dev/null @@ -1,155 +0,0 @@ -using MySql.Data.MySqlClient; - -namespace OMS.NET.DbClass -{ - public class MapData - { - #region base - public long Id { get; set; } - public string Type { get; set; } - public string Points { get; set; } - public string Point { get; set; } - public string? Color { get; set; } - public int Phase { get; set; } - public int? Width { get; set; } - public string? ChildRelations { get; set; } - public string? FatherRelations { get; set; } - public string? ChildNodes { get; set; } - public string? FatherNode { get; set; } - public string? Details { get; set; } - public string? Custom { get; set; } - - public MapData() - { - this.Id = -1; - this.Type = ""; - this.Points = ""; - this.Point = ""; - this.Phase = 1; - } - #endregion - - public static void Add(MapData mapData) - { - using MySqlConnection connection = new(GlobalArea.ConnectionStringWithDbName); - connection.Open(); - var query = @"INSERT INTO map_0_data (type, points, point, color, phase, width, child_relations, father_relations, child_nodes, father_node, details, custom) - VALUES (@Type, @Points, @Point, @Color, @Phase, @Width, @ChildRelations, @FatherRelations, @ChildNodes, @FatherNode, @Details, @Custom)"; - using MySqlCommand command = new(query, connection); - command.Parameters.AddWithValue("@Type", mapData.Type); - command.Parameters.AddWithValue("@Points", mapData.Points); - command.Parameters.AddWithValue("@Point", mapData.Point); - command.Parameters.AddWithValue("@Color", mapData.Color ?? (object)DBNull.Value); - command.Parameters.AddWithValue("@Phase", mapData.Phase); - command.Parameters.AddWithValue("@Width", mapData.Width ?? (object)DBNull.Value); - command.Parameters.AddWithValue("@ChildRelations", mapData.ChildRelations ?? (object)DBNull.Value); - command.Parameters.AddWithValue("@FatherRelations", mapData.FatherRelations ?? (object)DBNull.Value); - command.Parameters.AddWithValue("@ChildNodes", mapData.ChildNodes ?? (object)DBNull.Value); - command.Parameters.AddWithValue("@FatherNode", mapData.FatherNode ?? (object)DBNull.Value); - command.Parameters.AddWithValue("@Details", mapData.Details ?? (object)DBNull.Value); - command.Parameters.AddWithValue("@Custom", mapData.Custom ?? (object)DBNull.Value); - command.ExecuteNonQuery(); - mapData.Id = command.LastInsertedId; - } - - public static int Update(MapData mapData) - { - using MySqlConnection connection = new(GlobalArea.ConnectionStringWithDbName); - connection.Open(); - var query = @"UPDATE map_0_data SET type = @Type, points = @Points, point = @Point, color = @Color, phase = @Phase, width = @Width, - child_relations = @ChildRelations, father_relations = @FatherRelations, child_nodes = @ChildNodes, father_node = @FatherNode, - details = @Details, custom = @Custom WHERE id = @Id"; - using MySqlCommand command = new(query, connection); - command.Parameters.AddWithValue("@Id", mapData.Id); - command.Parameters.AddWithValue("@Type", mapData.Type); - command.Parameters.AddWithValue("@Points", mapData.Points); - command.Parameters.AddWithValue("@Point", mapData.Point); - command.Parameters.AddWithValue("@Color", mapData.Color ?? (object)DBNull.Value); - command.Parameters.AddWithValue("@Phase", mapData.Phase); - command.Parameters.AddWithValue("@Width", mapData.Width ?? (object)DBNull.Value); - command.Parameters.AddWithValue("@ChildRelations", mapData.ChildRelations ?? (object)DBNull.Value); - command.Parameters.AddWithValue("@FatherRelations", mapData.FatherRelations ?? (object)DBNull.Value); - command.Parameters.AddWithValue("@ChildNodes", mapData.ChildNodes ?? (object)DBNull.Value); - command.Parameters.AddWithValue("@FatherNode", mapData.FatherNode ?? (object)DBNull.Value); - command.Parameters.AddWithValue("@Details", mapData.Details ?? (object)DBNull.Value); - command.Parameters.AddWithValue("@Custom", mapData.Custom ?? (object)DBNull.Value); - return command.ExecuteNonQuery(); - } - - public static void Delete(long id) - { - using MySqlConnection connection = new(GlobalArea.ConnectionStringWithDbName); - connection.Open(); - var query = @"DELETE FROM map_0_data WHERE id = @Id"; - using MySqlCommand command = new(query, connection); - command.Parameters.AddWithValue("@Id", id); - command.ExecuteNonQuery(); - } - - public static MapData? Get(long id) - { - using MySqlConnection connection = new(GlobalArea.ConnectionStringWithDbName); - connection.Open(); - var query = @"SELECT id, type, points, point, color, phase, width, child_relations, father_relations, child_nodes, father_node, details, custom - FROM map_0_data WHERE id = @Id"; - using MySqlCommand command = new(query, connection); - command.Parameters.AddWithValue("@Id", id); - using MySqlDataReader reader = command.ExecuteReader(); - if (reader.Read()) - { - return new MapData - { - Id = reader.GetInt64("id"), - Type = reader.GetString("type"), - Points = reader.GetString("points"), - Point = reader.GetString("point"), - Color = reader["color"] as string, - Phase = reader.GetInt32("phase"), - Width = reader["width"] as int?, - ChildRelations = reader["child_relations"] as string, - FatherRelations = reader["father_relations"] as string, - ChildNodes = reader["child_nodes"] as string, - FatherNode = reader["father_node"] as string, - Details = reader["details"] as string, - Custom = reader["custom"] as string - }; - } - return null; - } - - public static List GetMapDataList() - { - List mapDataList = new(); - using MySqlConnection connection = new(GlobalArea.ConnectionStringWithDbName); - connection.Open(); - var query = @"SELECT * FROM map_0_data"; - using var command = new MySqlCommand(query, connection); - using var reader = command.ExecuteReader(); - if (reader.HasRows) - { - while (reader.Read()) - { - var mapData = new MapData - { - Id = reader.GetInt64("id"), - Type = reader.GetString("type"), - Points = reader.GetString("points"), - Point = reader.GetString("point"), - Color = reader.IsDBNull(reader.GetOrdinal("color")) ? null : reader.GetString("color"), - Phase = reader.GetInt32("phase"), - Width = reader.IsDBNull(reader.GetOrdinal("width")) ? (int?)null : reader.GetInt32("width"), - ChildRelations = reader.IsDBNull(reader.GetOrdinal("child_relations")) ? null : reader.GetString("child_relations"), - FatherRelations = reader.IsDBNull(reader.GetOrdinal("father_relations")) ? null : reader.GetString("father_relations"), - ChildNodes = reader.IsDBNull(reader.GetOrdinal("child_nodes")) ? null : reader.GetString("child_nodes"), - FatherNode = reader.IsDBNull(reader.GetOrdinal("father_node")) ? null : reader.GetString("father_node"), - Details = reader.IsDBNull(reader.GetOrdinal("details")) ? null : reader.GetString("details"), - Custom = reader.IsDBNull(reader.GetOrdinal("custom")) ? null : reader.GetString("custom") - }; - mapDataList.Add(mapData); - } - } - - return mapDataList; - } - } -} \ No newline at end of file diff --git a/DbClass/MapLayer.cs b/DbClass/MapLayer.cs deleted file mode 100644 index f3f810a..0000000 --- a/DbClass/MapLayer.cs +++ /dev/null @@ -1,142 +0,0 @@ -using MySql.Data.MySqlClient; - -namespace OMS.NET.DbClass -{ - public class MapLayer - { - #region base - public long Id { get; set; } - public string Type { get; set; } - public string Members { get; set; } - public string Structure { get; set; } - public int Phase { get; set; } - - public MapLayer() - { - this.Id = 0; - this.Type = ""; - this.Members = ""; - this.Structure = ""; - this.Phase = 1; - } - public MapLayer(long id, string type, string members, string structure, int phase) - { - Id = id; - Type = type; - Members = members; - Structure = structure; - Phase = phase; - } - - #endregion - public static void Add(MapLayer mapLayer) - { - using MySqlConnection connection = new(GlobalArea.ConnectionStringWithDbName); - connection.Open(); - var query = @"INSERT INTO map_0_layer (type, members, structure, phase) - VALUES (@Type, @Members, @Structure, @Phase)"; - using var command = new MySqlCommand(query, connection); - command.Parameters.AddWithValue("@Type", mapLayer.Type); - command.Parameters.AddWithValue("@Members", mapLayer.Members); - command.Parameters.AddWithValue("@Structure", mapLayer.Structure); - command.Parameters.AddWithValue("@Phase", mapLayer.Phase); - command.ExecuteNonQuery(); - mapLayer.Id = command.LastInsertedId; - } - - public static void Update(MapLayer mapLayer) - { - using MySqlConnection connection = new(GlobalArea.ConnectionStringWithDbName); - connection.Open(); - var query = @"UPDATE map_0_layer SET type = @Type, members = @Members, structure = @Structure, phase = @Phase - WHERE id = @Id"; - using var command = new MySqlCommand(query, connection); - command.Parameters.AddWithValue("@Id", mapLayer.Id); - command.Parameters.AddWithValue("@Type", mapLayer.Type); - command.Parameters.AddWithValue("@Members", mapLayer.Members); - command.Parameters.AddWithValue("@Structure", mapLayer.Structure); - command.Parameters.AddWithValue("@Phase", mapLayer.Phase); - command.ExecuteNonQuery(); - } - - public static void Delete(long id) - { - using MySqlConnection connection = new(GlobalArea.ConnectionStringWithDbName); - connection.Open(); - var query = @"DELETE FROM map_0_layer WHERE id = @Id"; - using var command = new MySqlCommand(query, connection); - command.Parameters.AddWithValue("@Id", id); - command.ExecuteNonQuery(); - } - - public static MapLayer? Get(long id) - { - using MySqlConnection connection = new(GlobalArea.ConnectionStringWithDbName); - connection.Open(); - var query = @"SELECT id, type, members, structure, phase FROM map_0_layer WHERE id = @Id"; - using var command = new MySqlCommand(query, connection); - command.Parameters.AddWithValue("@Id", id); - using var reader = command.ExecuteReader(); - if (reader.Read()) - { - return new MapLayer - { - Id = reader.GetInt64("id"), - Type = reader.GetString("type"), - Members = reader.GetString("members"), - Structure = reader.GetString("structure"), - Phase = reader.GetInt32("phase") - }; - } - return null; - } - - /// - /// 获取所有MapLayer数据 - /// - /// - public static List GetMapLayerList() - { - List mapLayerList = new(); - using MySqlConnection connection = new(GlobalArea.ConnectionStringWithDbName); - connection.Open(); - string query = "SELECT * FROM map_0_layer"; - using var command = new MySqlCommand(query, connection); - using var reader = command.ExecuteReader(); - if (reader.HasRows) - { - while (reader.Read()) - { - var mapLayer = new MapLayer - { - Id = reader.GetInt64("id"), - Type = reader.GetString("type"), - Members = reader.GetString("members"), - Structure = reader.GetString("structure"), - Phase = reader.GetInt32("phase") - }; - mapLayerList.Add(mapLayer); - } - } - return mapLayerList; - } - - /// - /// 指定是否将指定字段编码成base64格式 ??? - /// - public static void ProcessMapLayers(List mapLayers, bool encode = false) - { - mapLayers.ForEach(mapLayer => - { - if (encode) - { - - } - else - { - - } - }); - } - } -} \ No newline at end of file diff --git a/Instructs/GetMapDataInstruct.cs b/Instructs/GetMapDataInstruct.cs index bb4041a..9904449 100644 --- a/Instructs/GetMapDataInstruct.cs +++ b/Instructs/GetMapDataInstruct.cs @@ -1,4 +1,4 @@ -using OMS.NET.DbClass; +using OMS.NET.Common; namespace OMS.NET.Instructs { @@ -15,12 +15,7 @@ namespace OMS.NET.Instructs { if (GlobalArea.LoginCheckByID(wsid)) { - List mapDatas = MapData.GetMapDataList().Where(m => m.Phase != 2).ToList(); - this.ResponseOrBroadcastInstructs.Add(new SendMapDataInstruct() - { - IsResponse = true, - Data = mapDatas - }); + } }); } diff --git a/Instructs/GetMapLayerInstruct.cs b/Instructs/GetMapLayerInstruct.cs index b91d681..1916a7f 100644 --- a/Instructs/GetMapLayerInstruct.cs +++ b/Instructs/GetMapLayerInstruct.cs @@ -1,4 +1,4 @@ -using OMS.NET.DbClass; +using OMS.NET.Common; namespace OMS.NET.Instructs { @@ -15,12 +15,7 @@ namespace OMS.NET.Instructs { if (GlobalArea.LoginCheckByID(wsid)) { - List mapLayers = MapLayer.GetMapLayerList().Where(m => m.Phase != 2).ToList(); - this.ResponseOrBroadcastInstructs.Add(new SendMapLayerInstruct() - { - IsResponse = true, - Data = mapLayers - }); + } }); } diff --git a/Instructs/GetPublickeyInstruct.cs b/Instructs/GetPublickeyInstruct.cs index 9e6d02a..1d49a79 100644 --- a/Instructs/GetPublickeyInstruct.cs +++ b/Instructs/GetPublickeyInstruct.cs @@ -1,3 +1,5 @@ +using OMS.NET.Common; + namespace OMS.NET.Instructs { public class GetPublickeyInstruct : Instruct diff --git a/Instructs/GetUserDataInstruct.cs b/Instructs/GetUserDataInstruct.cs index 6131274..85ae581 100644 --- a/Instructs/GetUserDataInstruct.cs +++ b/Instructs/GetUserDataInstruct.cs @@ -1,4 +1,4 @@ -using OMS.NET.DbClass; +using OMS.NET.Common; namespace OMS.NET.Instructs { @@ -16,23 +16,6 @@ namespace OMS.NET.Instructs if (GlobalArea.LoginCheckByID(wsid)) { string userEmail = GlobalArea.UserConnects.First(u => u.ID == wsid).UserEmail!; - AccountData accountData = GlobalArea.GetLoginAccountData(userEmail)!; - this.ResponseOrBroadcastInstructs.Add(new SendUserDataInstruct() - { - IsResponse = true, - Data = new - { - user_email = accountData.UserEmail, - user_name = accountData.UserName, - map_layer = accountData.MapLayer, - default_a1 = accountData.DefaultA1, - save_point = accountData.SavePoint, - head_color = accountData.HeadColor, - mode = accountData.Mode, - phase = accountData.Phase, - custom = accountData.Custom, - } - }); } }); } diff --git a/Instructs/Instruct.cs b/Instructs/Instruct.cs index 10f3ff8..7ee3722 100644 --- a/Instructs/Instruct.cs +++ b/Instructs/Instruct.cs @@ -1,6 +1,7 @@ using System.Diagnostics; using System.Text.Json; using System.Text.Json.Serialization; +using OMS.NET.Common; namespace OMS.NET.Instructs { @@ -43,29 +44,14 @@ namespace OMS.NET.Instructs { //实现新指令需在这里添加反序列化类型,限定为客户端发过来的指令类型 "get_publickey" => JsonSerializer.Deserialize(root.GetRawText(), options), - "get_serverImg" => JsonSerializer.Deserialize(root.GetRawText(), options), - "get_serverConfig" => JsonSerializer.Deserialize(root.GetRawText(), options), "login" => JsonSerializer.Deserialize(root.GetRawText(), options), "test" => JsonSerializer.Deserialize(root.GetRawText(), options), "get_userData" => JsonSerializer.Deserialize(root.GetRawText(), options), - "get_presence" => JsonSerializer.Deserialize(root.GetRawText(), options), "get_mapData" => JsonSerializer.Deserialize(root.GetRawText(), options), "get_mapLayer" => JsonSerializer.Deserialize(root.GetRawText(), options), - "ping" => JsonSerializer.Deserialize(root.GetRawText(), options), - - //广播指令 - "broadcast" => classValue switch - { - //广播指令继承结构 - "point" => JsonSerializer.Deserialize(root.GetRawText(), options), - "line" => JsonSerializer.Deserialize(root.GetRawText(), options), - "area" => JsonSerializer.Deserialize(root.GetRawText(), options), - "curve" => JsonSerializer.Deserialize(root.GetRawText(), options), - _ => JsonSerializer.Deserialize(root.GetRawText(), options) - }, _ => null - } ?? throw new JsonException($"{typeValue} 反序列化失败"); - return instruct; + }; + return instruct ?? throw new JsonException($"{typeValue} 反序列化失败"); } else { @@ -144,7 +130,7 @@ namespace OMS.NET.Instructs stopWatch.Start(); await Handler(wsid); stopWatch.Stop(); - GlobalArea.Log.Debug($"处理{this.GetType()}耗时:{stopWatch.ElapsedMilliseconds}ms"); + Log.Debug($"处理{this.GetType()}耗时:{stopWatch.ElapsedMilliseconds}ms"); } public string ToJsonString() @@ -160,7 +146,7 @@ namespace OMS.NET.Instructs } catch (Exception ex) { - GlobalArea.Log.Error(ex.Message); + Log.Error(ex.Message); return null; } } diff --git a/Instructs/LoginInstruct.cs b/Instructs/LoginInstruct.cs index e8a78f2..58cf9ae 100644 --- a/Instructs/LoginInstruct.cs +++ b/Instructs/LoginInstruct.cs @@ -1,6 +1,6 @@ using System.Text.Json; -using OMS.NET.DbClass; +using OMS.NET.Common; namespace OMS.NET.Instructs { @@ -24,47 +24,9 @@ namespace OMS.NET.Instructs string password = this.Data.GetProperty("password").GetString(); if (string.IsNullOrEmpty(email) || string.IsNullOrEmpty(password)) { - GlobalArea.Log.Warn("登录信息不能为空!"); + Log.Warn("登录信息不能为空!"); return; } - //能够获取到则说明客户端有发送数据过来 - Instruct res1 = new LoginStatusInstuct - { - Data = false, - IsResponse = true - };//默认为false - //Console.WriteLine($"已获取到{email}:{password},解密测试{GlobalArea.DecryptFromBase64String(password)}"); - AccountData? accountData = AccountData.Get(email); - GlobalArea.AddLoginAccountData(accountData); - if (accountData != null) - { - //只能原文比较,密文每次都不一样,涉及随机性填充 - if (accountData.Password == GlobalArea.DecryptFromBase64String(password)) - { - res1.Data = true;//登录成功则修改为true - this.ResponseOrBroadcastInstructs.Add(res1); - GlobalArea.Log.Info($"{accountData.UserEmail}:登录成功"); - GlobalArea.Login(wsid, accountData.UserEmail); - GlobalArea.Log.Info($"当前登录用户数量: {GlobalArea.LoginUserCount}"); - this.ResponseOrBroadcastInstructs.Add(new Instruct - { - Type = "broadcast", - Class = "logIn", - Data = new - { - userEmail = accountData.UserEmail, - userName = accountData.UserName, - headColor = accountData.HeadColor, - userQq = accountData.UserQQ, - }, - IsBroadcast = true - }); - } - else - { - this.ResponseOrBroadcastInstructs.Add(res1); - } - } } }); } diff --git a/Instructs/TestInstuct.cs b/Instructs/TestInstuct.cs index 90b4821..d1e4c80 100644 --- a/Instructs/TestInstuct.cs +++ b/Instructs/TestInstuct.cs @@ -1,3 +1,5 @@ +using OMS.NET.Common; + namespace OMS.NET.Instructs { /// @@ -15,8 +17,8 @@ namespace OMS.NET.Instructs return Task.Run(() => { //GlobalArea.UserConnects.Where(x => x.ID == wsid).First().UserEmail = "xxx@xx.com";//login - GlobalArea.Log.Info("当前客户端连接数:" + GlobalArea.ConnectClientsCount); - GlobalArea.Log.Info("当前登录用户数:" + GlobalArea.LoginUserCount); + Log.Info("当前客户端连接数:" + GlobalArea.ConnectClientsCount); + Log.Info("当前登录用户数:" + GlobalArea.LoginUserCount); }); } } diff --git a/OMS.NET.csproj b/OMS.NET.csproj index 06a87c5..61a0ea2 100644 --- a/OMS.NET.csproj +++ b/OMS.NET.csproj @@ -19,8 +19,5 @@ Always - - Always - diff --git a/Program.cs b/Program.cs index 77303e0..a60b224 100644 --- a/Program.cs +++ b/Program.cs @@ -1,6 +1,7 @@ using WebSocketSharp.Server; using MySql.Data.MySqlClient; using OMS.NET.Common; +using OMS.NET.DbClass; namespace OMS.NET { @@ -10,35 +11,7 @@ namespace OMS.NET { try { - GlobalArea.LoadServerConfig();//加载服务器配置 默认server.yaml - GlobalArea.LoadRsaPkey();//加载rsa私钥 默认.pkey - DbCheck(); - - //开启ws监听 - var wssv = new WebSocketServer(Convert.ToInt16(GlobalArea.ServerConfig.ListenPort), false); - //wssv.SslConfiguration.ServerCertificate = new X509Certificate2(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "server.pfx")); - wssv.AddWebSocketService("/"); - wssv.Start(); - Console.WriteLine("已开启ws监听, 端口: " + GlobalArea.ServerConfig.ListenPort); - Console.WriteLine("输入exit退出程序"); - - bool loopFlag = true; - while (loopFlag) - { - string input = Console.ReadLine() ?? ""; - switch (input.Trim()) - { - case "exit": - loopFlag = false; - break; - case "logins": - Console.WriteLine("当前登录用户 " + GlobalArea.LoginUserCount); - break; - default: - break; - } - } - wssv.Stop(); + MainLoop(); } catch (Exception e) { @@ -100,5 +73,38 @@ namespace OMS.NET Log.Info("满足预设条件,跳过数据库检查"); } } + + static void MainLoop() + { + GlobalArea.LoadServerConfig();//加载服务器配置 默认server.yaml + GlobalArea.LoadRsaPkey();//加载rsa私钥 默认.pkey + DbCheck(); + + //开启ws监听 + var wssv = new WebSocketServer(Convert.ToInt16(GlobalArea.ServerConfig.ListenPort), false); + //wssv.SslConfiguration.ServerCertificate = new X509Certificate2(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "server.pfx")); + wssv.AddWebSocketService("/"); + wssv.Start(); + Console.WriteLine("已开启ws监听, 端口: " + GlobalArea.ServerConfig.ListenPort); + Console.WriteLine("输入exit退出程序"); + + bool loopFlag = true; + while (loopFlag) + { + string input = Console.ReadLine() ?? ""; + switch (input.Trim()) + { + case "exit": + loopFlag = false; + break; + case "logins": + Console.WriteLine("当前登录用户 " + GlobalArea.LoginUserCount); + break; + default: + break; + } + } + wssv.Stop(); + } } } diff --git a/init.sql b/init.sql index 06ec3fc..1194ce8 100644 --- a/init.sql +++ b/init.sql @@ -1,40 +1,6 @@ -CREATE TABLE IF NOT EXISTS map_0_data ( - id BIGINT(20) NOT NULL AUTO_INCREMENT, - type VARCHAR(12) NOT NULL, - points MEDIUMTEXT NOT NULL, - point VARCHAR(255) NOT NULL, - color VARCHAR(255), - phase INT(1) NOT NULL, - width INT(11), - child_relations MEDIUMTEXT, - father_relations VARCHAR(255), - child_nodes MEDIUMTEXT, - father_node VARCHAR(255), - details MEDIUMTEXT, - custom MEDIUMTEXT, +CREATE TABLE IF NOT EXISTS map_data ( + id VARCHAR(255) NOT NULL, + name VARCHAR(255) NOT NULL, + description VARCHAR(255) NOT NULL, PRIMARY KEY (id) -); - -CREATE TABLE IF NOT EXISTS map_0_layer ( - id BIGINT(20) NOT NULL AUTO_INCREMENT, - type VARCHAR(255) NOT NULL, - members MEDIUMTEXT NOT NULL, - structure MEDIUMTEXT NOT NULL, - phase INT(1) NOT NULL, - PRIMARY KEY (id) -); - -CREATE TABLE IF NOT EXISTS account_data ( - user_email VARCHAR(255) NOT NULL, - user_name VARCHAR(255) NOT NULL, - pass_word VARCHAR(255) NOT NULL, - map_layer INT(11), - default_a1 VARCHAR(255), - save_point MEDIUMTEXT, - user_qq VARCHAR(255), - head_color VARCHAR(6), - mode INT(1) NOT NULL, - phase INT(1) NOT NULL, - custom MEDIUMTEXT, - PRIMARY KEY (user_email) ); \ No newline at end of file