소스 검색

Merge branch 'master' of http://139.155.15.221:3000/zoulei/XdCxRhDW

wyq 1 년 전
부모
커밋
c2d74ed14d

+ 0 - 4
Service/CheckServer/App.config

@@ -9,10 +9,6 @@
 
 		<!--定位平台Http地址-->
 		<add key="PosPlatformAddr" value="http://127.0.0.1:8091" />
-
-		<!--使用老板本检测=1,使用新版本检测=2,老板本无结果时使用新版本=3-->
-		<add key="DamaVersion" value="3"/>
-
 	</appSettings>
 	<startup>
 		<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />

+ 19 - 18
Service/CheckServer/Controllers/CheckController.cs

@@ -8,6 +8,7 @@ using System.Linq;
 using System.Threading.Tasks;
 using System.Web.Http;
 using XdCxRhDW.Dto;
+using XdCxRhDW.Framework;
 using XdCxRhDW.WebApi;
 
 namespace CheckServer.Controllers
@@ -51,27 +52,27 @@ namespace CheckServer.Controllers
                 List<DmcResult> kyResults = new List<DmcResult>();
                 if (dto.dmcType.HasFlag(EnumSigCheckTypeDto.DAMA))
                 {
-                    var damaVersion = ConfigurationManager.AppSettings["DamaVersion"];
-                    if (string.IsNullOrWhiteSpace(damaVersion) || damaVersion.Trim() == "1")
+                    //var damaVersion = AppConfigHelper.Get("DamaVersion");
+                    //if (string.IsNullOrWhiteSpace(damaVersion) || damaVersion.Trim() == "1")
+                    //{
+                    //    var dmcResult = await CheckHelper.DmcCheckAsync(dto.file1, dto.fsHz, EnumSigCheckTypeDto.DAMA, dto.band);
+                    //    dmcResults.AddRange(dmcResult);
+                    //}
+                    //else if (damaVersion.Trim() == "2")
+                    //{
+                    //    var dmcResult = await CheckHelper.DAMACheckAsync(dto.file1, dto.fsHz, EnumSigCheckTypeDto.DAMA, dto.band);
+                    //    dmcResults.AddRange(dmcResult);
+                    //}
+                    //else
+                    //{
+                    var dmcResult = await CheckHelper.DmcCheckAsync(dto.file1, dto.fsHz, EnumSigCheckTypeDto.DAMA, dto.band);
+                    dmcResults.AddRange(dmcResult);
+                    if (dmcResult == null || !dmcResult.Any())
                     {
-                        var dmcResult = await CheckHelper.DmcCheckAsync(dto.file1, dto.fsHz, EnumSigCheckTypeDto.DAMA, dto.band);
+                        var dmcResult2 = await CheckHelper.DAMACheckAsync(dto.file1, dto.fsHz, EnumSigCheckTypeDto.DAMA, dto.band);
                         dmcResults.AddRange(dmcResult);
                     }
-                    else if (damaVersion.Trim() == "2")
-                    {
-                        var dmcResult = await CheckHelper.DAMACheckAsync(dto.file1, dto.fsHz, EnumSigCheckTypeDto.DAMA, dto.band);
-                        dmcResults.AddRange(dmcResult);
-                    }
-                    else
-                    {
-                        var dmcResult = await CheckHelper.DmcCheckAsync(dto.file1, dto.fsHz, EnumSigCheckTypeDto.DAMA, dto.band);
-                        dmcResults.AddRange(dmcResult);
-                        if (dmcResult == null || !dmcResult.Any())
-                        {
-                            var dmcResult2 = await CheckHelper.DAMACheckAsync(dto.file1, dto.fsHz, EnumSigCheckTypeDto.DAMA, dto.band);
-                            dmcResults.AddRange(dmcResult);
-                        }
-                    }
+                    //}
 
                 }
                 if (dto.dmcType.HasFlag(EnumSigCheckTypeDto.IBS))

+ 15 - 24
Service/CheckServer/MainForm.cs

@@ -8,12 +8,14 @@ using System.Reflection;
 using System.Threading.Tasks;
 using System.Windows.Forms;
 using XdCxRhDW.Dto;
