Env.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. using ControlzEx.Theming;
  2. using DIL;
  3. using NPOI.SS.Formula.Functions;
  4. using SCADA.CommonCtrl.Wpf;
  5. using SCADA.CommonCtrl.WpfControl;
  6. using SCADA.CommonCtrl.WpfHelper;
  7. using SCADA.CommonLib;
  8. using SCADA.CommonLib.Data.DIL;
  9. using SCADA.CommonLib.Data.DIL.Sqlite;
  10. using SCADA.CommonLib.Helper;
  11. using SCADA_DAQ.Plugin.Core.License;
  12. using SCADA_DAQ.Plugin.CoreUI;
  13. using SysManage.User;
  14. using System;
  15. using System.Collections.Generic;
  16. using System.Collections.ObjectModel;
  17. using System.IO;
  18. using System.Linq;
  19. using System.Reflection;
  20. using System.Windows;
  21. using System.Windows.Media;
  22. namespace SCADA_DAQ
  23. {
  24. class Env
  25. {
  26. public static DILDBV1 DAL = null;
  27. public static bool EnvInitFinish = false;
  28. public static User NewUser;
  29. public static Schedual Schedual { get; internal set; } = Schedual.Instance;
  30. internal static LicenseInfo LicenseInfo;
  31. public static DateTime StartTime { get; set; }
  32. public static int StartTick { get; internal set; }
  33. public static AutoSaveParameterItem<string> ProductTitle { get; set; }
  34. public static AutoSaveParameterItem<string> ProductName { get; set; }
  35. public static AutoSaveParameterItem<string> CompanyName { get; set; }
  36. public static AutoSaveParameterItem<string> AuthorInfo { get; set; }
  37. public static AutoSaveParameterItem<string> MainDllName { get; set; }
  38. public static DataBaseConfig CurrentDbConfig { get; set; }
  39. public static AutoSaveParameterItem<DatabaseSelector> CurrentDataBase { get; set; }
  40. public static DataBaseConfig SysDBConfig { get; set; }
  41. public static AutoSaveParameterItem<DatabaseSelector> SysDataBase { get; set; }
  42. public static DataBaseConfig AlarmDBConfig { get; set; }
  43. public static AutoSaveParameterItem<DatabaseSelector> AlarmDataBase { get; set; }
  44. public static AutoSaveParameterItem<ObservableCollection<DataBaseConfig>> DataBaseResource { get; set; }
  45. public static AutoSaveParameterItem<string> DefaultUserName { get; set; }
  46. public static AutoSaveParameterItem<string> WebServerAddress = AutoSaveParameterItem.Create("App.WebServer", "www.skdscada.com");
  47. public static AutoSaveParameterItem<bool> DataBaseNeedRest { get; set; } = AutoSaveParameterItem.Create("App.DatabaseNeedRest", false);
  48. /// <summary>
  49. /// 产量个数
  50. /// </summary>
  51. public static AutoSaveParameterItem<int> TotalOutputPcs { get; set; } = AutoSaveParameterItem.Create("App.TotalOutputPcs", 0);
  52. /// <summary>
  53. /// 产量
  54. /// </summary>
  55. public static AutoSaveParameterItem<decimal> TotalOutputQty { get; set; } = AutoSaveParameterItem.Create("App.TotalOutputQty", 0m);
  56. #region 系统设置
  57. public static AutoSaveParameterItem<string> ComputerId;
  58. public static AutoSaveParameterItem<string> ComputerTag;
  59. public static AutoSaveParameterItem<int> RESTfulPort;
  60. public static AutoSaveParameterItem<int> RPCPort;
  61. public static AutoSaveParameterItem<bool> SingleModel;
  62. public static AutoSaveParameterItem<SCADA.CommonLib.LoggerHelper.LogLevel> LogLevel;
  63. public static AutoSaveParameterItem<bool> AutoCycle;
  64. public static AutoSaveParameterItem<int> CycleTime;
  65. public static AutoSaveParameterItem<int> DataExpireDay;
  66. #endregion
  67. #region 主题配置
  68. public static AutoSaveParameterItem<string> ThemeName;
  69. public static AutoSaveParameterItem<string> ThemeColor;
  70. #endregion
  71. public static AutoSaveParameterItem<string> Language;
  72. /// <summary>
  73. /// 设备配置文件
  74. /// </summary>
  75. public static AutoSaveParameterItem<string> DeviceConfigFilePath;
  76. public static void ParameterInit()
  77. {
  78. ProductTitle = AutoSaveParameterItem.Create("App.MainTitle", ApplicationHelper.GetProductTitle(), true);
  79. ProductTitle.DisplayName = "窗口标题";
  80. ProductName = AutoSaveParameterItem.Create("App.ProductName", "EICP", true);
  81. ProductName.DisplayName = "产品名称";
  82. CompanyName = AutoSaveParameterItem.Create("App.CompanyName", "", true);
  83. CompanyName.DisplayName = "公司名称";
  84. AuthorInfo = AutoSaveParameterItem.Create("App.AuthorInfo", System.Windows.Forms.Application.CompanyName, true);
  85. AuthorInfo.DisplayName = "作者信息";
  86. DefaultUserName = AutoSaveParameterItem.Create("App.DefualtUserName", "Operator", true);
  87. DefaultUserName.DisplayName = "默认用户";
  88. ComputerId = AutoSaveParameterItem.Create("App.ComputerId", "", true);
  89. ComputerId.IsReadOnly = true;
  90. ComputerId.DisplayName = "本机ID";
  91. ComputerTag = AutoSaveParameterItem.Create("App.ComputerTag", "", true);
  92. ComputerTag.IsReadOnly = true;
  93. RESTfulPort = AutoSaveParameterItem.Create("App.RESTfulPort", 7888);
  94. RESTfulPort.DisplayName = "网页端口";
  95. RPCPort = AutoSaveParameterItem.Create("App.RPCPort", 7880);
  96. RPCPort.DisplayName = "本地端口";
  97. SingleModel = AutoSaveParameterItem.Create("App.SingleModel", true);
  98. SingleModel.DisplayName = "单例模式";
  99. LogLevel = AutoSaveParameterItem.Create("App.LogLevel", SCADA.CommonLib.LoggerHelper.LogLevel.All);
  100. AutoCycle = AutoSaveParameterItem.Create("App.AutoCycle", false);
  101. AutoCycle.DisplayName = "页面自动循环";
  102. CycleTime = AutoSaveParameterItem.Create("App.CycleTime", 5);
  103. CycleTime.IsEnableBinding = new System.Windows.Data.Binding("Value")
  104. {
  105. Source = AutoCycle
  106. };
  107. CycleTime.Unit = "秒";
  108. CurrentDataBase = AutoSaveParameterItem.Create("App.DataBaseConfig", new DatabaseSelector()
  109. { CurrentDataBaseConfig = "Default" });
  110. SysDataBase = AutoSaveParameterItem.Create("App.DataBaseConfig.System", new DatabaseSelector()
  111. { CurrentDataBaseConfig = "SysDB" });
  112. AlarmDataBase = AutoSaveParameterItem.Create("App.DataBaseConfig.Alarm", new DatabaseSelector()
  113. { CurrentDataBaseConfig = "AlarmDB" });
  114. DataBaseResource = AutoSaveParameterItem.Create("App.DataBaseResource",
  115. new ObservableCollection<DataBaseConfig>()
  116. {
  117. new DataBaseConfig()
  118. {
  119. ResourceName="Default",
  120. DBType = DatabaseType.Sqlite,
  121. FilePath = @"Data\QwPlatform.db"
  122. },
  123. new DataBaseConfig()
  124. {
  125. ResourceName="AlarmDB",
  126. DBType = DatabaseType.Sqlite,
  127. FilePath = @"Data\QwPlatform.db"
  128. },
  129. new DataBaseConfig()
  130. {
  131. ResourceName="SysDB",
  132. DBType = DatabaseType.Sqlite,
  133. FilePath = @"Data\LocalApp.db"
  134. },
  135. }, true);
  136. dataBaseConfigInit(DataBaseResource, CurrentDataBase.Value, out var currentconfig);
  137. dataBaseConfigInit(DataBaseResource, SysDataBase.Value, out var sysConfig);
  138. dataBaseConfigInit(DataBaseResource, AlarmDataBase.Value, out var alarmConfig);
  139. CurrentDbConfig = currentconfig;
  140. AlarmDBConfig = alarmConfig;
  141. SysDBConfig = sysConfig;
  142. void dataBaseConfigInit(ObservableCollection<DataBaseConfig> srouce, DatabaseSelector selector, out DataBaseConfig config)
  143. {
  144. config = DataBaseResource.Value.FirstOrDefault(t => t.ResourceName == selector?.CurrentDataBaseConfig);
  145. selector.DataBaseConfigResource = DataBaseResource.Value;
  146. if (config == null)
  147. {
  148. config = DataBaseResource.Value.FirstOrDefault();
  149. selector.CurrentDataBaseConfig = config.ResourceName;
  150. }
  151. selector.DataBaseConfig = config;
  152. }
  153. DataExpireDay = AutoSaveParameterItem.Create($"App.DataExpireDay", 30);
  154. DataExpireDay.DisplayName = "数据过期时间(天)";
  155. ThemeName = AutoSaveParameterItem.Create("App.ThemeName", "Light");
  156. ThemeName.StringType = StringType.IsLimited;
  157. ThemeName.ShowButton = false;
  158. ThemeName.ItemsSource = new Dictionary<string, string>
  159. {
  160. { "Light", "Light" }, { "Dark", "Dark" }
  161. };
  162. ThemeColor = AutoSaveParameterItem.Create("App.ThemeColor", "Blue");
  163. ThemeColor.StringType = StringType.IsLimited;
  164. ThemeColor.ShowButton = false;
  165. DeviceConfigFilePath = AutoSaveParameterItem.Create("DeviceConfigFilePath", "DeviceCfg.xml");
  166. DeviceConfigFilePath.StringType = StringType.IsFilePath;
  167. DeviceConfigFilePath.DisplayName = "设备配置文件";
  168. Language = AutoSaveParameterItem.Create("App.Language", "zh-cn");
  169. Language.StringType = StringType.IsLimited;
  170. Language.ItemsSource = new Dictionary<string, string>()
  171. {
  172. {"中文(简体)","zh-cn" },
  173. {"中文(繁体)","zh-tw" },
  174. {"English(US)","en-us" },
  175. {"Deutsch","de-de" },
  176. {"Руская","ru-ru" },
  177. {"日本語","ja-jp" },
  178. {"한국어","ko-kr" },
  179. {"ภาษาไทย","th-th"}
  180. };
  181. ThemeColor.PropertyChanged += Theme_PropertyChanged;
  182. ThemeName.PropertyChanged += Theme_PropertyChanged;
  183. if (Application.Current != null)
  184. {
  185. ThemeColor.ItemsSource = new List<string>() {
  186. "Red", "Green", "Blue", "Purple", "Orange", "Lime", "Emerald", "Teal", "Cyan", "Cobalt", "Indigo", "Violet", "Pink", "Magenta", "Crimson", "Amber", "Yellow", "Brown", "Olive", "Steel", "Mauve", "Taupe", "Sienna"
  187. }.ToDictionary(t => t, t => t);
  188. }
  189. bool neeRestDatabase = DataBaseNeedRest.Value;
  190. DAL = new DILDBV1(CurrentDbConfig.GetDB());
  191. CheckDataBase(DAL, CurrentDbConfig.NeedReset || DataBaseNeedRest.Value);
  192. GlobalEnv.Instance.GlobalDB = DAL;
  193. GlobalEnv.Instance.AlarmDB = new DILDBV1(AlarmDBConfig.GetDB());
  194. CheckDataBase(GlobalEnv.Instance.AlarmDB as BaseDB, CurrentDbConfig.NeedReset || DataBaseNeedRest.Value);
  195. GlobalEnv.Instance.LocalAppDB = new LocalDB.DIL.DILDBV1(SysDBConfig.GetDB());
  196. CheckDataBase(GlobalEnv.Instance.LocalAppDB as BaseDB, CurrentDbConfig.NeedReset || DataBaseNeedRest.Value);
  197. NewUser = new User(DAL)
  198. {
  199. UserName = "Admin",
  200. PassWordReviseHandler = () =>
  201. {
  202. var passWordRevise = new FrmUserLogin(new PasswordReviseViewModel(NewUser));
  203. ((BaseMainWindow)Application.Current.MainWindow).ShowChildWindow(passWordRevise);
  204. },
  205. TryLoginHandler = () =>
  206. {
  207. if (NewUser.IsLogged == false)
  208. {
  209. FrmUserLogin frmUserLog = new FrmUserLogin(new UserLoginViewModel(NewUser));
  210. ((BaseMainWindow)Application.Current.MainWindow).ShowChildWindow(frmUserLog);
  211. }
  212. else
  213. {
  214. (Application.Current as IApp).ShowToast($"{LanguageHelper.GetStringByKey("SysCfg_CurrentUser")}{NewUser.UserName}", ControlStyle.Info);
  215. }
  216. },
  217. MidCheckHandler = () =>
  218. {
  219. var frmUserLog = new FrmUserLogin(new UserLoginViewModel(NewUser));
  220. if (NewUser.IsLogged == false)
  221. {
  222. ((BaseMainWindow)Application.Current.MainWindow).ShowChildWindow(frmUserLog);
  223. return NewUser.IsLogged;
  224. }
  225. else
  226. {
  227. return NewUser.IsLogged;
  228. }
  229. }
  230. };
  231. GlobalEnv.Instance.User = NewUser;
  232. Language.PropertyChanged += Language_PropertyChanged;
  233. EnvInitFinish = true;
  234. }
  235. private static void dataBaseInit(bool v, DataBaseConfig dataBaseConfig, object config, DatabaseSelector databaseSelector, object selector)
  236. {
  237. throw new NotImplementedException();
  238. }
  239. static Env()
  240. {
  241. //XmlUserConfig.Create();
  242. }
  243. private static void Language_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
  244. {
  245. SetLanguage();
  246. }
  247. public static void SetLanguage()
  248. {
  249. try
  250. {
  251. List<ResourceDictionary> dictionaryList = new List<ResourceDictionary>();
  252. foreach (ResourceDictionary dictionary in Application.Current.Resources.MergedDictionaries)
  253. {
  254. dictionaryList.Add(dictionary);
  255. }
  256. string requestedCulture = $@"{Language.Value}.xaml";
  257. ResourceDictionary resourceDictionary = dictionaryList.FirstOrDefault(d => d?.Source?.Segments.Last() == requestedCulture);
  258. Application.Current.Resources.MergedDictionaries.Remove(resourceDictionary);
  259. Application.Current.Resources.MergedDictionaries.Add(resourceDictionary);
  260. LanguageHelper.CurrentLanguageDictionary = resourceDictionary;
  261. LanguageHelper.DefaultLanguageDictionary = dictionaryList.FirstOrDefault(d => d?.Source?.Segments.Last() == @"zh-cn.xaml");
  262. }
  263. catch (Exception ex)
  264. {
  265. System.Diagnostics.Trace.TraceError($"{ex}");
  266. }
  267. }
  268. private static void Theme_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
  269. {
  270. SetTheme();
  271. }
  272. public static void SetTheme()
  273. {
  274. try
  275. {
  276. ThemeManager.Current.ChangeTheme(Application.Current, $"{ThemeName.Value}.{ThemeColor.Value}");
  277. }
  278. catch (Exception ex)
  279. {
  280. System.Diagnostics.Trace.TraceError($"{ex}");
  281. }
  282. }
  283. public static void SetFont()
  284. {
  285. AutoSaveParameterItem<string> DefaultFont = AutoSaveParameterItem.Create("App.DefaultFont", "Microsoft YaHei UI");
  286. AutoSaveParameterItem<double> DefaultFontSize = AutoSaveParameterItem.Create("App.DefaultFontSize", 14d);
  287. AutoSaveParameterItem<int> DefaultFontWeight = AutoSaveParameterItem.Create("App.DefaultFontWeight", 400);
  288. Application.Current.Resources["DefaultFontWeight"] = FontWeight.FromOpenTypeWeight(DefaultFontWeight.Value);
  289. Application.Current.Resources["DefaultFontSize"] = DefaultFontSize.Value;
  290. Application.Current.Resources["DefaultFont"] = new FontFamily(DefaultFont.Value);
  291. }
  292. private static void CheckDataBase(BaseDB db, bool dataBaseNeedRest)
  293. {
  294. string databasepath = "";
  295. if (db.DatabaseType == DatabaseType.Sqlite)
  296. {
  297. databasepath = Path.Combine(db.ServerName, db.DatabaseInfo);
  298. }
  299. else
  300. {
  301. return;
  302. }
  303. if (dataBaseNeedRest) //用户设置了重置数据库
  304. {
  305. System.Diagnostics.Trace.TraceInformation($"用户请求重置数据库,数据库开始重置");
  306. if (ReleseDatabase())
  307. {
  308. DataBaseNeedRest.Value = false; //数据库重置成功
  309. }
  310. }
  311. else
  312. {
  313. if (File.Exists(databasepath))
  314. {
  315. object dt = db.ExecuteScalar("PRAGMA integrity_check");
  316. if ($"{dt}".ToUpper() == "OK")
  317. {
  318. System.Diagnostics.Debug.WriteLine($"{databasepath} 数据库检测正常");
  319. }
  320. else
  321. {
  322. Application.Current.Dispatcher.Invoke(new Action(() =>
  323. {
  324. if (MessageBox.Show(Application.Current?.MainWindow, LanguageHelper.GetStringByKey("SysCfg_DatabaseIsDamageTip"), LanguageHelper.SysCfg_Wran, MessageBoxButton.OK) == MessageBoxResult.OK)
  325. {
  326. System.Diagnostics.Trace.TraceWarning($"检测到本地数据库已损坏,开始重置数据库");
  327. _ = ReleseDatabase();
  328. }
  329. }));
  330. }
  331. }
  332. else
  333. {
  334. ReleseDatabase();
  335. }
  336. }
  337. bool ReleseDatabase()
  338. {
  339. try
  340. {
  341. if (File.Exists(databasepath))
  342. {
  343. File.Move(databasepath, $"{databasepath}.{DateTime.Now:yyyyMMddHHmmss}");
  344. }
  345. var assembly = Assembly.GetEntryAssembly();
  346. Stream res = null;
  347. if (Path.GetFileName(databasepath).ToUpper() == "LOCALAPP.DB")
  348. {
  349. res = new MemoryStream(LocalResource.LocalApp);
  350. }
  351. else if (Path.GetFileName(databasepath).ToUpper() == "QWPLATFORM.DB")
  352. {
  353. res = new MemoryStream(LocalResource.QwPlatform);
  354. }
  355. if (res == null) return true;
  356. using (res)
  357. {
  358. FileHelper.EnsureDirectoryExist(databasepath);
  359. byte[] save = ZipHelper.UnZip(res)[0];
  360. using (FileStream fsObj = new FileStream(databasepath, FileMode.Create))
  361. {
  362. fsObj.Write(save, 0, save.Length);
  363. fsObj.Close();
  364. }
  365. }
  366. System.Diagnostics.Debug.WriteLine($"{databasepath} 数据库修复成功");
  367. return true;
  368. }
  369. catch (Exception ex)
  370. {
  371. System.Diagnostics.Trace.Fail($"{databasepath} 数据库修复失败,{ex}");
  372. //_ = MessageBox.Show(Application.Current?.MainWindow, ex.ToString(), LanguageHelper.GetStringByKey("SysCfg_DatabaseRepairFail"));
  373. }
  374. return false;
  375. }
  376. }
  377. }
  378. }