zoulei 10 miesięcy temu
rodzic
commit
b6f5fb9410

+ 201 - 0
XdCxRhDW.App/CpuMonitor.cs

@@ -0,0 +1,201 @@
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Threading;
+using System.IO;
+using System.Text;
+using System.Management;
+using System.Runtime.InteropServices;
+using XdCxRhDW.App;
+
+namespace XdCxRhDW.App
+{
+    public class CpuMonitor
+    {
+        private int m_ProcessorCount = 0;   //CPU个数
+        private PerformanceCounter pcCpuLoad;   //CPU计数器
+        private long m_PhysicalMemory = 0;   //物理内存
+
+        private const int GW_HWNDFIRST = 0;
+        private const int GW_HWNDNEXT = 2;
+        private const int GWL_STYLE = (-16);
+        private const int WS_VISIBLE = 268435456;
+        private const int WS_BORDER = 8388608;
+
+        #region AIP声明
+        [DllImport("IpHlpApi.dll")]
+        extern static public uint GetIfTable(byte[] pIfTable, ref uint pdwSize, bool bOrder);
+
+        [DllImport("User32")]
+        private extern static int GetWindow(int hWnd, int wCmd);
+
+        [DllImport("User32")]
+        private extern static int GetWindowLongA(int hWnd, int wIndx);
+
+        [DllImport("user32.dll")]
+        private static extern bool GetWindowText(int hWnd, StringBuilder title, int maxBufSize);
+
+        [DllImport("user32", CharSet = CharSet.Auto)]
+        private extern static int GetWindowTextLength(IntPtr hWnd);
+        #endregion
+
+        #region 构造函数
+        /// <summary>
+        /// 构造函数,初始化计数器等
+        /// </summary>
+        public CpuMonitor()
+        {
+            //初始化CPU计数器
+            pcCpuLoad = new PerformanceCounter("Processor", "% Processor Time", "_Total");
+            pcCpuLoad.MachineName = ".";
+            pcCpuLoad.NextValue();
+
+            //CPU个数
+            m_ProcessorCount = Environment.ProcessorCount;
+
+            //获得物理内存
+            ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
+            ManagementObjectCollection moc = mc.GetInstances();
+            foreach (ManagementObject mo in moc)
+            {
+                if (mo["TotalPhysicalMemory"] != null)
+                {
+                    m_PhysicalMemory = long.Parse(mo["TotalPhysicalMemory"].ToString());
+                }
+            }
+        }
+        #endregion
+
+        #region CPU个数
+        /// <summary>
+        /// 获取CPU个数
+        /// </summary>
+        public int ProcessorCount
+        {
+            get
+            {
+                return m_ProcessorCount;
+            }
+        }
+        #endregion
+
+        #region CPU占用率
+        /// <summary>
+        /// 获取CPU占用率
+        /// </summary>
+        public float CpuLoad
+        {
+            get
+            {
+                return pcCpuLoad.NextValue();
+            }
+        }
+        #endregion
+
+        #region 可用内存
+        /// <summary>
+        /// 获取可用内存
+        /// </summary>
+        public long MemoryAvailable
+        {
+            get
+            {
+                long availablebytes = 0;
+                //ManagementObjectSearcher mos = new ManagementObjectSearcher("SELECT * FROM Win32_PerfRawData_PerfOS_Memory");
+                //foreach (ManagementObject mo in mos.Get())
+                //{
+                //    availablebytes = long.Parse(mo["Availablebytes"].ToString());
+                //}
+                ManagementClass mos = new ManagementClass("Win32_OperatingSystem");
+                foreach (ManagementObject mo in mos.GetInstances())
+                {
+                    if (mo["FreePhysicalMemory"] != null)
+                    {
+                        availablebytes = 1024 * long.Parse(mo["FreePhysicalMemory"].ToString());
+                    }
+                }
+                return availablebytes;
+            }
+        }
+        #endregion
+
+        #region 物理内存
+        /// <summary>
+        /// 获取物理内存
+        /// </summary>
+        public long PhysicalMemory
+        {
+            get
+            {
+                return m_PhysicalMemory;
+            }
+        }
+        #endregion
+
+        #region 结束指定进程
+        /// <summary>
+        /// 结束指定进程
+        /// </summary>
+        /// <param name="pid">进程的 Process ID</param>
+        public static void EndProcess(int pid)
+        {
+            try
+            {
+                Process process = Process.GetProcessById(pid);
+                process.Kill();
+            }
+            catch { }
+        }
+        #endregion
+
+
+        public int ProcessThread()
+        {
+            return Process.GetCurrentProcess().Threads.Count;
+        }
+
+        public long ProcessMemory()
+        {
+            return Process.GetCurrentProcess().PrivateMemorySize64;
+        }
+
+        #region 查找所有应用程序标题
+        /// <summary>
+        /// 查找所有应用程序标题
+        /// </summary>
+        /// <returns>应用程序标题范型</returns>
+        public static List<string> FindAllApps(int Handle)
+        {
+            List<string> Apps = new List<string>();
+
+            int hwCurr;
+            hwCurr = GetWindow(Handle, GW_HWNDFIRST);
+
+            while (hwCurr > 0)
+            {
+                int IsTask = (WS_VISIBLE | WS_BORDER);
+                int lngStyle = GetWindowLongA(hwCurr, GWL_STYLE);
+                bool TaskWindow = ((lngStyle & IsTask) == IsTask);
+                if (TaskWindow)
+                {
+                    int length = GetWindowTextLength(new IntPtr(hwCurr));
+                    StringBuilder sb = new StringBuilder(2 * length + 1);
+                    GetWindowText(hwCurr, sb, sb.Capacity);
+                    string strTitle = sb.ToString();
+                    if (!string.IsNullOrEmpty(strTitle))
+                    {
+                        Apps.Add(strTitle);
+                    }
+                }
+                hwCurr = GetWindow(hwCurr, GW_HWNDNEXT);
+            }
+
+            return Apps;
+        }
+        #endregion
+    }
+
+}
+
+
+