+using XdCxRhDW.Framework;
 using XdCxRhDW.WebApi;
 
 namespace CheckServer
 {
     public partial class MainForm : Form
     {
+        private EnumSvrType svrType = EnumSvrType.CheckSvr;
         public MainForm()
         {
             InitializeComponent();
@@ -49,13 +51,13 @@ namespace CheckServer
                     { }
                 }
             }
-            var port = Convert.ToInt32(ConfigurationManager.AppSettings["LocalHttpPort"].Trim());
-            var svrID = ConfigurationManager.AppSettings["SvrID"].Trim();
-            var posPlatformAddr = ConfigurationManager.AppSettings["PosPlatformAddr"].Trim();
-            LogHelper.BaseUrl = posPlatformAddr + "/api/";
-            this.Text = EnumSvrType.CheckSvr.GetEnumDisplayName() + "-" + svrID;
+            var port = AppConfigHelper.Get<int>("LocalHttpPort");
+            var svrID = AppConfigHelper.Get("SvrID");
+            var posPlatformAddr = AppConfigHelper.Get("PosPlatformAddr").AppendUrlSuffix("api/");
+            LogHelper.BaseUrl = posPlatformAddr;
+            this.Text = svrType.GetEnumDisplayName() + "-" + svrID;
             string localIp;
-            string getIpUrl = $"{posPlatformAddr}/api/task/getclientip";
+            string getIpUrl = posPlatformAddr.AppendUrlSuffix("task/getclientip");
             while (true)
             {
                 try
@@ -82,11 +84,7 @@ namespace CheckServer
             Startup.Start(port, $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}.xml", "XdCxRhDW.Dto.xml");
             await LogHelper.Info($"服务启动成功.接口地址http://{localIp}:{port}/swagger");
 
-            string url;
-            if (posPlatformAddr.EndsWith("/"))
-                url = posPlatformAddr + "api/SvrReport/Report";
-            else
-                url = posPlatformAddr + "/api/SvrReport/Report";
+            string url = posPlatformAddr.AppendUrlSuffix("SvrReport/Report");
             _ = ClearLocalFile();
             bool preSucceed = false;
             while (!this.Disposing)
@@ -95,7 +93,7 @@ namespace CheckServer
                 {
                     var res = await HttpHelper.PostRequestAsync<object>(url, new SvrStateReportDto()
                     {
-                        SvrType = EnumSvrType.CheckSvr,
+                        SvrType = svrType,
                         SvrID = svrID,
                         ReportType = 0,
                         BaseHttpAddr = $"http://{localIp}:{port}",
@@ -126,21 +124,15 @@ namespace CheckServer
         {
             try
             {
-                var port = Convert.ToInt32(ConfigurationManager.AppSettings["LocalHttpPort"].Trim());
-                var svrID = ConfigurationManager.AppSettings["SvrID"].Trim();
-                var posPlatformAddr = ConfigurationManager.AppSettings["PosPlatformAddr"].Trim();
-                string url;
-                if (posPlatformAddr.EndsWith("/"))
-                    url = posPlatformAddr + "api/SvrReport/Report";
-                else
-                    url = posPlatformAddr + "/api/SvrReport/Report";
+                var port = AppConfigHelper.Get<int>("LocalHttpPort");
+                var svrID = AppConfigHelper.Get("SvrID");
+                var posPlatformAddr = AppConfigHelper.Get("PosPlatformAddr").AppendUrlSuffix("api/");
+                string url = posPlatformAddr.AppendUrlSuffix("SvrReport/Report");
                 var localIp = IpHelper.GetLocalIp();
-
-
                 _ = HttpHelper.PostRequestAsync<object>(url, new SvrStateReportDto()
                 {
                     SvrID = svrID,
-                    SvrType = EnumSvrType.CheckSvr,
+                    SvrType = svrType,
                     ReportType = 1,
                     BaseHttpAddr = $"http://{localIp}:{port}",
                 });
@@ -152,7 +144,6 @@ namespace CheckServer
             }
         }
 
-
         //清理10分钟之前的文件
         private async Task ClearLocalFile()
         {

+ 15 - 24
Service/CpuCgServer/MainForm.cs

@@ -8,12 +8,14 @@ using System.Reflection;
 using System.Threading.Tasks;
 using System.Windows.Forms;
 using XdCxRhDW.Dto;
+using XdCxRhDW.Framework;
 using XdCxRhDW.WebApi;
 
 namespace CpuCgServer
 {
     public partial class MainForm : Form
     {
+        private EnumSvrType svrType = EnumSvrType.CpuCgSvr;
         public MainForm()
         {
             InitializeComponent();
@@ -49,13 +51,13 @@ namespace CpuCgServer
                     { }
                 }
             }
-            var port = Convert.ToInt32(ConfigurationManager.AppSettings["LocalHttpPort"].Trim());
-            var svrID = ConfigurationManager.AppSettings["SvrID"].Trim();
-            var posPlatformAddr = ConfigurationManager.AppSettings["PosPlatformAddr"].Trim();
-            LogHelper.BaseUrl = posPlatformAddr + "/api/";
-            this.Text = EnumSvrType.CpuCgSvr.GetEnumDisplayName() + "-" + svrID;
+            var port = AppConfigHelper.Get<int>("LocalHttpPort");
+            var svrID = AppConfigHelper.Get("SvrID");
+            var posPlatformAddr = AppConfigHelper.Get("PosPlatformAddr").AppendUrlSuffix("api/");
+            LogHelper.BaseUrl = posPlatformAddr;
+            this.Text = svrType.GetEnumDisplayName() + "-" + svrID;
             string localIp;
-            string getIpUrl = $"{posPlatformAddr}/api/task/getclientip";
+            string getIpUrl = posPlatformAddr.AppendUrlSuffix("task/getclientip");
             while (true)
             {
                 try
@@ -82,11 +84,7 @@ namespace CpuCgServer
             Startup.Start(port, $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}.xml", "XdCxRhDW.Dto.xml");
             await LogHelper.Info($"服务启动成功.接口地址http://{localIp}:{port}/swagger");
 
-            string url;
-            if (posPlatformAddr.EndsWith("/"))
-                url = posPlatformAddr + "api/SvrReport/Report";
-            else
-                url = posPlatformAddr + "/api/SvrReport/Report";
+            string url = posPlatformAddr.AppendUrlSuffix("SvrReport/Report");
             _ = ClearLocalFile();
             bool preSucceed = false;
             while (!this.Disposing)
@@ -95,7 +93,7 @@ namespace CpuCgServer
                 {
                     var res = await HttpHelper.PostRequestAsync<object>(url, new SvrStateReportDto()
                     {
-                        SvrType = EnumSvrType.CpuCgSvr,
+                        SvrType = svrType,
                         SvrID = svrID,
                         ReportType = 0,
                         BaseHttpAddr = $"http://{localIp}:{port}",
@@ -126,21 +124,15 @@ namespace CpuCgServer
         {
             try
             {
-                var port = Convert.ToInt32(ConfigurationManager.AppSettings["LocalHttpPort"].Trim());
-                var svrID = ConfigurationManager.AppSettings["SvrID"].Trim();
-                var posPlatformAddr = ConfigurationManager.AppSettings["PosPlatformAddr"].Trim();
-                string url;
-                if (posPlatformAddr.EndsWith("/"))
-                    url = posPlatformAddr + "api/SvrReport/Report";
-                else
-                    url = posPlatformAddr + "/api/SvrReport/Report";
+                var port = AppConfigHelper.Get<int>("LocalHttpPort");
+                var svrID = AppConfigHelper.Get("SvrID");
+                var posPlatformAddr = AppConfigHelper.Get("PosPlatformAddr").AppendUrlSuffix("api/");
+                string url = posPlatformAddr.AppendUrlSuffix("SvrReport/Report");
                 var localIp = IpHelper.GetLocalIp();
-
-
                 _ = HttpHelper.PostRequestAsync<object>(url, new SvrStateReportDto()
                 {
                     SvrID = svrID,
-                    SvrType = EnumSvrType.CpuCgSvr,
+                    SvrType = svrType,
                     ReportType = 1,
                     BaseHttpAddr = $"http://{localIp}:{port}",
                 });
@@ -152,7 +144,6 @@ namespace CpuCgServer
             }
         }
 
-
         //清理10分钟之前的文件
         private async Task ClearLocalFile()
         {

+ 15 - 24
Service/GpuCgServer/MainForm.cs

@@ -8,12 +8,14 @@ using System.Reflection;
 using System.Threading.Tasks;
 using System.Windows.Forms;
 using XdCxRhDW.Dto;
+using XdCxRhDW.Framework;
 using XdCxRhDW.WebApi;
 
 namespace GpuCgServer
 {
     public partial class MainForm : Form
     {
+        private EnumSvrType svrType = EnumSvrType.GpuCgSvr;
         public MainForm()
         {
             InitializeComponent();
@@ -49,13 +51,13 @@ namespace GpuCgServer
                     { }
                 }
             }
-            var port = Convert.ToInt32(ConfigurationManager.AppSettings["LocalHttpPort"].Trim());
-            var svrID = ConfigurationManager.AppSettings["SvrID"].Trim();
-            var posPlatformAddr = ConfigurationManager.AppSettings["PosPlatformAddr"].Trim();
-            LogHelper.BaseUrl = posPlatformAddr + "/api/";
-            this.Text = EnumSvrType.GpuCgSvr.GetEnumDisplayName() + "-" + svrID;
+            var port = AppConfigHelper.Get<int>("LocalHttpPort");
+            var svrID = AppConfigHelper.Get("SvrID");
+            var posPlatformAddr = AppConfigHelper.Get("PosPlatformAddr").AppendUrlSuffix("api/");
+            LogHelper.BaseUrl = posPlatformAddr;
+            this.Text = svrType.GetEnumDisplayName() + "-" + svrID;
             string localIp;
-            string getIpUrl = $"{posPlatformAddr}/api/task/getclientip";
+            string getIpUrl = posPlatformAddr.AppendUrlSuffix("task/getclientip");
             while (true)
             {
                 try
@@ -82,11 +84,7 @@ namespace GpuCgServer
             Startup.Start(port, $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}.xml", "XdCxRhDW.Dto.xml");
             await LogHelper.Info($"服务启动成功.接口地址http://{localIp}:{port}/swagger");
 
-            string url;
-            if (posPlatformAddr.EndsWith("/"))
-                url = posPlatformAddr + "api/SvrReport/Report";
-            else
-                url = posPlatformAddr + "/api/SvrReport/Report";
+            string url = posPlatformAddr.AppendUrlSuffix("SvrReport/Report");
             _ = ClearLocalFile();
             bool preSucceed = false;
             while (!this.Disposing)
@@ -95,7 +93,7 @@ namespace GpuCgServer
                 {
                     var res = await HttpHelper.PostRequestAsync<object>(url, new SvrStateReportDto()
                     {
-                        SvrType = EnumSvrType.GpuCgSvr,
+                        SvrType = svrType,
                         SvrID = svrID,
                         ReportType = 0,
                         BaseHttpAddr = $"http://{localIp}:{port}",
@@ -126,21 +124,15 @@ namespace GpuCgServer
         {
             try
             {
-                var port = Convert.ToInt32(ConfigurationManager.AppSettings["LocalHttpPort"].Trim());
-                var svrID = ConfigurationManager.AppSettings["SvrID"].Trim();
-                var posPlatformAddr = ConfigurationManager.AppSettings["PosPlatformAddr"].Trim();
-                string url;
-                if (posPlatformAddr.EndsWith("/"))
-                    url = posPlatformAddr + "api/SvrReport/Report";
-                else
-                    url = posPlatformAddr + "/api/SvrReport/Report";
+                var port = AppConfigHelper.Get<int>("LocalHttpPort");
+                var svrID = AppConfigHelper.Get("SvrID");
+                var posPlatformAddr = AppConfigHelper.Get("PosPlatformAddr").AppendUrlSuffix("api/");
+                string url = posPlatformAddr.AppendUrlSuffix("SvrReport/Report");
                 var localIp = IpHelper.GetLocalIp();
-
-
                 _ = HttpHelper.PostRequestAsync<object>(url, new SvrStateReportDto()
                 {
                     SvrID = svrID,
-                    SvrType = EnumSvrType.GpuCgSvr,
+                    SvrType = svrType,
                     ReportType = 1,
                     BaseHttpAddr = $"http://{localIp}:{port}",
                 });
@@ -152,7 +144,6 @@ namespace GpuCgServer
             }
         }
 
-
         //清理10分钟之前的文件
         private async Task ClearLocalFile()
         {

+ 16 - 24
Service/X2D1TaskServer/MainForm.cs

@@ -7,13 +7,16 @@ using System.Linq;
 using System.Reflection;
 using System.Threading.Tasks;
 using System.Windows.Forms;
+using X2D1TaskServer.Service;
 using XdCxRhDW.Dto;
+using XdCxRhDW.Framework;
 using XdCxRhDW.WebApi;
 
 namespace X2D1TaskServer
 {
     public partial class MainForm : Form
     {
+        private EnumSvrType svrType = EnumSvrType.X2D1NoRefTask;
         public MainForm()
         {
             InitializeComponent();
@@ -49,13 +52,13 @@ namespace X2D1TaskServer
                     { }
                 }
             }
-            var port = Convert.ToInt32(ConfigurationManager.AppSettings["LocalHttpPort"].Trim());
-            var svrID = ConfigurationManager.AppSettings["SvrID"].Trim();
-            var posPlatformAddr = ConfigurationManager.AppSettings["PosPlatformAddr"].Trim();
-            LogHelper.BaseUrl = posPlatformAddr + "/api/";
-            this.Text = EnumSvrType.X2D1NoRefTask.GetEnumDisplayName() + "-" + svrID;
+            var port = AppConfigHelper.Get<int>("LocalHttpPort");
+            var svrID = AppConfigHelper.Get("SvrID");
+            var posPlatformAddr = AppConfigHelper.Get("PosPlatformAddr").AppendUrlSuffix("api/");
+            LogHelper.BaseUrl = posPlatformAddr;
+            this.Text = svrType.GetEnumDisplayName() + "-" + svrID;
             string localIp;
-            string getIpUrl = $"{posPlatformAddr}/api/task/getclientip";
+            string getIpUrl = posPlatformAddr.AppendUrlSuffix("task/getclientip");
             while (true)
             {
                 try
@@ -82,11 +85,7 @@ namespace X2D1TaskServer
             Startup.Start(port, $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}.xml", "XdCxRhDW.Dto.xml");
             await LogHelper.Info($"服务启动成功.接口地址http://{localIp}:{port}/swagger");
 
-            string url;
-            if (posPlatformAddr.EndsWith("/"))
-                url = posPlatformAddr + "api/SvrReport/Report";
-            else
-                url = posPlatformAddr + "/api/SvrReport/Report";
+            string url = posPlatformAddr.AppendUrlSuffix("SvrReport/Report");
             _ = ClearLocalFile();
             bool preSucceed = false;
             while (!this.Disposing)
@@ -95,7 +94,7 @@ namespace X2D1TaskServer
                 {
                     var res = await HttpHelper.PostRequestAsync<object>(url, new SvrStateReportDto()
                     {
-                        SvrType = EnumSvrType.X2D1NoRefTask,
+                        SvrType = svrType,
                         SvrID = svrID,
                         ReportType = 0,
                         BaseHttpAddr = $"http://{localIp}:{port}",
@@ -126,21 +125,15 @@ namespace X2D1TaskServer
         {
             try
             {
-                var port = Convert.ToInt32(ConfigurationManager.AppSettings["LocalHttpPort"].Trim());
-                var svrID = ConfigurationManager.AppSettings["SvrID"].Trim();
-                var posPlatformAddr = ConfigurationManager.AppSettings["PosPlatformAddr"].Trim();
-                string url;
-                if (posPlatformAddr.EndsWith("/"))
-                    url = posPlatformAddr + "api/SvrReport/Report";
-                else
-                    url = posPlatformAddr + "/api/SvrReport/Report";
+                var port = AppConfigHelper.Get<int>("LocalHttpPort");
+                var svrID = AppConfigHelper.Get("SvrID");
+                var posPlatformAddr = AppConfigHelper.Get("PosPlatformAddr").AppendUrlSuffix("api/");
+                string url = posPlatformAddr.AppendUrlSuffix("SvrReport/Report");
                 var localIp = IpHelper.GetLocalIp();
-
-
                 _ = HttpHelper.PostRequestAsync<object>(url, new SvrStateReportDto()
                 {
                     SvrID = svrID,
-                    SvrType = EnumSvrType.X2D1NoRefTask,
+                    SvrType = svrType,
                     ReportType = 1,
                     BaseHttpAddr = $"http://{localIp}:{port}",
                 });
@@ -152,7 +145,6 @@ namespace X2D1TaskServer
             }
         }
 
-
         //清理10分钟之前的文件
         private async Task ClearLocalFile()
         {

+ 2 - 0
Service/X2D1TaskServer/Program.cs

@@ -9,6 +9,8 @@ using System.Reflection;
 using System.Security.Principal;
 using System.Threading.Tasks;
 using System.Windows.Forms;
+using XdCxRhDW.Framework;
+using static Org.BouncyCastle.Math.EC.ECCurve;
 
 namespace X2D1TaskServer
 {

+ 9 - 31
Service/X2D1TaskServer/Service/TaskService.cs

@@ -10,6 +10,7 @@ using System.Text;
 using System.Threading;
 using System.Threading.Tasks;
 using XdCxRhDW.Dto;
+using XdCxRhDW.Framework;
 
 namespace X2D1TaskServer.Service
 {
@@ -21,40 +22,17 @@ namespace X2D1TaskServer.Service
             try
             {
                 _config = new TaskSvrConfig();
-                var posPlatformAddr = ConfigurationManager.AppSettings["PosPlatformAddr"].Trim();//like http://127.0.0.1:8091 or http://127.0.0.1:8091/
-                if (posPlatformAddr.EndsWith("/"))
-                    _config.baseUrl = posPlatformAddr + "api/";
-                else
-                    _config.baseUrl = posPlatformAddr + "/api/";
-                var val = ConfigurationManager.AppSettings["CapSeconds"].Trim();
-                if (!int.TryParse(val, out int tempcapSeconds))
-                {
-                    tempcapSeconds = 60;
-                }
-                _config.capSeconds = tempcapSeconds;
-                string mainSatDelayStr = ConfigurationManager.AppSettings["MainSatDelay"];
-                if (!string.IsNullOrWhiteSpace(mainSatDelayStr))
-                {
-                    _config.mainSatDelay = Convert.ToDouble(mainSatDelayStr);
-                }
-                string adjaSatDelayStr = ConfigurationManager.AppSettings["AdjaSatDelay"];
-                if (!string.IsNullOrWhiteSpace(adjaSatDelayStr))
-                {
-                    _config.adjaSatDelay = Convert.ToDouble(adjaSatDelayStr);
-                }
-                _config.checkFileType = Convert.ToInt32(ConfigurationManager.AppSettings["CheckFileType"]);
-
-                int.TryParse(ConfigurationManager.AppSettings["ThreadCount"], out int tempthreadCount);
-                if (tempthreadCount < 0) tempthreadCount = 0;
-                _config.threadCount = tempthreadCount;
-                int.TryParse(ConfigurationManager.AppSettings["PosDtoFactor"], out int posDtoFactor);
-                if (posDtoFactor == 0) posDtoFactor = 1;//定位时时差系数
-                _config.posDtoFactor = posDtoFactor;
+                _config.baseUrl = AppConfigHelper.Get("PosPlatformAddr").AppendUrlSuffix("api/");
+                _config.capSeconds = AppConfigHelper.Get("CapSeconds", 60);
+                _config.mainSatDelay = AppConfigHelper.Get<double?>("MainSatDelay");
+                _config.adjaSatDelay = AppConfigHelper.Get<double?>("AdjaSatDelay");
+                _config.checkFileType = AppConfigHelper.Get("CheckFileType", 0);
+                _config.threadCount = AppConfigHelper.Get("ThreadCount", 0).NotLessThanZero();
+                _config.posDtoFactor = AppConfigHelper.Get("PosDtoFactor", 1);
             }
             catch (Exception ex)
             {
                 LogHelper.Error("读取配置文件异常", ex).Wait(5000);
-
             }
         }
 
@@ -253,7 +231,7 @@ namespace X2D1TaskServer.Service
             }
             catch (Exception ex)
             {
-                LogHelper.Warning($"【任务{taskID}】下行频点{freqdownMHz}从MySQL中查询卫星编号异常.ConnectionString={System.Configuration.ConfigurationManager.ConnectionStrings["MySql"].ConnectionString}", ex).Wait(5000);
+                LogHelper.Warning($"【任务{taskID}】下行频点{freqdownMHz}从MySQL中查询卫星编号异常.ConnectionString={ConfigurationManager.ConnectionStrings["MySql"].ConnectionString}", ex).Wait(5000);
             }
             return satId;
         }

+ 1 - 1
Service/X2D1TaskServer/Service/TaskSvrConfig.cs

@@ -26,7 +26,7 @@ namespace X2D1TaskServer.Service
         /// </summary>
         public double? adjaSatDelay { get; set; }
         /// <summary>
-        /// 检测文件类型(上行信号= 0, 主星下行信号= 1
+        /// 检测文件类型(上行信号= 0, 主星下行信号= 1)
         /// </summary>
         public int checkFileType { get; set; }
         /// <summary>

+ 9 - 6
XdCxRhDW.App/App.config

@@ -7,10 +7,10 @@
 	<appSettings>
 		<!--程序标题-->
 		<add key="SystemName" value="多模式融合定位平台" />
-		
+
 		<!--公司名称(没有则不会显示版权)-->
 		<add key="Company" value="" />
-		
+
 		<!--本机IP,没有则由程序自动获取-->
 		<add key="LocalIP" value="" />
 
@@ -20,14 +20,17 @@
 		<!--数据中心地图源URL-->
 		<add key="SJZX_URL" value="http://192.168.1.7:5889/MapServer" />
 
-		<!--地图定位点聚合-->
+		<!--取参考时间 单位:分钟-->
+		<add key="TakeRefTime" value="10" />
+
+		<!--是否启用地图定位点聚合 启用=1,禁用=0-->
 		<add key="UseMapCluster" value="0" />
 
-		<!--GDOP使用最新的版本  1:使用-->
+		<!--是否启用新版GDOP  启用=1,禁用=0-->
 		<add key="UseNewGDOP" value="1" />
 
-		<!--取参考时间 单位:分钟-->
-		<add key="TakeRefTime" value="10" />
+		<!--是否启用平台设备状态收集功能 启用=1,禁用=0-->
+		<add key="UseGatherDevState" value="0"/>
 
 	</appSettings>
 	<startup>

+ 40 - 56
XdCxRhDW.App/Controllers/PosController.cs

@@ -374,17 +374,15 @@ namespace XdCxRhDW.App.Controllers
                     return Success(MapDto(posRes));
                 }
             }
-            catch (DbUpdateException ex)
+            catch (DbUpdateException)
             {
-                string errMsg;
                 using (RHDWPartContext db = RHDWPartContext.GetContext(dto.SigTime, true))
                 {
-                    errMsg = db.CheckTableField();
+                    if (!db.IsTableFieldSync())
+                        throw new Exception("表结构不一致,本次定位异常,已自动同步结构");
+                    else
+                        throw;
                 }
-                if (!string.IsNullOrWhiteSpace(errMsg))
-                    throw new Exception(errMsg);
-                else
-                    throw;
             }
 
         }
@@ -582,17 +580,15 @@ namespace XdCxRhDW.App.Controllers
                     return Success(MapDto(posRes));
                 }
             }
-            catch (DbUpdateException ex)
+            catch (DbUpdateException)
             {
-                string errMsg;
                 using (RHDWPartContext db = RHDWPartContext.GetContext(dto.SigTime, true))
                 {
-                    errMsg = db.CheckTableField();
+                    if (!db.IsTableFieldSync())
+                        throw new Exception("表结构不一致,本次定位异常,已自动同步结构");
+                    else
+                        throw;
                 }
-                if (!string.IsNullOrWhiteSpace(errMsg))
-                    throw new Exception(errMsg);
-                else
-                    throw;
             }
         }
 
@@ -714,17 +710,15 @@ namespace XdCxRhDW.App.Controllers
                     return Success(MapDto(posRes));
                 }
             }
-            catch (DbUpdateException ex)
+            catch (DbUpdateException)
             {
-                string errMsg;
                 using (RHDWPartContext db = RHDWPartContext.GetContext(dto.SigTime, true))
                 {
-                    errMsg = db.CheckTableField();
+                    if (!db.IsTableFieldSync())
+                        throw new Exception("表结构不一致,本次定位异常,已自动同步结构");
+                    else
+                        throw;
                 }
-                if (!string.IsNullOrWhiteSpace(errMsg))
-                    throw new Exception(errMsg);
-                else
-                    throw;
             }
         }
 
@@ -902,17 +896,15 @@ namespace XdCxRhDW.App.Controllers
                     return Success(MapDto(posRes));
                 }
             }
-            catch (DbUpdateException ex)
+            catch (DbUpdateException)
             {
-                string errMsg;
                 using (RHDWPartContext db = RHDWPartContext.GetContext(dto.SigTime, true))
                 {
-                    errMsg = db.CheckTableField();
+                    if (!db.IsTableFieldSync())
+                        throw new Exception("表结构不一致,本次定位异常,已自动同步结构");
+                    else
+                        throw;
                 }
-                if (!string.IsNullOrWhiteSpace(errMsg))
-                    throw new Exception(errMsg);
-                else
-                    throw;
             }
         }
         #endregion
@@ -1305,17 +1297,15 @@ namespace XdCxRhDW.App.Controllers
                     return Success(MapDto(posRes));
                 }
             }
-            catch (DbUpdateException ex)
+            catch (DbUpdateException)
             {
-                string errMsg;
                 using (RHDWPartContext db = RHDWPartContext.GetContext(dto.SigTime, true))
                 {
-                    errMsg = db.CheckTableField();
+                    if (!db.IsTableFieldSync())
+                        throw new Exception("表结构不一致,本次定位异常,已自动同步结构");
+                    else
+                        throw;
                 }
-                if (!string.IsNullOrWhiteSpace(errMsg))
-                    throw new Exception(errMsg);
-                else
-                    throw;
             }
         }
 
@@ -1483,17 +1473,15 @@ namespace XdCxRhDW.App.Controllers
                     return Success(MapDto(posRes));
                 }
             }
-            catch (DbUpdateException ex)
+            catch (DbUpdateException)
             {
-                string errMsg;
                 using (RHDWPartContext db = RHDWPartContext.GetContext(dto.SigTime, true))
                 {
-                    errMsg = db.CheckTableField();
+                    if (!db.IsTableFieldSync())
+                        throw new Exception("表结构不一致,本次定位异常,已自动同步结构");
+                    else
+                        throw;
                 }
-                if (!string.IsNullOrWhiteSpace(errMsg))
-                    throw new Exception(errMsg);
-                else
-                    throw;
             }
         }
 
@@ -1611,17 +1599,15 @@ namespace XdCxRhDW.App.Controllers
                     return Success(MapDto(posRes));
                 }
             }
-            catch (DbUpdateException ex)
+            catch (DbUpdateException)
             {
-                string errMsg;
                 using (RHDWPartContext db = RHDWPartContext.GetContext(dto.SigTime, true))
                 {
-                    errMsg = db.CheckTableField();
+                    if (!db.IsTableFieldSync())
+                        throw new Exception("表结构不一致,本次定位异常,已自动同步结构");
+                    else
+                        throw;
                 }
-                if (!string.IsNullOrWhiteSpace(errMsg))
-                    throw new Exception(errMsg);
-                else
-                    throw;
             }
         }
 
@@ -1784,17 +1770,15 @@ namespace XdCxRhDW.App.Controllers
                     return Success(MapDto(posRes));
                 }
             }
