using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Threading; using Aitex.Core.Account; using Aitex.Core.Common.DeviceData; using Aitex.Core.RT.Event; using Aitex.Core.RT.Log; using Aitex.Core.Util; using Aitex.Core.WCF; using Caliburn.Micro; using EfemDualUI.Views.History.ProcessHistory; using EfemDualUI.Views.PMs; using MECF.Framework.Common.Account.Extends; using MECF.Framework.Common.DataCenter; using MECF.Framework.Common.OperationCenter; using MECF.Framework.UI.Client.CenterViews.DataLogs.DataHistory; using MECF.Framework.UI.Client.CenterViews.LogOnOff; using MECF.Framework.UI.Client.ClientBase; using MECF.Framework.UI.Core.Accounts; using OpenSEMI.ClientBase; using OpenSEMI.ClientBase.Command; using OpenSEMI.ClientBase.Utility; using SciChart.Charting.ChartModifiers; using SciChart.Charting.Visuals; using SciChart.Charting.Visuals.Annotations; using SciChart.Charting.Visuals.Axes; using Cali = Caliburn.Micro.Core; using CalibrationTableViewModel = MECF.Framework.UI.Client.CenterViews.Maitenances.CalibrationTable.CalibrationTableViewModel; namespace EfemDualUI { public class TimeredMainViewModel : Cali.Conductor.Collection.OneActive { PeriodicJob _timer; ConcurrentBag _subscribedKeys = new ConcurrentBag(); Func _isSubscriptionAttribute; Func _hasSubscriptionAttribute; public TimeredMainViewModel() { _timer = new PeriodicJob(1000, this.OnTimer, "UIUpdaterThread - " + GetType().Name); _isSubscriptionAttribute = attribute => attribute is SubscriptionAttribute; _hasSubscriptionAttribute = mi => mi.GetCustomAttributes(false).Any(_isSubscriptionAttribute); SubscribeKeys(this); } [StructLayout(LayoutKind.Sequential)] internal struct LASTINPUTINFO { [MarshalAs(UnmanagedType.U4)] public int cbSize; [MarshalAs(UnmanagedType.U4)] public int dwTime; } [DllImport("user32.dll")] internal static extern bool GetLastInputInfo(ref LASTINPUTINFO plii); /// /// 获取鼠标键盘不活动的时间 /// /// 结果 public static int GetLastInputTime() { LASTINPUTINFO lastInputInfo = new LASTINPUTINFO(); lastInputInfo.cbSize = Marshal.SizeOf(lastInputInfo); lastInputInfo.dwTime = 0; int idleTime = 0; if (GetLastInputInfo(ref lastInputInfo)) { idleTime = Environment.TickCount - lastInputInfo.dwTime; } return ((idleTime > 0) ? (idleTime / 1000) : 0); } protected virtual bool OnTimer() { try { Poll(); } catch (Exception ex) { LOG.Error(ex.Message); } return true; } public virtual void EnableTimer(bool enable) { if (enable) _timer.Start(); else _timer.Pause(); } protected virtual void Poll() { if (_subscribedKeys.Count > 0) { Dictionary result = QueryDataClient.Instance.Service.PollData(_subscribedKeys); if (result == null) { LOG.Error("获取RT数据失败"); return; } if (result.Count != _subscribedKeys.Count) { string unknowKeys = string.Empty; foreach (string key in _subscribedKeys) { if (!result.ContainsKey(key)) { unknowKeys += key + "\r\n"; } } //System.Diagnostics.Debug.Assert(false, unknowKeys); } InvokeBeforeUpdateProperty(result); UpdateValue(result); Application.Current.Dispatcher.Invoke(new System.Action(() => { InvokePropertyChanged(); InvokeAfterUpdateProperty(result); })); } } private void InvokePropertyChanged() { Refresh(); } protected virtual void InvokeBeforeUpdateProperty(Dictionary data) { } protected virtual void InvokeAfterUpdateProperty(Dictionary data) { } void UpdateValue(Dictionary data) { if (data == null) return; UpdateSubscribe(data, this); var properties = GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => p.GetCustomAttribute() != null); foreach (var property in properties) { var moduleAttr = property.GetCustomAttribute(); UpdateSubscribe(data, property.GetValue(this), moduleAttr.Module); } } protected void Subscribe(string key) { if (!string.IsNullOrEmpty(key)) { _subscribedKeys.Add(key); } } public void SubscribeKeys(TimeredMainViewModel target) { Parallel.ForEach(target.GetType().GetProperties().Where(_hasSubscriptionAttribute), property => { SubscriptionAttribute subscription = property.GetCustomAttributes(false).First(_isSubscriptionAttribute) as SubscriptionAttribute; string key = subscription.ModuleKey; if (!_subscribedKeys.Contains(key)) _subscribedKeys.Add(key); }); Parallel.ForEach(target.GetType().GetFields().Where(_hasSubscriptionAttribute), method => { SubscriptionAttribute subscription = method.GetCustomAttributes(false).First(_isSubscriptionAttribute) as SubscriptionAttribute; string key = subscription.ModuleKey; if (!_subscribedKeys.Contains(key)) _subscribedKeys.Add(key); }); } public void UpdateSubscribe(Dictionary data, object target, string module = null) { Parallel.ForEach(target.GetType().GetProperties().Where(_hasSubscriptionAttribute), property => { PropertyInfo pi = (PropertyInfo)property; SubscriptionAttribute subscription = property.GetCustomAttributes(false).First(_isSubscriptionAttribute) as SubscriptionAttribute; string key = subscription.ModuleKey; key = module == null ? key : string.Format("{0}.{1}", module, key); if (_subscribedKeys.Contains(key) && data.ContainsKey(key)) { try { var convertedValue = Convert.ChangeType(data[key], pi.PropertyType); var originValue = Convert.ChangeType(pi.GetValue(target, null), pi.PropertyType); if (originValue != convertedValue) { if (pi.Name == "PumpLimitSetPoint") pi.SetValue(target, convertedValue, null); else pi.SetValue(target, convertedValue, null); } } catch (Exception ex) { LOG.Error("由RT返回的数据更新失败" + key, ex); } } }); Parallel.ForEach(target.GetType().GetFields().Where(_hasSubscriptionAttribute), property => { FieldInfo pi = (FieldInfo)property; SubscriptionAttribute subscription = property.GetCustomAttributes(false).First(_isSubscriptionAttribute) as SubscriptionAttribute; string key = subscription.ModuleKey; if (_subscribedKeys.Contains(key) && data.ContainsKey(key)) { try { var convertedValue = Convert.ChangeType(data[key], pi.FieldType); pi.SetValue(target, convertedValue); } catch (Exception ex) { LOG.Error("由RT返回的数据更新失败" + key, ex); } } }); } } public class MainViewModel : TimeredMainViewModel { #region Menus public string NowDateTime { get; set; } private bool _IsLogin = false; public bool IsLogin { get { return _IsLogin; } set { _IsLogin = value; NotifyOfPropertyChange("IsLogin"); } } private List roles; public List Roles { get { return this.roles; } set { this.roles = value; this.RaisePropertyChangedEventImmediately("Roles"); } } private ICommand menuItemClickCommand; public ICommand MenuItemClickCommand { get { if (this.menuItemClickCommand == null) this.menuItemClickCommand = new BaseCommand((AppMenu menuViewItem) => this.SwitchMenuItem(menuViewItem)); return this.menuItemClickCommand; } } private ICommand mainmenuItemClickCommand; public ICommand MainMenuItemClickCommand { get { if (this.mainmenuItemClickCommand == null) this.mainmenuItemClickCommand = new BaseCommand((AppMenu menuViewItem) => this.MainSwitchMenuItem(menuViewItem)); return this.mainmenuItemClickCommand; } } public List MenuItems { get { return this.menuItems; } set { this.menuItems = value; this.NotifyOfPropertyChange("MenuItems"); } } public List SubMenuItems { get { return this.subMenuItems; } set { this.subMenuItems = value; this.NotifyOfPropertyChange("SubMenuItems"); } } public ObservableCollection HistoryMenus { get { return this.historyItems; } set { this.historyItems = value; this.NotifyOfPropertyChange("HistoryMenus"); } } public string Context { get { return this.context; } set { this.context = value; this.NotifyOfPropertyChange("Context"); } } public BaseModel CurrentViewModel { get; private set; } public UserContext User { get { return BaseApp.Instance.UserContext; } } private AppMenu _currentMenuItem; private List menuItems; private List subMenuItems; private ObservableCollection historyItems; private string context; private MainView _view; private Dictionary _models; #endregion public bool IsPermission { get; set; } public bool IsAutoLogout { get; set; } public int LogoutTime { get; set; } public ObservableCollection WarnEventLogList { get; set; } public ObservableCollection EventLogList { get; set; } public Visibility AllEventsVisibility { get; set; } public Visibility WarnEventsVisibility { get; set; } [Subscription("Rt.Status")] public string RtStatus { get; set; } public string RtStatusBackground { get { return ModuleStatusBackground.GetStatusBackground(RtStatus); } } [Subscription("EFEM.Status")] public string EfemStatus { get; set; } public string EfemStatusBackground { get { return ModuleStatusBackground.GetStatusBackground(EfemStatus); } } [Subscription("TM.Status")] public string TMStatus { get; set; } public string TMStatusBackground { get { return ModuleStatusBackground.GetStatusBackground(TMStatus); } } #region FA [Subscription("System.ControlStatus")] public string SystemControlStatus { get; set; } public string ControlStatus { get { return SystemControlStatus; } set { } } public string ControlStatusBackground { get { switch (SystemControlStatus) { case "Unknown": return "Yellow"; case "EquipmentOffline": case "AttemptOnline": case "HostOffline": return "Yellow"; case "OnlineLocal": case "OnlineRemote": return "LawnGreen"; default: return "Yellow"; } } } /// Disabled = 0, /// Enabled = 1, /// EnabledNotCommunicating = 2, /// EnabledCommunicating = 3, /// WaitCRA = 4, /// WaitDelay = 5, /// WaitCRFromHost = 6, public string HostStatusBackground { get { switch (HostCommunicationStatus) { case "EnabledNotCommunicating": case "WaitCRA": case "Enabled": case "WaitDelay": case "WaitCRFromHost": return "Yellow"; case "EnabledCommunicating": if (SystemControlStatus == "OnlineRemote") return "LawnGreen"; return "White"; default: return "Yellow"; } } } /// ///Disabled, ///Enabled, ///EnabledNotCommunicating, ///EnabledCommunicating, ///WaitCRA, ///WaitDelay, ///WaitCRFromHost, /// public string HostStatus { get { switch (HostCommunicationStatus) { case "EnabledNotCommunicating": case "WaitCRA": case "Enabled": case "WaitDelay": case "WaitCRFromHost": return "Connecting"; case "EnabledCommunicating": if (SystemControlStatus == "OnlineRemote") return "OnlineRemote"; if (SystemControlStatus == "OnlineLocal") return "OnlineLocal"; return "Offline"; default: return "Disconnect"; } } set { } } [Subscription("System.CommunicationStatus")] public string HostCommunicationStatus { get; set; } public bool IsEnableFAEnable { get { return HostCommunicationStatus == "Disabled"; } } public bool IsDisableFAEnable { get { return HostCommunicationStatus != "Disabled"; } } #endregion #region LP [Subscription("LP1.IsPlaced")] public bool IsLP1Placed { get; set; } [Subscription("LP2.IsPlaced")] public bool IsLP2Placed { get; set; } [Subscription("LP3.IsPlaced")] public bool IsLP3Placed { get; set; } #endregion public string PMAStatus { get { return $"{PMAEntityStatus}"; } set { } } [Subscription("PMA.Chamber.ServiceStatus")] public string PMAServiceStatus { get; set; } [Subscription("PMA.Status")] public string PMAEntityStatus { get; set; } public string PMAStatusBackground { get { return ModuleStatusBackground.GetStatusBackground(PMAEntityStatus); } } public string PMBStatus { get { return $"{PMBEntityStatus}"; } set { } } [Subscription("PMB.Chamber.ServiceStatus")] public string PMBServiceStatus { get; set; } [Subscription("PMB.Status")] public string PMBEntityStatus { get; set; } public string PMBStatusBackground { get { return ModuleStatusBackground.GetStatusBackground(PMBEntityStatus); } } [Subscription("System.SignalTower.DeviceData")] public AITSignalTowerData SignalTowerData { get; set; } public string SoftwareVersion { get; set; } public string RunTime { get { return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); } } public string LogoTooltip { get { return $"Software Version: {SoftwareVersion}"; } } [Subscription("PMA.IsOnline")] public bool IsOnlinePMA { get; set; } [Subscription("PMB.IsOnline")] public bool IsOnlinePMB { get; set; } [Subscription("System.HasActiveAlarm")] public bool SystemHasAlarm { get; set; } private AppMenu _alarmMenu; public MainViewModel() { BaseApp.Instance.Initialize(); ((ClientApp)BaseApp.Instance).ViewModelSwitcher = this; this._models = new Dictionary(); //for login part Roles = RoleAccountProvider.Instance.GetRoles(); EventLogList = new ObservableCollection(); WarnEventLogList = new ObservableCollection(); SoftwareVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(); EventClient.Instance.OnEvent += Instance_OnEvent; EventClient.Instance.OnDisconnectedWithRT += Instance_OnDisconnectedWithRT; EventClient.Instance.Start(); //Reset(); } private void Instance_OnDisconnectedWithRT() { MessageBox.Show("Disconnected with RT, UI will exit", "Error", MessageBoxButton.OK, MessageBoxImage.Error); Environment.Exit(0); } public void ShowAlarmEvents() { AllEventsVisibility = Visibility.Hidden; WarnEventsVisibility = Visibility.Visible; this.NotifyOfPropertyChange("AllEventsVisibility"); this.NotifyOfPropertyChange("WarnEventsVisibility"); } public void ShowAllEvents() { AllEventsVisibility = Visibility.Visible; WarnEventsVisibility = Visibility.Hidden; this.NotifyOfPropertyChange("AllEventsVisibility"); this.NotifyOfPropertyChange("WarnEventsVisibility"); } private void PopDialog(EventItem obj) { Application.Current.Dispatcher.Invoke(() => { DialogBox.ShowInfo(obj.Explaination); }); //MessageBox.Show(obj.Explaination,"Information",MessageBoxButton.OK,MessageBoxImage.Information); } private void Instance_OnEvent(EventItem obj) { switch (obj.Type) { case EventType.EventUI_Notify: LogEvent(obj); break; case EventType.Dialog_Nofity: PopDialog(obj); break; case EventType.KickOut_Notify: if (obj.Description == "ShutDown") { AccountClient.Instance.Service.LogoutEx(BaseApp.Instance.UserContext.LoginName, BaseApp.Instance.UserContext.LoginId); ShutdownThread = ShutdownExecute; ShutdownThread.BeginInvoke(ShutdownCallBack, ShutdownThread); } break; case EventType.Sound_Notify: break; case EventType.UIMessage_Notify: //PopUIMessage(obj); break; } } void LogEvent(EventItem obj) { if (obj.Type != EventType.EventUI_Notify) return; Application.Current.Dispatcher.Invoke(() => { while (EventLogList.Count > 100) { EventLogList.RemoveAt(0); } EventLogList.Add(obj); if (obj.Level == EventLevel.Alarm) this.WarnEventLogList.Add(obj); }); } public void FAEnable() { InvokeClient.Instance.Service.DoOperation("FACommand", "FAEnable"); } public void FADisable() { InvokeClient.Instance.Service.DoOperation("FACommand", "FADisable"); } #region login part public void Enter(KeyEventArgs args, string loginName, PasswordBox password, Role role) { if (args.Key == Key.Enter) this.Login(loginName, password, role); } public void Login(string loginName, PasswordBox password, Role role) { try { LoginResult result = AccountClient.Instance.Service.LoginEx(loginName, password.Password, role.RoleID); if (result.ActSucc) { ClientApp.Instance.UserContext.LoginId = result.SessionId; ClientApp.Instance.UserMode = UserMode.Normal; ClientApp.Instance.UserContext.LoginName = loginName; ClientApp.Instance.UserContext.Role = role; ClientApp.Instance.UserContext.RoleID = role.RoleID; ClientApp.Instance.UserContext.RoleName = role.RoleName; ClientApp.Instance.UserContext.LoginTime = DateTime.Now; //ClientApp.Instance.UserContext.Token = token; ClientApp.Instance.UserContext.LastAccessTime = DateTime.Now; ClientApp.Instance.UserContext.IsLogin = true; //Load menu by role //filer menu if necessary... ClientApp.Instance.MenuManager.LoadMenu(RoleAccountProvider.Instance.GetMenusByRole(role.RoleID, ClientApp.Instance.MenuLoader.MenuList)); IsAutoLogout = role.IsAutoLogout; LogoutTime = role.LogoutTime; IsPermission = RoleAccountProvider.Instance.GetMenuPermission(role.RoleID, "Header") == 3; InitMenu(); //bind menu to main view IsLogin = true; //control the display logic of main view LOG.Info(string.Format("{0} login as {1}", loginName, role.RoleName)); } else { Enum.TryParse(result.Description, out AuthorizeResult errCode); switch (errCode) { case AuthorizeResult.None: DialogBox.ShowError("Not connected with RT."); break; case AuthorizeResult.WrongPwd: DialogBox.ShowError("Invalid password."); break; case AuthorizeResult.HasLogin: DialogBox.ShowError("{0} has already logged in.", loginName); break; case AuthorizeResult.NoMatchRole: DialogBox.ShowError("{0} does not match {1} role.", loginName, role.RoleName); break; case AuthorizeResult.NoMatchUser: DialogBox.ShowError("{0} does not exists.", loginName); break; case AuthorizeResult.NoSession: DialogBox.ShowError("The current session is invalid."); break; } } password.Clear(); } catch (Exception ex) { LOG.Error(ex.Message, ex); } } #endregion public void PutModuleOnline(string module) { InvokeClient.Instance.Service.DoOperation($"{module}.PutOnline"); } public void PutModuleOffline(string module) { InvokeClient.Instance.Service.DoOperation($"{module}.PutOffline"); } public void Logout() { this.OnLogoutCommand(); } public void OnLogoutCommand() { WindowManager windowmanager = new WindowManager(); var logoffViewmodel = new LogoffViewModel(); windowmanager.ShowDialog(logoffViewmodel); BaseApp.Instance.UserMode = logoffViewmodel.DialogResult; switch (logoffViewmodel.DialogResult) { case UserMode.Logoff: Logoff(); break; case UserMode.Exit: AccountClient.Instance.Service.LogoutEx(BaseApp.Instance.UserContext.LoginName, BaseApp.Instance.UserContext.LoginId); BaseApp.Instance.UserMode = UserMode.Exit; LOG.Info(string.Format("{0} exit as {1}", BaseApp.Instance.UserContext.LoginName, BaseApp.Instance.UserContext.RoleName)); this.TryClose(); break; case UserMode.Shutdown: InvokeClient.Instance.Service.DoOperation("System.ShutDown"); break; } } public void Logoff() { BaseApp.Instance.UserMode = UserMode.Logoff; if (BaseApp.Instance.UserContext.IsLogin) { try { AccountClient.Instance.Service.LogoutEx(BaseApp.Instance.UserContext.LoginName, BaseApp.Instance.UserContext.LoginId); BaseApp.Instance.UserContext.IsLogin = false; LOG.Info(string.Format("{0} logoff as {1}", BaseApp.Instance.UserContext.LoginName, BaseApp.Instance.UserContext.RoleName)); } catch (Exception exp) { LOG.Write(exp); } } IsLogin = false; //no independent login page Roles = RoleAccountProvider.Instance.GetRoles(); } public void Reset() { InvokeClient.Instance.Service.DoOperation("System.Reset"); } public void BuzzerOff() { InvokeClient.Instance.Service.DoOperation($"System.SignalTower.{AITSignalTowerOperation.SwitchOffBuzzer}"); } #region override functions public override void CanClose(Action callback) { if (BaseApp.Instance.UserMode == UserMode.Normal) { callback(false); Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, (ThreadStart)delegate { this.OnLogoutCommand(); }); } else callback(true); } protected override void OnInitialize() { //display system version or other info... this.DisplayName = $"Efem Dual Tool (V{SoftwareVersion})"; base.OnInitialize(); this.StartTimer(); //DrawSciChart(); if (Debugger.IsAttached) { Login("admin", new PasswordBox() { Password = "admin" }, Roles.Find(x => x.RoleName == "Manager")); } } protected override void OnActivate() { base.OnActivate(); this.ShowAllEvents(); EnableTimer(true); } void DrawSciChart() { // Create the chart surface var sciChartSurface = new SciChartSurface(); // Create the X and Y Axis var xAxis = new NumericAxis() { AxisTitle = "Number of Samples (per series)" }; var yAxis = new NumericAxis() { AxisTitle = "Value" }; sciChartSurface.XAxis = xAxis; sciChartSurface.YAxis = yAxis; // Specify Interactivity Modifiers sciChartSurface.ChartModifier = new ModifierGroup(new RubberBandXyZoomModifier(), new ZoomExtentsModifier()); // Add annotation hints to the user var textAnnotation = new TextAnnotation() { Text = "Hello World!", X1 = 5.0, Y1 = 5.0 }; sciChartSurface.Annotations.Add(textAnnotation); } protected override void OnViewLoaded(object view) { base.OnViewLoaded(view); this._view = view as MainView; //this._view.tbLoginName.Focus(); } protected override void OnDeactivate(bool close) { base.OnDeactivate(close); EnableTimer(false); } #endregion #region #region Sync ShutDown Thread public delegate void ShutDownSysncThread(); ShutDownSysncThread ShutdownThread = null; ShutdownViewModel ShutdownWindow = null; private void ShutdownExecute() { BaseApp.Instance.UserMode = UserMode.Shutdown; BaseApp.Instance.UserContext.IsLogin = false; LOG.Info(string.Format("{0} shutdown as {1}", BaseApp.Instance.UserContext.LoginName, BaseApp.Instance.UserContext.RoleName)); this.TryClose(); } private void ShutdownCallBack(IAsyncResult result) { if (ShutdownWindow != null) { ShutdownWindow.TryClose(); } ShutdownThread.EndInvoke(result); } #endregion #region Menu Control and page switch private void InitMenu() { this.MenuItems = BaseApp.Instance.MenuManager.MenuItems; this.SubMenuItems = new List(); this.HistoryMenus = new ObservableCollection(); if (this.MenuItems.Count > 0) { AppMenu _default = null; foreach (AppMenu menuitem in this.MenuItems) { if (menuitem.MenuItems.Count > 0) { if (menuitem.AlarmModule == "System") { _alarmMenu = menuitem; break; } if (_default == null) _default = menuitem.MenuItems[0]; } } this.SwitchMenuItem(_default); } } public void MainSwitchMenuItem(AppMenu menuViewItem) { if (menuViewItem.MenuItems.Count > 0) { if (menuViewItem.LastSelectedSubMenu != null) SwitchMenuItem(menuViewItem.LastSelectedSubMenu); else SwitchMenuItem(menuViewItem.MenuItems[0]); } } Stopwatch _sw = new Stopwatch(); public void SwitchMenuItem(AppMenu menuViewItem, object parameter = null) { _sw.Restart(); if (menuViewItem.ViewModel != null && menuViewItem.ViewModel != string.Empty) { if (menuViewItem.Model == null) { menuViewItem.Model = (BaseModel)AssemblyUtil.CreateInstance(AssemblyUtil.GetType(menuViewItem.ViewModel)); ((BaseModel)menuViewItem.Model).Permission = menuViewItem.Permission; ((BaseModel)menuViewItem.Model).Token = BaseApp.Instance.UserContext.Token; if (menuViewItem.Model is ISupportMultipleSystem) (menuViewItem.Model as ISupportMultipleSystem).SystemName = menuViewItem.System; if (menuViewItem.Model is CalibrationTableViewModel) { var viewModel = (menuViewItem.Model as CalibrationTableViewModel); if (viewModel.CustomParameter == null) viewModel.CustomParameter = new CustomCalibration(viewModel.SystemName); } } this.ActivateItem(((BaseModel)menuViewItem.Model)); CurrentViewModel = ((BaseModel)menuViewItem.Model); //if (((BaseModel)menuViewItem.Model).Page != PageID.MAX_PAGE) // BaseApp.Instance.SetCurrentPage(((BaseModel)menuViewItem.Model).Page); this.HandleSubAndHistoryMenu(menuViewItem); if (this._currentMenuItem != null) { this._currentMenuItem.Selected = false; this._currentMenuItem.Parent.Selected = false; } menuViewItem.Selected = true; menuViewItem.Parent.Selected = true; menuViewItem.Parent.LastSelectedSubMenu = menuViewItem; this._currentMenuItem = menuViewItem; if (menuViewItem.Model is DataViewModel && parameter != null) { Task.Delay(1000).ContinueWith((x) => { var viewModel = (menuViewItem.Model as DataViewModel); viewModel.Query(parameter); }); } if (menuViewItem.Model is ProcessHistoryViewModel && parameter != null) { Task.Delay(1000).ContinueWith((x) => { var viewModel = (menuViewItem.Model as ProcessHistoryViewModel); viewModel.Query(parameter); }); } } float elapsed = _sw.ElapsedMilliseconds; System.Diagnostics.Trace.WriteLine($"===>SwitchMenuItem time consume: {elapsed} MS"); _sw.Stop(); } private void HandleSubAndHistoryMenu(AppMenu menuitem) { this.SubMenuItems = menuitem.Parent.MenuItems; if (!this.HistoryMenus.Contains(menuitem)) { if (this.HistoryMenus.Count >= 8) this.HistoryMenus.RemoveAt(7); this.HistoryMenus.Insert(0, menuitem); } else { this.HistoryMenus.Remove(menuitem); this.HistoryMenus.Insert(0, menuitem); } } public bool SwitchPage(string firstLevelMenuID, string secondLevelMenuID, object parameter) { foreach (AppMenu menuitem in BaseApp.Instance.MenuManager.MenuItems) { if (menuitem.MenuID == firstLevelMenuID) { foreach (AppMenu menu in menuitem.MenuItems) { if (menu.MenuID == secondLevelMenuID) { SwitchMenuItem(menu, parameter); return true; } } } } return false; } #endregion #region Refresh Date Time on page protected override void InvokeAfterUpdateProperty(Dictionary data) { if (_alarmMenu != null) _alarmMenu.IsAlarm = SystemHasAlarm; } protected override bool OnTimer() { try { base.Poll(); List roles = RoleAccountProvider.Instance.GetRoles(); if (!string.IsNullOrEmpty(ClientApp.Instance.UserContext.RoleName)) { Role role = roles.Find(x => x.RoleName == ClientApp.Instance.UserContext.RoleName); LogoutTime = role.LogoutTime; IsAutoLogout = role.IsAutoLogout; int intervaltime = GetLastInputTime(); //if (System.DateTime.Now >= ClientApp.Instance.UserContext.LoginTime.AddMinutes(LogoutTime) && IsLogin && IsAutoLogout) if (intervaltime >= LogoutTime * 60 && IsLogin && IsAutoLogout) Logoff(); } App.Current.Dispatcher.Invoke((System.Action)(() => { foreach (Window window in Application.Current.Windows) { var mdv = window.Content as MessageDialogView; if (mdv != null) { var mdvm = mdv.DataContext as MessageDialogViewModel; if (mdvm != null && mdvm.DisplayName == "Dialog Box") { if ((!IsLP1Placed && mdvm.Text.Contains("LP1")) || (!IsLP2Placed && mdvm.Text.Contains("LP2")) || (!IsLP3Placed && mdvm.Text.Contains("LP3"))) mdvm.TryClose(); } } } })); } catch (Exception ex) { LOG.Error(ex.Message); } return true; } private void StartTimer() { System.Windows.Threading.DispatcherTimer myDispatcherTimer = new System.Windows.Threading.DispatcherTimer(); myDispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 1000); myDispatcherTimer.Tick += new EventHandler(Each_Tick); myDispatcherTimer.Start(); } public void Each_Tick(object o, EventArgs sender) { this.NowDateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); this.NotifyOfPropertyChange("NowDateTime"); } #endregion #endregion } }