123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367 |
- using ControlzEx.Theming;
- using DIL;
- using SCADA.CommonCtrl.WpfHelper;
- using SCADA.CommonLib;
- using SCADA.CommonLib.Data.DIL;
- using SCADA.CommonLib.Helper;
- using SCADA_DAQ.Plugin.Core.License;
- using SysManage.User;
- using System;
- using System.Collections.Generic;
- using System.Collections.ObjectModel;
- using System.IO;
- using System.Linq;
- using System.Reflection;
- using System.Windows;
- using System.Windows.Media;
- using SCADA_DAQ.Plugin.CoreUI;
- using SCADA.CommonLib.License;
- namespace SCADA_DAQ
- {
- class Env
- {
- public static DILDBV1 DAL = null;
- public static bool EnvInitFinish = false;
- public static User NewUser;
- public static Schedual Schedual { get; internal set; } = Schedual.Instance;
- public static DateTime StartTime { get; set; }
- public static int StartTick { get; internal set; }
- public static DataBaseConfig CurrentDbConfig { get; set; }
- public static AutoSaveParameterItem<DatabaseSelector> CurrentDataBase { get; set; }
- public static DataBaseConfig SysDBConfig { get; set; }
- public static AutoSaveParameterItem<DatabaseSelector> SysDataBase { get; set; }
- public static DataBaseConfig AlarmDBConfig { get; set; }
- public static AutoSaveParameterItem<DatabaseSelector> AlarmDataBase { get; set; }
- public static AutoSaveParameterItem<ObservableCollection<DataBaseConfig>> DataBaseResource { get; set; }
- public static AutoSaveParameterItem<bool> DataBaseNeedRest { get; set; } = AutoSaveParameterItem.Create("App.DatabaseNeedRest", false);
- /// <summary>
- /// 产量个数
- /// </summary>
- public static AutoSaveParameterItem<int> TotalOutputPcs { get; set; } = AutoSaveParameterItem.Create("App.TotalOutputPcs", 0);
- /// <summary>
- /// 产量
- /// </summary>
- public static AutoSaveParameterItem<decimal> TotalOutputQty { get; set; } = AutoSaveParameterItem.Create("App.TotalOutputQty", 0m);
- public static void ParameterInit(IApp app)
- {
- CurrentDataBase = AutoSaveParameterItem.Create("App.DataBaseConfig", new DatabaseSelector()
- { CurrentDataBaseConfig = "Default" });
- SysDataBase = AutoSaveParameterItem.Create("App.DataBaseConfig.System", new DatabaseSelector()
- { CurrentDataBaseConfig = "SysDB" });
- AlarmDataBase = AutoSaveParameterItem.Create("App.DataBaseConfig.Alarm", new DatabaseSelector()
- { CurrentDataBaseConfig = "AlarmDB" });
- DataBaseResource = AutoSaveParameterItem.Create("App.DataBaseResource",
- new ObservableCollection<DataBaseConfig>()
- {
- new DataBaseConfig()
- {
- ResourceName="Default",
- DBType = DatabaseType.Sqlite,
- FilePath = @"Data\QwPlatform.db"
- },
- new DataBaseConfig()
- {
- ResourceName="AlarmDB",
- DBType = DatabaseType.Sqlite,
- FilePath = @"Data\QwPlatform.db"
- },
- new DataBaseConfig()
- {
- ResourceName="SysDB",
- DBType = DatabaseType.Sqlite,
- FilePath = @"Data\LocalApp.db"
- },
- }, true);
- dataBaseConfigInit(DataBaseResource, CurrentDataBase.Value, out var currentconfig);
- dataBaseConfigInit(DataBaseResource, SysDataBase.Value, out var sysConfig);
- dataBaseConfigInit(DataBaseResource, AlarmDataBase.Value, out var alarmConfig);
- CurrentDbConfig = currentconfig;
- AlarmDBConfig = alarmConfig;
- SysDBConfig = sysConfig;
- void dataBaseConfigInit(ObservableCollection<DataBaseConfig> srouce, DatabaseSelector selector, out DataBaseConfig config)
- {
- config = DataBaseResource.Value.FirstOrDefault(t => t.ResourceName == selector?.CurrentDataBaseConfig);
- selector.DataBaseConfigResource = DataBaseResource.Value;
- if (config == null)
- {
- config = DataBaseResource.Value.FirstOrDefault();
- selector.CurrentDataBaseConfig = config.ResourceName;
- }
- selector.DataBaseConfig = config;
- }
- app.ThemeConfig.ThemeNameSrc = new List<string> { "Light", "Dark" };
- app.ThemeConfig.ThemeColorSrc = new List<string>() { "Red", "Green", "Blue", "Purple", "Orange", "Lime", "Emerald", "Teal", "Cyan", "Cobalt", "Indigo", "Violet", "Pink", "Magenta", "Crimson", "Amber", "Yellow", "Brown", "Olive", "Steel", "Mauve", "Taupe", "Sienna" };
- app.ThemeConfig.LanguageSrc = new Dictionary<string, string>()
- {
- {"中文(简体)","zh-cn" },
- {"中文(繁体)","zh-tw" },
- {"English(US)","en-us" },
- {"Deutsch","de-de" },
- {"Руская","ru-ru" },
- {"日本語","ja-jp" },
- {"한국어","ko-kr" },
- {"ภาษาไทย","th-th"}
- };
- app.ThemeConfig.PropertyChanged += SystemConfig_PropertyChanged;
- bool neeRestDatabase = DataBaseNeedRest.Value;
- DAL = new DILDBV1(CurrentDbConfig.GetDB());
- CheckDataBase(DAL, CurrentDbConfig.NeedReset || DataBaseNeedRest.Value);
- //GlobalEnv.Instance.GlobalDB = DAL;
- //GlobalEnv.Instance.AlarmDB = new DILDBV1(AlarmDBConfig.GetDB());
- //CheckDataBase(GlobalEnv.Instance.AlarmDB as BaseDB, CurrentDbConfig.NeedReset || DataBaseNeedRest.Value);
- //GlobalEnv.Instance.LocalAppDB = new LocalDB.DIL.DILDBV1(SysDBConfig.GetDB());
- //CheckDataBase(GlobalEnv.Instance.LocalAppDB as BaseDB, CurrentDbConfig.NeedReset || DataBaseNeedRest.Value);
- app.RuntimeInfo.GlobalDB = DAL;
- app.RuntimeInfo.AlarmDB = new DILDBV1(AlarmDBConfig.GetDB());
- CheckDataBase(app.RuntimeInfo.AlarmDB as BaseDB, CurrentDbConfig.NeedReset || DataBaseNeedRest.Value);
- app.RuntimeInfo.LocalAppDB = new LocalDB.DIL.DILDBV1(SysDBConfig.GetDB());
- CheckDataBase(app.RuntimeInfo.LocalAppDB as BaseDB, CurrentDbConfig.NeedReset || DataBaseNeedRest.Value);
- NewUser = new User(DAL)
- {
- UserName = "Admin",
- PassWordReviseHandler = () =>
- {
- var passWordRevise = new FrmUserLogin(new PasswordReviseViewModel(NewUser));
- ((BaseMainWindow)Application.Current.MainWindow).ShowChildWindow(passWordRevise);
- },
- TryLoginHandler = () =>
- {
- if (NewUser.IsLogged == false)
- {
- FrmUserLogin frmUserLog = new FrmUserLogin(new UserLoginViewModel(NewUser));
- ((BaseMainWindow)Application.Current.MainWindow).ShowChildWindow(frmUserLog);
- }
- else
- {
- (Application.Current as IApp).ShowToast($"{LanguageHelper.GetStringByKey("SysCfg_CurrentUser")}{NewUser.UserName}", ControlStyle.Info);
- }
- },
- MidCheckHandler = () =>
- {
- var frmUserLog = new FrmUserLogin(new UserLoginViewModel(NewUser));
- if (NewUser.IsLogged == false)
- {
- ((BaseMainWindow)Application.Current.MainWindow).ShowChildWindow(frmUserLog);
- return NewUser.IsLogged;
- }
- else
- {
- return NewUser.IsLogged;
- }
- }
- };
- app.RuntimeInfo.User = NewUser;
- EnvInitFinish = true;
- }
- private static void SystemConfig_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
- {
- if (e.PropertyName == nameof(ThemeConfig.Language))
- {
- SetLanguage();
- }
- else if (e.PropertyName == nameof(ThemeConfig.ThemeColors) || e.PropertyName == nameof(ThemeConfig.ThemeName))
- {
- SetTheme();
- }
- else if (e.PropertyName == nameof(ThemeConfig.FontName) || e.PropertyName == nameof(ThemeConfig.FontSize) || e.PropertyName == nameof(ThemeConfig.FontWeight))
- {
- SetFont();
- }
- }
- static Env()
- {
- }
- public static void SetLanguage()
- {
- try
- {
- List<ResourceDictionary> dictionaryList = new List<ResourceDictionary>();
- foreach (ResourceDictionary dictionary in Application.Current.Resources.MergedDictionaries)
- {
- dictionaryList.Add(dictionary);
- }
- string requestedCulture = $@"{(Application.Current as IApp).ThemeConfig.Language}.xaml";
- ResourceDictionary resourceDictionary = null;
- ResourceDictionary defaultLanguage = null;
- foreach (var item in dictionaryList)
- {
- try
- {
- if (item.Source == null) continue;
- if (item.Source.Segments.LastOrDefault() == requestedCulture)
- {
- resourceDictionary = item;
- }
- if (item.Source.Segments.LastOrDefault() == "zh-cn.xaml")
- {
- defaultLanguage = item;
- }
- }
- catch (Exception)
- {
- }
- }
- if (requestedCulture == null) return;
- Application.Current.Resources.MergedDictionaries.Remove(resourceDictionary);
- Application.Current.Resources.MergedDictionaries.Add(resourceDictionary);
- LanguageHelper.CurrentLanguageDictionary = resourceDictionary;
- LanguageHelper.DefaultLanguageDictionary = defaultLanguage;
- }
- catch (Exception ex)
- {
- System.Diagnostics.Trace.TraceError($"{ex}");
- }
- }
- private static void Theme_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
- {
- SetTheme();
- }
- public static void SetTheme()
- {
- try
- {
- var themeConfig = (Application.Current as IApp).ThemeConfig;
- ThemeManager.Current.ChangeTheme(Application.Current, $"{themeConfig.ThemeName}.{themeConfig.ThemeColors}");
- }
- catch (Exception ex)
- {
- System.Diagnostics.Trace.TraceError($"{ex}");
- }
- }
- public static void SetFont()
- {
- var app = (Application.Current as IApp);
- Application.Current.Resources["DefaultFontWeight"] = FontWeight.FromOpenTypeWeight(app.ThemeConfig.FontWeight);
- Application.Current.Resources["DefaultFontSize"] = app.ThemeConfig.FontSize;
- Application.Current.Resources["DefaultFont"] = new FontFamily(app.ThemeConfig.FontName);
- }
- private static void CheckDataBase(BaseDB db, bool dataBaseNeedRest)
- {
- string databasepath = "";
- if (db.DatabaseType == DatabaseType.Sqlite)
- {
- databasepath = Path.Combine(db.ServerName, db.DatabaseInfo);
- }
- else
- {
- return;
- }
- if (dataBaseNeedRest) //用户设置了重置数据库
- {
- System.Diagnostics.Trace.TraceInformation($"用户请求重置数据库,数据库开始重置");
- if (ReleseDatabase())
- {
- DataBaseNeedRest.Value = false; //数据库重置成功
- }
- }
- else
- {
- if (File.Exists(databasepath))
- {
- //object dt = db.ExecuteScalar("PRAGMA integrity_check");
- //if ($"{dt}".ToUpper() == "OK")
- //{
- // System.Diagnostics.Debug.WriteLine($"{databasepath} 数据库检测正常");
- //}
- //else
- //{
- // Application.Current.Dispatcher.Invoke(new Action(() =>
- // {
- // if (MessageBox.Show(Application.Current?.MainWindow, LanguageHelper.GetStringByKey("SysCfg_DatabaseIsDamageTip"), LanguageHelper.SysCfg_Wran, MessageBoxButton.OK) == MessageBoxResult.OK)
- // {
- // System.Diagnostics.Trace.TraceWarning($"检测到本地数据库已损坏,开始重置数据库");
- // _ = ReleseDatabase();
- // }
- // }));
- //}
- }
- else
- {
- ReleseDatabase();
- }
- }
- bool ReleseDatabase()
- {
- try
- {
- if (File.Exists(databasepath))
- {
- File.Move(databasepath, $"{databasepath}.{DateTime.Now:yyyyMMddHHmmss}");
- }
- var assembly = Assembly.GetEntryAssembly();
- Stream res = null;
- var dbRes = LocalResource.ResourceManager.GetObject(Path.GetFileNameWithoutExtension(databasepath));
- if (dbRes is byte[] resBytes)
- {
- res = new MemoryStream(resBytes);
- }
- if (res == null) return true;
- using (res)
- {
- FileHelper.EnsureDirectoryExist(databasepath);
- byte[] save = ZipHelper.UnZip(res)[0];
- using (FileStream fsObj = new FileStream(databasepath, FileMode.Create))
- {
- fsObj.Write(save, 0, save.Length);
- fsObj.Close();
- }
- }
- System.Diagnostics.Debug.WriteLine($"{databasepath} 数据库修复成功");
- return true;
- }
- catch (Exception ex)
- {
- System.Diagnostics.Trace.Fail($"{databasepath} 数据库修复失败,{ex}");
- //_ = MessageBox.Show(Application.Current?.MainWindow, ex.ToString(), LanguageHelper.GetStringByKey("SysCfg_DatabaseRepairFail"));
- }
- return false;
- }
- }
- }
- }
|