-            catch (DbUpdateException ex)
+            catch (DbUpdateException)
             {
-                string errMsg;
                 using (RHDWPartContext db = RHDWPartContext.GetContext(dto.SigTime, true))
                 {
-                    errMsg = db.CheckTableField();
+                    if (!db.IsTableFieldSync())
+                        throw new Exception("表结构不一致,本次定位异常,已自动同步结构");
+                    else
+                        throw;
                 }
-                if (!string.IsNullOrWhiteSpace(errMsg))
-                    throw new Exception(errMsg);
-                else
-                    throw;
             }
         }
         #endregion

+ 4 - 5
XdCxRhDW.App/EditForms/X2D1DTOParamEditor.cs

@@ -15,6 +15,7 @@ using System.Threading.Tasks;
 using XdCxRhDW.Api;
 using XdCxRhDW.Dto;
 using XdCxRhDW.Entity;
+using XdCxRhDW.Framework;
 using XdCxRhDW.Repostory;
 
 namespace XdCxRhDW.App.EditForms
@@ -206,12 +207,10 @@ namespace XdCxRhDW.App.EditForms
                 if (string.IsNullOrWhiteSpace(msat)) msat = cg.MainCode.Value.ToString();
                 var nsat = listSat.FirstOrDefault(m => m.SatCode == cg.Adja1Code.Value)?.Sat;
                 if (string.IsNullOrWhiteSpace(nsat)) nsat = cg.Adja1Code.Value.ToString();