+ 53 - 8
XdCxRhDW.App/MainForm.cs

@@ -32,6 +32,8 @@ using DevExpress.Utils.Extensions;
 using System.Net;
 using XdCxRhDW.WebApi;
 using XdCxRhDW.DataEmulation;
+using DxHelper;
+using System.Runtime.InteropServices;
 
 namespace XdCxRhDW
 {
@@ -59,9 +61,17 @@ namespace XdCxRhDW
             ctrlTypes.Add("信号仿真", typeof(SignalEmulation));
             ctrlTypes.Add("服务状态", typeof(CtrlSvrs));
             ctrlTypes.Add("服务日志", typeof(CtrlSvrLog));
-            using (RHDWLogContext db = new RHDWLogContext())
+
+        }
+        private string text;
+        private async void MainForm_Load(object sender, EventArgs e)
+        {
+            this.text = this.Text;
+            this.HtmlText = $"<size=12>{this.text}";
+            if (!CheckDb())
             {
-                var qq = db.LogRes.ToList();
+                Application.Exit();
+                return;
             }
             using (RHDWContext db = new RHDWContext())
             {
@@ -73,12 +83,6 @@ namespace XdCxRhDW
             }
             btn_ItemClick(null, null);
             ServerContext.Instance.Init();
-        }
-        private string text;
-        private async void MainForm_Load(object sender, EventArgs e)
-        {
-            this.text = this.Text;
-            this.HtmlText = $"<size=12>{this.text}";
             if (SysConfig.Config == null)
             {
                 var size = new Size(500, 600);
@@ -103,8 +107,49 @@ namespace XdCxRhDW
             _ = XlClear();
             _ = ClearLocalFile();
             _ = ClearLog();
+            _ = MonitorCpuAndMemory();
             await XlLonCalc();
         }
+        private Task MonitorCpuAndMemory()
+        {
+            return Task.Run(() =>
+            {
+                try
+                {
+                    int interval = 10000;
+                    CpuMonitor sys = new CpuMonitor();
+                    const int GB_DIV = 1024 * 1024 * 1024;
+                    while (true)
+                    {
+                        //第二章方法获取系统CPU和内存使用情况
+                        LogHelper.Info($"设备CPU:{sys.CpuLoad:f1}%,设备内存:{(sys.PhysicalMemory - sys.MemoryAvailable) / GB_DIV:f2}GB/{sys.PhysicalMemory / (double)GB_DIV:f2}GB,平台内存:{sys.ProcessMemory() / (double)GB_DIV:f2}GB,平台线程:{sys.ProcessThread()}").Wait();
+                        Thread.Sleep(interval);
+                    }
+                }
+                catch
+                { }
+            });
+
+        }
+        private bool CheckDb()
+        {
+            RHDWContext db = new RHDWContext();
+            string notExistTableName = db.CheckTableExist();
+            if (!string.IsNullOrWhiteSpace(notExistTableName))
+            {
+                db.Dispose();
+                MsgBoxHelper.ShowError($"Database.db数据库中不存在表{notExistTableName}");
+                return false;
+            }
+            var errmsg = db.CheckTableField();
+            if (!string.IsNullOrWhiteSpace(errmsg))
+            {
+                db.Dispose();
+                MsgBoxHelper.ShowError(errmsg);
+                return false;
+            }
+            return true;
+        }
         private void StartWebApi()
         {
             try

+ 1 - 0
XdCxRhDW.App/XdCxRhDW.App.csproj

@@ -333,6 +333,7 @@
     <Compile Include="Model\ModelCg.cs" />
     <Compile Include="Model\ModelCgXgf.cs" />
     <Compile Include="Model\RePosRes.cs" />
+    <Compile Include="CpuMonitor.cs" />
     <Compile Include="PopupControl\ShowCgCtrl.cs">
       <SubType>UserControl</SubType>
     </Compile>

+ 126 - 9
XdCxRhDW.Repostory/EFContext/RHDWContext.cs

@@ -1,6 +1,7 @@
 using SQLite.CodeFirst;
 using System;
 using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations.Schema;
 using System.Data.Common;
 using System.Data.Entity;
 using System.Data.Entity.Core.Common;
@@ -12,13 +13,16 @@ using System.Data.SQLite;
 using System.Data.SQLite.EF6;
 using System.IO;
 using System.Linq;
+using System.Reflection;
 using System.Text.RegularExpressions;
+using System.Threading.Tasks;
 using XdCxRhDW.Entity;
 
 namespace XdCxRhDW.Repostory
 {
     public class RHDWLogContext : DbContext
     {
+
         public RHDWLogContext() : base("LogDbCon") //配置使用的连接名
         {
         }
@@ -41,18 +45,131 @@ namespace XdCxRhDW.Repostory
     /// </summary>
     public class RHDWContext : DbContext
     {
+        private class DbTableColumnInfo
+        {
+            public string name { get; set; }
+
+            public string type { get; set; }
+
+            public int notnull { get; set; }
+
+            public int pk { get; set; }
+        }
+
+        public class DbTableForeignKeyInfo
+        {
+            public string from { get; set; }
+        }
         public RHDWContext() : base("DbCon") //配置使用的连接名
         {
         }
-        //protected override DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry, IDictionary<object, object> items)
-        //{
-        //    var tables = this.Database.SqlQuery<string>("select name from sqlite_master where type='table' and  name not like 'sqlite%'").ToList();
-        //    return base.ValidateEntity(entityEntry, items);
-        //}
-        //protected override bool ShouldValidateEntity(DbEntityEntry entityEntry)
-        //{
-        //    return  base.ShouldValidateEntity(entityEntry);
-        //}
+
+        public Task<List<T>> SqlQueryAsync<T>(string sql)
+        {
+            return this.Database.SqlQuery<T>(sql).ToListAsync();
+        }
+        public Task<T> SqlQueryOneAsync<T>(string sql)
+        {
+            return this.Database.SqlQuery<T>(sql).FirstOrDefaultAsync();
+
+        }
+        //检查数据库表是否缺失
+        public string CheckTableExist()
+        {
+            var tables = this.Database.SqlQuery<string>("select name from sqlite_master where type='table' and  name not like 'sqlite%'").ToList();
+            var props = this.GetType().GetProperties();
+            List<string> list = new List<string>();
+            foreach (var prop in props)
+            {
+                bool isDbSet = prop.PropertyType.IsGenericType && typeof(DbSet<>) == prop.PropertyType.GetGenericTypeDefinition();
+                if (isDbSet)
+                {
+                    var entityType = prop.PropertyType.GenericTypeArguments[0];
+                    var name = entityType.GetCustomAttribute<TableAttribute>()?.Name;
+                    if (name == null)
+                    {
+                        name = entityType.Name;
+                    }
+                    list.Add(name);
+                }
+            }
+            foreach (var item in list)
+            {
+                if (!tables.Contains(item))
+                {
+                    return item;
+                }
+            }
+            return "";
+        }
+        public string CheckTableField()
+        {
+            var tables = this.Database.SqlQuery<string>("select name from sqlite_master where type='table' and  name not like 'sqlite%'").ToList();
+            var props = this.GetType().GetProperties();
+            List<Type> entityTypes = new List<Type>();
+            foreach (var prop in props)
+            {
+                bool isDbSet = prop.PropertyType.IsGenericType && typeof(DbSet<>) == prop.PropertyType.GetGenericTypeDefinition();
+                if (isDbSet)
+                {
+                    var entityType = prop.PropertyType.GenericTypeArguments[0];
+                    entityTypes.Add(entityType);
+                }
+            }
+            foreach (var table in tables)
+            {
+                var res = this.Database.SqlQuery<DbTableColumnInfo>($"PRAGMA table_info([{table}])").ToList();
+                var entityType = entityTypes.First(p => p.Name == table);
+                var entityProps = entityType.GetProperties().Where(p =>
+                    p.CanRead
+                    && p.CanWrite
+                    && !p.GetMethod.IsVirtual
+                    && p.GetCustomAttribute<NotMappedAttribute>() == null);
+                foreach (var prop in entityProps)
+                {
+                    var find = res.Find(p => p.name == prop.Name);
+                    if (find == null)
+                    {
+                        string typeStr = "";
+                        var type = prop.PropertyType;
+                        if (prop.PropertyType.IsGenericType)
+                        {
+                            type = prop.PropertyType.GenericTypeArguments[0];
+                        }
+                        if (type == typeof(string))
+                        {
+                            typeStr = "nvarchar";
+                        }
+                        else if (type == typeof(int) || type == typeof(long))
+                        {
+                            typeStr = "int";
+                        }
+                        else if (type == typeof(double) || type == typeof(float))
+                        {
+                            typeStr = "float";
+                        }
+                        else if (type == typeof(DateTime))
+                        {
+                            typeStr = "datetime";
+                        }
+                        return $"Database.db数据库表{table}缺少{prop.Name}字段,类型={typeStr}";
+                    }
+                    else
+                    {
+
+                        if (prop.PropertyType != typeof(string) && find.pk == 0 && !prop.PropertyType.IsGenericType && find.notnull == 0)
+                        {
+                            var foreignInfo = this.Database.SqlQuery<DbTableForeignKeyInfo>($"PRAGMA foreign_key_list({table})").ToList();
+                            if (!foreignInfo.Any(p => p.from == prop.Name))
+                            {
+                                return $"Database.db数据库表{table}中{prop.Name}字段不允许为空";
+                            }
+                        }
+                    }
+                }
+            }
+            return "";
+        }
         protected override void OnModelCreating(DbModelBuilder modelBuilder)
         {
             this.Database.Log = msg =>