-                string useNewGDOP = ConfigurationManager.AppSettings["UseNewGDOP"];
+                bool useNewGDOP = AppConfigHelper.Get("UseNewGDOP", true);
                 if (info.PosResType == EnumPosResType.X2D1)
                 {
-                    //var xdDtoLine = DrawDtoLineHelper.DtoLineXd(dtoLineXd);
-                    //mapControl1.DrawDtoLine($"[{msat},超短{CDBAnt[0]}°]时差线", xdDtoLine);
-                    if (useNewGDOP == null || useNewGDOP == "0")
+                    if (!useNewGDOP)
                     {
                         var xdDtoLine1 = DrawDtoLineHelper.DtoLineXdEx(dtoLineXd);
                         mapControl1.DrawDtoLineTwo($"[{msat},超短{CDBAnt[0]}°]带参时差线", xdDtoLine1);
@@ -238,7 +237,7 @@ namespace XdCxRhDW.App.EditForms
                 }
                 else
                 {
-                    if (useNewGDOP == null || useNewGDOP == "0")
+                    if (!useNewGDOP)
                     {
                         var xdDtoLine1 = DrawDtoLineHelper.DtoLineXdNoRefEx(dtoLineXd);
                         mapControl1.DrawDtoLineTwo($"[{msat},超短{CDBAnt[0]}°]无参时差线", xdDtoLine1);

+ 12 - 9
XdCxRhDW.App/MainForm.cs

@@ -35,6 +35,9 @@ using XdCxRhDW.DataEmulation;
 using DxHelper;
 using System.Runtime.InteropServices;
 using System.Runtime.InteropServices.ComTypes;
+using DevExpress.LookAndFeel.Design;
+using System.Configuration;
+using XdCxRhDW.Framework;
 
 namespace XdCxRhDW
 {
@@ -64,7 +67,7 @@ namespace XdCxRhDW
             ctrlTypes.Add("服务状态", typeof(CtrlSvrs));
             ctrlTypes.Add("服务日志", typeof(CtrlSvrLog));
             DxHelper.WaitHelper.UpdateSplashMessage("正在检查数据库环境...");
-            errmsg = CheckDb();
+            CheckDb();
 
         }
         private string text;
@@ -117,6 +120,7 @@ namespace XdCxRhDW
         }
         private Task MonitorCpuAndMemory()
         {
+            if (!AppConfigHelper.Get("UseGatherDevState", true)) return Task.CompletedTask;
             return Task.Run(() =>
             {
                 try
@@ -136,7 +140,7 @@ namespace XdCxRhDW
             });
 
         }
-        private string CheckDb()
+        private void CheckDb()
         {
             using (RHDWContext db = new RHDWContext())
             {
@@ -162,15 +166,14 @@ namespace XdCxRhDW
                     }
                 }
             }
+
             using (RHDWContext db = new RHDWContext())
             {
-                string notExistTableName = db.CheckTableExist();
-                if (!string.IsNullOrWhiteSpace(notExistTableName))
-                {
-                    db.Dispose();
-                    return $"Database.db数据库中不存在表{notExistTableName}";
-                }
-                return db.CheckTableField();
+                db.SyncDb();
+            }
+            using (RHDWLogContext db = new RHDWLogContext())
+            {
+                db.SyncDb();
             }
         }
         private void StartWebApi()

+ 3 - 4
XdCxRhDW.App/UserControl/CtrlHome.cs

@@ -28,6 +28,7 @@ using XdCxRhDW.App.Model;
 using XdCxRhDW.App.PopupControl;
 using XdCxRhDW.Dto;
 using XdCxRhDW.Entity;
+using XdCxRhDW.Framework;
 using XdCxRhDW.Repostory;
 using XdCxRhDW.WebApi;
 using static System.Windows.Forms.VisualStyles.VisualStyleElement.TextBox;
@@ -111,9 +112,7 @@ namespace XdCxRhDW.App.UserControl
            .UseTrack()
            .UseExportImg()
            .UseExportXlsx();
-            if (ConfigurationManager.AppSettings["UseMapCluster"] != null
-                && ConfigurationManager.AppSettings["UseMapCluster"].Trim().ToLower() != "0"
-                 && ConfigurationManager.AppSettings["UseMapCluster"].Trim().ToLower() != "false")
+            if (AppConfigHelper.Get("UseMapCluster", false))
             {
                 mapControl1.UseCluster();
             }
@@ -641,7 +640,7 @@ namespace XdCxRhDW.App.UserControl
                             {
                                 dto.FixedStationDto = new X2D1FixedStationDto()
                                 {
-                                    FixedStationId=fixedStation.ID,
+                                    FixedStationId = fixedStation.ID,
                                     FreqUp = fixedStation.FreqUpHz,
                                     Lon = fixedStation.Lon,
                                     Lat = fixedStation.Lat,

+ 3 - 2
XdCxRhDW.App/UserControl/RHGDOPParam.cs

@@ -13,6 +13,7 @@ using DevExpress.Utils.About;
 using DevExpress.XtraEditors.DXErrorProvider;
 using XdCxRhDW.Dto;
 using System.Configuration;
+using XdCxRhDW.Framework;
 
 namespace XdCxRhDW.App.UserControl
 {
@@ -104,8 +105,8 @@ namespace XdCxRhDW.App.UserControl
             {
 
                 mapControl1.ClearMap();
-                string useNewGDOP = ConfigurationManager.AppSettings["UseNewGDOP"];
-                if (useNewGDOP == null || useNewGDOP == "0")
+                bool useNewGDOP = AppConfigHelper.Get("UseNewGDOP", true);
+                if (!useNewGDOP)
                 {
                     var data = GdopHelper.Gdop2Sat1DByXyz(Model.EphMain, Model.EphAdja, Model.CDBStation
                              , Model.DtousErr, Model.SatLocErr, Model.RefStation);

+ 3 - 2
XdCxRhDW.App/UserControl/X1D1GDOPParam.cs

@@ -12,6 +12,7 @@ using DevExpress.XtraCharts.Design;
 using System.Runtime.ConstrainedExecution;
 using XdCxRhDW.Dto;
 using System.Configuration;
+using XdCxRhDW.Framework;
 
 namespace XdCxRhDW.App.UserControl
 {
@@ -104,8 +105,8 @@ namespace XdCxRhDW.App.UserControl
             {
                 mapControl1.ClearMap();
 
-                string useNewGDOP = ConfigurationManager.AppSettings["UseNewGDOP"];
-                if (useNewGDOP == null || useNewGDOP == "0")
+                bool useNewGDOP = AppConfigHelper.Get("UseNewGDOP", true);
+                if (!useNewGDOP)
                 {
                     var data = GdopHelper.Gdop1Sat1DByXyz(Model.EphMain, Model.CDBStation, Model.CXStation,
                                      Model.DtousErr, Model.CXErr, Model.SatLocErr, Model.RefStation);

+ 3 - 2
XdCxRhDW.App/UserControl/X2D1GDOPParam.cs

@@ -13,6 +13,7 @@ using DevExpress.Utils.About;
 using DevExpress.XtraEditors.DXErrorProvider;
 using XdCxRhDW.Dto;
 using System.Configuration;
+using XdCxRhDW.Framework;
 
 namespace XdCxRhDW.App.UserControl
 {
@@ -108,8 +109,8 @@ namespace XdCxRhDW.App.UserControl
             {
 
                 mapControl1.ClearMap();
-                string useNewGDOP = ConfigurationManager.AppSettings["UseNewGDOP"];
-                if (useNewGDOP == null || useNewGDOP == "0")
+                bool useNewGDOP = AppConfigHelper.Get("UseNewGDOP", true);
+                if (!useNewGDOP)
                 {
                     var data = GdopHelper.Gdop2Sat1DByXyz(Model.EphMain, Model.EphAdja, Model.CDBStation
                              , Model.DtousErr, Model.SatLocErr, PosResType == EnumPosResType.X2D1NoRef ? null : Model.RefStation);

+ 3 - 2
XdCxRhDW.App/UserControl/X2DFGDOPParam.cs

@@ -12,6 +12,7 @@ using System.Linq;
 using XdCxRhDW.Api;
 using XdCxRhDW.Dto;
 using XdCxRhDW.Entity;
+using XdCxRhDW.Framework;
 using XdCxRhDW.Repostory;
 namespace XdCxRhDW.App.UserControl
 {
@@ -116,8 +117,8 @@ namespace XdCxRhDW.App.UserControl
 
 
                 mapControl1.ClearMap();
-                string useNewGDOP = ConfigurationManager.AppSettings["UseNewGDOP"];
-                if (useNewGDOP == null || useNewGDOP == "0")
+                bool useNewGDOP = AppConfigHelper.Get("UseNewGDOP", true);
+                if (!useNewGDOP)
                 {
                     var data = GdopHelper.Gdop2SatDRefByXyz(Model.EphMain, Model.EphAdja, Model.fu1, Model.fu2, Model.DtousErr, Model.DfoErr, Model.SatLocErr, Model.EphVelErr, Model.RefStation);
                     if (data.Count == 0)

+ 3 - 2
XdCxRhDW.App/UserControl/X3DFGDOPParam .cs

@@ -10,6 +10,7 @@ using System.Linq;
 using XdCxRhDW.Api;
 using XdCxRhDW.Dto;
 using XdCxRhDW.Entity;
+using XdCxRhDW.Framework;
 using XdCxRhDW.Repostory;
 
 namespace XdCxRhDW.App.UserControl
@@ -113,8 +114,8 @@ namespace XdCxRhDW.App.UserControl
             try
             {
                 mapControl1.ClearMap();
-                string useNewGDOP = ConfigurationManager.AppSettings["UseNewGDOP"];
-                if (useNewGDOP == null || useNewGDOP == "0")
+                bool useNewGDOP = AppConfigHelper.Get("UseNewGDOP", true);
+                if (!useNewGDOP)
                 {
                     var data = GdopHelper.Gdop3SatDFByXyz(Model.EphMain, Model.EphAdja1, Model.EphAdja2, Model.fu1, Model.fu2, Model.DfoErr, Model.SatLocErr, Model.EphVelErr, Model.RefStation);
                     if (data.Count == 0)

+ 3 - 2
XdCxRhDW.App/UserControl/X3GDOPParam.cs

@@ -12,6 +12,7 @@ using System.Drawing;
 using DevExpress.XtraEditors.DXErrorProvider;
 using XdCxRhDW.Dto;
 using System.Configuration;
+using XdCxRhDW.Framework;
 namespace XdCxRhDW.App.UserControl
 {
     public partial class X3GDOPParam : DevExpress.XtraEditors.XtraUserControl
@@ -103,8 +104,8 @@ namespace XdCxRhDW.App.UserControl
             try
             {
                 mapControl1.ClearMap();
-                string useNewGDOP = ConfigurationManager.AppSettings["UseNewGDOP"];
-                if (useNewGDOP == null || useNewGDOP == "0")
+                bool useNewGDOP = AppConfigHelper.Get("UseNewGDOP", true);
+                if (!useNewGDOP)
                 {
                     var data = GdopHelper.Gdop3SatByXyz(Model.EphMain, Model.EphAdja1, Model.EphAdja2
                                   , Model.DtousErr, Model.SatLocErr, PosResType == EnumPosResType.X3NoRef ? null : Model.RefStation);

+ 1 - 0
XdCxRhDW.Entity/03.XdCxRhDW.Entity.csproj

@@ -76,6 +76,7 @@
     <Compile Include="StationRes.cs" />
     <Compile Include="SysSetings.cs" />
     <Compile Include="TargetInfo.cs" />
+    <Compile Include="TaskRunnningInfo.cs" />
     <Compile Include="TaskSig.cs" />
     <Compile Include="TaskInfo.cs" />
     <Compile Include="TxInfo.cs" />

+ 0 - 1
XdCxRhDW.Entity/TaskInfo.cs

@@ -9,7 +9,6 @@ using System.Threading.Tasks;
 
 namespace XdCxRhDW.Entity
 {
-
     [Table("TaskInfo")]   // 标识数据库创建的表名
     public class TaskInfo : BaseEntity
     {

+ 29 - 0
XdCxRhDW.Entity/TaskRunnningInfo.cs

@@ -0,0 +1,29 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using System.ComponentModel.DataAnnotations.Schema;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace XdCxRhDW.Entity
+{
+    [Table("TaskRunnningInfo")]
+    public class TaskRunnningInfo : BaseEntity
+    {
+        /// <summary>
+        /// 任务编号
+        /// </summary>
+        public int TaskID { get; set; }
+
+        /// <summary>
+        /// 上行频点Hz
+        /// </summary>
+        public long FreqUp { get; set; }
+
+        /// <summary>
+        /// 最近处理完成的文件的采集时间时刻
+        /// </summary>
+        public DateTime LastDoneAdFileTime { get; set; }
+    }
+}

+ 1 - 0
XdCxRhDW.Framework/01.XdCxRhDW.Framework.csproj

@@ -77,6 +77,7 @@
     <Reference Include="System.Xml" />
   </ItemGroup>
   <ItemGroup>
+    <Compile Include="AppConfigHelper.cs" />
     <Compile Include="RandomHelper.cs" />
     <Compile Include="ColorHelper.cs" />
     <Compile Include="ColorRGB.cs" />

+ 94 - 0
XdCxRhDW.Framework/AppConfigHelper.cs

@@ -0,0 +1,94 @@
+using Newtonsoft.Json.Linq;
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Configuration;
+using System.Linq;
+using System.Runtime.Remoting;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace XdCxRhDW.Framework
+{
+    public static class AppConfigHelper
+    {
+        public static string Get(string key, string defaultVal = "")
+        {
+            var str = ConfigurationManager.AppSettings[key];
+            if (string.IsNullOrWhiteSpace(str))
+                return defaultVal;
+            return str.Trim();
+        }
+
+        /// <summary>
+        /// 获取App.config配置文件中appSettings节点中指定key的value
+        /// <para>如果泛型为bool,则{"1","true","True","TRUE"}都会被转换成true,否则转换为false</para>
+        /// <para>该方法支持int?、double?等可空类型的转换</para>
+        /// </summary>
+        /// <typeparam name="T"></typeparam>
+        /// <param name="key"></param>
+        /// <param name="defaultVal"></param>
+        /// <returns></returns>
+        public static T Get<T>(string key, T defaultVal = default)
+        {
+            var str = ConfigurationManager.AppSettings[key];
+            if (string.IsNullOrWhiteSpace(str))
+            {
+                return defaultVal;
+            }
+            str = str.Trim();
+            bool isNullable = typeof(T).IsGenericType && typeof(T).GetGenericTypeDefinition() == typeof(Nullable<>);
+            if (isNullable)
+            {
+                NullableConverter nullableConverter = new NullableConverter(typeof(T));
+                return (T)nullableConverter.ConvertFromString(str);
+            }
+            else if (typeof(T) == typeof(bool))
+            {
+                if (str.ToLower().Trim() == "true" || str.ToLower().Trim() == "1")
+                {
+                    T boolVal = (T)Convert.ChangeType(true, typeof(T));
+                    return boolVal;
+                }
+                else
+                {
+                    T boolVal = (T)Convert.ChangeType(false, typeof(T));
+                    return boolVal;
+                }
+            }
+            else
+            {
+                T ret = (T)Convert.ChangeType(str, typeof(T));
+                return ret;
+            }
+        }
+
+        /// <summary>
+        /// 如果参数小于0则返回0,否则返回原数字
+        /// </summary>
+        /// <param name="this"></param>
+        /// <returns></returns>
+        public static int NotLessThanZero(this int @this)
+        {
+            if (@this >= 0) return @this;
+            return 0;
+        }
+
+        /// <summary>
+        /// 为url字符串添加后缀
+        /// </summary>
+        /// <param name="this"></param>
+        /// <param name="suffix"></param>
+        /// <returns></returns>
+        public static string AppendUrlSuffix(this string @this, string suffix)
+        {
+            if (suffix.StartsWith("/"))
+                suffix = suffix.Substring(1);
+            if (@this.EndsWith("/"))
+                return $"{@this}{suffix}";
+            else
+                return $"{@this}/{suffix}";
+        }
+
+    }
+}

+ 146 - 78
XdCxRhDW.Repostory/EFContext/RHDWContext.cs

@@ -5,6 +5,7 @@ using System.ComponentModel.DataAnnotations.Schema;
 using System.Data.Common;
 using System.Data.Entity;
 using System.Data.Entity.Core.Common;
+using System.Data.Entity.Core.Metadata.Edm;
 using System.Data.Entity.Infrastructure;
 using System.Data.Entity.Infrastructure.Interception;
 using System.Data.Entity.ModelConfiguration.Conventions;
@@ -14,6 +15,7 @@ using System.Data.SQLite.EF6;
 using System.IO;
 using System.Linq;
 using System.Reflection;
+using System.Text;
 using System.Text.RegularExpressions;
 using System.Threading.Tasks;
 using XdCxRhDW.Entity;
@@ -30,60 +32,24 @@ namespace XdCxRhDW.Repostory
 
         public int pk { get; set; }
     }
-    class DbTableForeignKeyInfo
-    {
-        public string from { get; set; }
-    }
-    public class RHDWLogContext : DbContext
-    {
-        public string DbFile;
-        public RHDWLogContext() : base("LogDbCon") //配置使用的连接名
-        {
-            //|DataDirectory|在mvc等程序中代表了App_Data,在普通程序中代表程序根目录
-            var dbFile = Database.Connection.ConnectionString.Replace("Data Source=", "").Replace("|DataDirectory|\\", "");
-            this.DbFile = dbFile;
-        }
 
-        protected override void OnModelCreating(DbModelBuilder modelBuilder)
-        {
-            this.Database.Log = msg =>
-            {
-            };
-            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
-            modelBuilder.Configurations.AddFromAssembly(typeof(RHDWLogContext).Assembly);//自动加载Entity-Type
-            var sqliteConnectionInitializer = new SqliteCreateDatabaseIfNotExists<RHDWLogContext>(modelBuilder);
-            Database.SetInitializer(sqliteConnectionInitializer);
-            base.OnModelCreating(modelBuilder);
-        }
-        public DbSet<LogRes> LogRes { set; get; }
-    }
-    /// <summary>
-    /// 基础表上下文(id为int)
-    /// </summary>
-    public class RHDWContext : DbContext
+    public class DbContextBase : DbContext
     {
-        public string DbFile;
-        public RHDWContext() : base("DbCon") //配置使用的连接名
+        public DbContextBase(string nameOrConnectionString)
+            : base(nameOrConnectionString)
         {
-            //|DataDirectory|在mvc等程序中代表了App_Data,在普通程序中代表程序根目录
-            this.DbFile = Database.Connection.ConnectionString.Replace("Data Source=", "").Replace("|DataDirectory|\\", "");
         }
 
-        public Task<List<T>> SqlQueryAsync<T>(string sql)
+        public void SyncDb()
         {
-            return this.Database.SqlQuery<T>(sql).ToListAsync();
-        }
-        public Task<T> SqlQueryOneAsync<T>(string sql)
-        {
-            return this.Database.SqlQuery<T>(sql).FirstOrDefaultAsync();
-
+            SyncTable();
+            SyncTableField();
         }
-        //检查数据库表是否缺失
-        public string CheckTableExist()
+        void SyncTable()
         {
             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>();
+            Dictionary<string, Type> list = new Dictionary<string, Type>();
             foreach (var prop in props)
             {
                 bool isDbSet = prop.PropertyType.IsGenericType && typeof(DbSet<>) == prop.PropertyType.GetGenericTypeDefinition();
@@ -95,19 +61,60 @@ namespace XdCxRhDW.Repostory
                     {
                         name = entityType.Name;
                     }
-                    list.Add(name);
+                    list.Add(name, entityType);
                 }
             }
             foreach (var item in list)
             {
-                if (!tables.Contains(item))
+                if (!tables.Contains(item.Key))
                 {
-                    return item;
+                    var entityProps = item.Value.GetProperties().Where(p =>
+                        p.CanRead
+                        && p.CanWrite
+                        && !p.GetMethod.IsVirtual
+                        && p.GetCustomAttribute<NotMappedAttribute>() == null);
+                    item.Value.GetProperties().Where(p => p.CanWrite);
+                    StringBuilder sb = new StringBuilder();
+                    sb.Append($"create table {item.Key}(ID integer primary key autoincrement");
+                    foreach (var prop in entityProps)
+                    {
+                        if (prop.Name.ToLower() == "id") continue;
+                        bool isNullable = prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>);
+                        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) || prop.PropertyType.IsEnum)
+                        {
+                            typeStr = "int";
+                        }
+                        else if (type == typeof(double) || type == typeof(float))
+                        {
+                            typeStr = "float";
+                        }
+                        else if (type == typeof(DateTime))
+                        {
+                            typeStr = "datetime";
+                        }
+                        sb.Append($",{prop.Name} {typeStr}");
+                        if (!isNullable)
+                        {
+                            sb.Append(" not null");
+                        }
+                    }
+                    sb.Append(")");
+                    string createTableSql = sb.ToString();
+                    Database.ExecuteSqlCommand(createTableSql);
                 }
             }
-            return "";
         }
-        public string CheckTableField()
+        void SyncTableField()
         {
             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();
@@ -124,7 +131,8 @@ namespace XdCxRhDW.Repostory
             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 entityType = entityTypes.FirstOrDefault(p => p.Name == table);
+                if (entityType == null) continue;
                 var entityProps = entityType.GetProperties().Where(p =>
                     p.CanRead
                     && p.CanWrite
@@ -132,7 +140,7 @@ namespace XdCxRhDW.Repostory
                     && p.GetCustomAttribute<NotMappedAttribute>() == null);
                 foreach (var prop in entityProps)
                 {
-                    var find = res.Find(p => p.name == prop.Name);
+                    var find = res.Find(p => p.name.ToLower() == prop.Name.ToLower());
                     if (find == null)
                     {
                         string typeStr = "";
@@ -145,7 +153,7 @@ namespace XdCxRhDW.Repostory
                         {
                             typeStr = "nvarchar";
                         }
-                        else if (type == typeof(int) || type == typeof(long))
+                        else if (type == typeof(int) || type == typeof(long) || prop.PropertyType.IsEnum)
                         {
                             typeStr = "int";
                         }
@@ -157,24 +165,76 @@ namespace XdCxRhDW.Repostory
                         {
                             typeStr = "datetime";
                         }
-                        return $"{DbFile}数据库表{table}缺少{prop.Name}字段,类型={typeStr}";
-                    }
-                    else
-                    {
+                        bool isNullable = prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>);
 
-                        if (prop.PropertyType != typeof(string) && find.pk == 0 && !prop.PropertyType.IsGenericType && find.notnull == 0)
+                        string updateTableSql;
+                        if (isNullable)
+                            updateTableSql = $"alter table {table} add column {prop.Name} {typeStr}";
+                        else
                         {
-                            var foreignInfo = this.Database.SqlQuery<DbTableForeignKeyInfo>($"PRAGMA foreign_key_list({table})").ToList();
-                            if (!foreignInfo.Any(p => p.from == prop.Name))
-                            {
-                                return $"{DbFile}数据库表{table}中{prop.Name}字段不允许为空";
-                            }
+                            if (typeStr == "int" || typeStr == "float")
+                                updateTableSql = $"alter table {table} add column {prop.Name} {typeStr} not null default 0";
+                            else if (typeStr == "nvarchar")
+                                updateTableSql = $"alter table {table} add column {prop.Name} {typeStr} not null default ''";
+                            else if (typeStr == "datetime")
+                                updateTableSql = $"alter table {table} add column {prop.Name} {typeStr} not null default '{DateTime.Now:yyyy-MM-dd HH:mm:ss}'";
+                            else
+                                updateTableSql = $"alter table {table} add column {prop.Name} {typeStr}";
                         }
+                        this.Database.ExecuteSqlCommand(updateTableSql);
                     }
                 }
             }
-            return "";
         }
+    }
+
+
+    public class RHDWLogContext : DbContextBase
+    {
+        public string DbFile;
+        public RHDWLogContext() : base("LogDbCon") //配置使用的连接名
+        {
+            //|DataDirectory|在mvc等程序中代表了App_Data,在普通程序中代表程序根目录
+            var dbFile = Database.Connection.ConnectionString.Replace("Data Source=", "").Replace("|DataDirectory|\\", "");
+            this.DbFile = dbFile;
+        }
+
+        protected override void OnModelCreating(DbModelBuilder modelBuilder)
+        {
+            this.Database.Log = msg =>
+            {
+            };
+            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
+            modelBuilder.Configurations.AddFromAssembly(typeof(RHDWLogContext).Assembly);//自动加载Entity-Type
+            var sqliteConnectionInitializer = new SqliteCreateDatabaseIfNotExists<RHDWLogContext>(modelBuilder);
+            Database.SetInitializer(sqliteConnectionInitializer);
+            base.OnModelCreating(modelBuilder);
+        }
+        public DbSet<LogRes> LogRes { set; get; }
+    }
+    /// <summary>
+    /// 基础表上下文(id为int)
+    /// </summary>
+    public class RHDWContext : DbContextBase
+    {
+        public string DbFile;
+        public RHDWContext() : base("DbCon") //配置使用的连接名
+        {
+            //|DataDirectory|在mvc等程序中代表了App_Data,在普通程序中代表程序根目录
+            this.DbFile = Database.Connection.ConnectionString.Replace("Data Source=", "").Replace("|DataDirectory|\\", "");
+        }
+
+        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();
+
+        }
+
+
         protected override void OnModelCreating(DbModelBuilder modelBuilder)
         {
             this.Database.Log = msg =>
@@ -206,6 +266,7 @@ namespace XdCxRhDW.Repostory
 
         public DbSet<SysSetings> SysSetings { get; set; }
 
+        public DbSet<TaskRunnningInfo> TaskRunnningInfos { get; set; }
     }
 
     /// <summary>
@@ -243,8 +304,9 @@ namespace XdCxRhDW.Repostory
             this.DbFile = dbFile;
         }
 
-        public string CheckTableField()
+        public bool IsTableFieldSync()
         {
+            bool val = true;
             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>();
@@ -260,7 +322,8 @@ namespace XdCxRhDW.Repostory
             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 entityType = entityTypes.FirstOrDefault(p => p.Name == table);
+                if (entityType == null) continue;
                 var entityProps = entityType.GetProperties().Where(p =>
                     p.CanRead
                     && p.CanWrite
@@ -268,7 +331,7 @@ namespace XdCxRhDW.Repostory
                     && p.GetCustomAttribute<NotMappedAttribute>() == null);
                 foreach (var prop in entityProps)
                 {
-                    var find = res.Find(p => p.name == prop.Name);
+                    var find = res.Find(p => p.name.ToLower() == prop.Name.ToLower());
                     if (find == null)
                     {
                         string typeStr = "";
@@ -281,7 +344,7 @@ namespace XdCxRhDW.Repostory
                         {
                             typeStr = "nvarchar";
                         }
-                        else if (type == typeof(int) || type == typeof(long))
+                        else if (type == typeof(int) || type == typeof(long) || prop.PropertyType.IsEnum)
                         {
                             typeStr = "int";
                         }
@@ -293,23 +356,28 @@ namespace XdCxRhDW.Repostory
                         {
                             typeStr = "datetime";
                         }
-                        return $"{DbFile}数据库表{table}缺少{prop.Name}字段,类型={typeStr}";
-                    }
-                    else
-                    {
+                        bool isNullable = prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>);
 
-                        if (prop.PropertyType != typeof(string) && find.pk == 0 && !prop.PropertyType.IsGenericType && find.notnull == 0)
+                        string updateTableSql;
+                        if (isNullable)
+                            updateTableSql = $"alter table {table} add column {prop.Name} {typeStr}";
+                        else
                         {
-                            var foreignInfo = this.Database.SqlQuery<DbTableForeignKeyInfo>($"PRAGMA foreign_key_list({table})").ToList();
-                            if (!foreignInfo.Any(p => p.from == prop.Name))
-                            {
-                                return $"{DbFile}数据库表{table}中{prop.Name}字段不允许为空";
-                            }
+                            if (typeStr == "int" || typeStr == "float")
+                                updateTableSql = $"alter table {table} add column {prop.Name} {typeStr} not null default 0";
+                            else if (typeStr == "nvarchar")
+                                updateTableSql = $"alter table {table} add column {prop.Name} {typeStr} not null default ''";
+                            else if (typeStr == "datetime")
+                                updateTableSql = $"alter table {table} add column {prop.Name} {typeStr} not null default '{DateTime.Now:yyyy-MM-dd HH:mm:ss}'";
+                            else
+                                updateTableSql = $"alter table {table} add column {prop.Name} {typeStr}";
                         }
+                        this.Database.ExecuteSqlCommand(updateTableSql);
+                        val = false;
                     }
                 }
             }
-            return "";
+            return val;
         }
         protected override void OnModelCreating(DbModelBuilder modelBuilder)
         {