private StartStopMineButtonViewModel()
 {
     if (WpfUtil.IsInDesignMode)
     {
         return;
     }
     VirtualRoot.BuildCmdPath <StopMineCommand>(this.GetType(), LogEnum.DevConsole, path: message => {
         if (!NTMinerContext.Instance.IsMining)
         {
             this.MinerProfile.IsMining = false;
         }
         NTMinerContext.IsAutoStartCanceled = true;
         NTMinerContext.Instance.StopMineAsync(StopMineReason.LocalUserAction, () => {
             if (!NTMinerContext.Instance.IsMining)
             {
                 this.MinerProfile.IsMining = false;
             }
         });
     });
     this.StartMine = new DelegateCommand(() => {
         VirtualRoot.ThisLocalInfo(nameof(StartStopMineButtonViewModel), $"手动开始挖矿", toConsole: true);
         NTMinerContext.Instance.StartMine();
     });
     this.StopMine = new DelegateCommand(() => {
         VirtualRoot.ThisLocalInfo(nameof(StartStopMineButtonViewModel), $"手动停止挖矿", toConsole: true);
         VirtualRoot.Execute(new StopMineCommand());
     });
 }
예제 #2
0
        /// <summary>
        /// 命令窗口。使用该方法的代码行应将前两个参数放在第一行以方便vs查找引用时展示出参数信息
        /// </summary>
        public void AddCmdPath <TCmd>(LogEnum logType, Type location, Action <TCmd> path)
            where TCmd : ICmd
        {
            var messagePathId = VirtualRoot.BuildCmdPath(location, logType, path);

            _contextPathIds.Add(messagePathId);
        }
예제 #3
0
 public GpuProfileSet(INTMinerContext ntminerContext)
 {
     VirtualRoot.BuildCmdPath <AddOrUpdateGpuProfileCommand>(path: message => {
         GpuProfileData data = _data.GpuProfiles.FirstOrDefault(a => a.CoinId == message.Input.CoinId && a.Index == message.Input.Index);
         if (data != null)
         {
             data.Update(message.Input);
             Save();
         }
         else
         {
             data = new GpuProfileData().Update(message.Input);
             _data.GpuProfiles.Add(data);
             Save();
         }
         VirtualRoot.RaiseEvent(new GpuProfileAddedOrUpdatedEvent(message.MessageId, data));
     }, location: this.GetType());
     // 注意:这个命令处理程序不能放在展示层注册。修复通过群控超频不生效的BUG:这是一个难以发现的老BUG,以前的版本也存
     // 在这个BUG,BUG具体表现是当没有点击过挖矿端主界面上的算力Tab页时通过群控超频无效。感谢矿友发现问题,已经修复。
     VirtualRoot.BuildCmdPath <CoinOverClockCommand>(path: message => {
         Task.Factory.StartNew(() => {
             CoinOverClock(ntminerContext, message.CoinId);
             VirtualRoot.RaiseEvent(new CoinOverClockDoneEvent(targetPathId: message.MessageId));
         });
     }, location: this.GetType());
 }
예제 #4
0
 public UserSet(IUserDataRedis redis, IUserMqSender mqSender) : base(redis)
 {
     _redis    = redis;
     _mqSender = mqSender;
     VirtualRoot.BuildCmdPath <UpdateUserRSAKeyMqCommand>(this.GetType(), LogEnum.DevConsole, path: message => {
         if (message.AppId == ServerRoot.HostConfig.ThisServerAddress)
         {
             return;
         }
         if (string.IsNullOrEmpty(message.LoginName))
         {
             return;
         }
         if (IsOldMqMessage(message.Timestamp))
         {
             NTMinerConsole.UserOk(nameof(UpdateUserRSAKeyMqCommand) + ":" + MqKeyword.SafeIgnoreMessage);
             return;
         }
         if (message.Key != null && _dicByLoginName.TryGetValue(message.LoginName, out UserData userData))
         {
             userData.Update(message.Key);
             redis.SetAsync(userData).ContinueWith(t => {
                 _mqSender.SendUserRSAKeyUpdated(message.LoginName);
             });
         }
     });
 }
예제 #5
0
 public KernelOutputKeywordSet(string dbFileFullName)
 {
     if (string.IsNullOrEmpty(dbFileFullName))
     {
         throw new ArgumentNullException(nameof(dbFileFullName));
     }
     _connectionString = $"filename={dbFileFullName}";
     VirtualRoot.BuildCmdPath <AddOrUpdateKernelOutputKeywordCommand>(path: (message) => {
         InitOnece();
         DataLevel dataLevel = DataLevel.Global;
         if (_dicById.TryGetValue(message.Input.GetId(), out KernelOutputKeywordData exist))
         {
             exist.Update(message.Input);
             exist.SetDataLevel(dataLevel);
             using (LiteDatabase db = new LiteDatabase(_connectionString)) {
                 var col = db.GetCollection <KernelOutputKeywordData>();
                 col.Update(exist);
             }
         }
         else
         {
             KernelOutputKeywordData entity = new KernelOutputKeywordData().Update(message.Input);
             entity.SetDataLevel(dataLevel);
             _dicById.Add(entity.Id, entity);
             if (!_dicByKernelOutputId.TryGetValue(entity.KernelOutputId, out List <IKernelOutputKeyword> list))
             {
                 list = new List <IKernelOutputKeyword>();
                 _dicByKernelOutputId.Add(entity.KernelOutputId, list);
             }
             list.Add(entity);
             using (LiteDatabase db = new LiteDatabase(_connectionString)) {
                 var col = db.GetCollection <KernelOutputKeywordData>();
                 col.Insert(entity);
             }
         }
     }, location: this.GetType());
     VirtualRoot.BuildCmdPath <RemoveKernelOutputKeywordCommand>(path: (message) => {
         InitOnece();
         if (message == null || message.EntityId == Guid.Empty)
         {
             return;
         }
         if (!_dicById.ContainsKey(message.EntityId))
         {
             return;
         }
         KernelOutputKeywordData entity = _dicById[message.EntityId];
         _dicById.Remove(entity.GetId());
         if (_dicByKernelOutputId.TryGetValue(entity.KernelOutputId, out List <IKernelOutputKeyword> list))
         {
             list.Remove(entity);
         }
         using (LiteDatabase db = new LiteDatabase(_connectionString)) {
             var col = db.GetCollection <KernelOutputKeywordData>();
             col.Delete(message.EntityId);
         }
     }, location: this.GetType());
 }
        public LocalKernelOutputKeywordSet(string dbFileFullName)
        {
            _dbFileFullName = dbFileFullName;
            VirtualRoot.BuildCmdPath <SetKernelOutputKeywordCommand>(action: (message) => {
                InitOnece();
                if (message == null || message.Input == null || message.Input.GetId() == Guid.Empty)
                {
                    throw new ArgumentNullException();
                }
                if (_dicById.ContainsKey(message.Input.GetId()))
                {
                    return;
                }
                if (string.IsNullOrEmpty(message.Input.MessageType))
                {
                    throw new ValidationException("MessageType can't be null or empty");
                }
                if (string.IsNullOrEmpty(message.Input.Keyword))
                {
                    throw new ValidationException("Keyword can't be null or empty");
                }
                if (_dicById.Values.Any(a => a.KernelOutputId == message.Input.KernelOutputId && a.Keyword == message.Input.Keyword && a.Id != message.Input.GetId()))
                {
                    throw new ValidationException($"关键字{message.Input.Keyword}已存在");
                }
                KernelOutputKeywordData entity = new KernelOutputKeywordData().Update(message.Input);
                _dicById.Add(entity.Id, entity);
                using (LiteDatabase db = new LiteDatabase(_dbFileFullName)) {
                    var col = db.GetCollection <KernelOutputKeywordData>();
                    col.Upsert(entity);
                }

                VirtualRoot.RaiseEvent(new KernelOutputKeyworSetedEvent(entity));
            });
            VirtualRoot.BuildCmdPath <RemoveKernelOutputKeywordCommand>(action: (message) => {
                InitOnece();
                if (message == null || message.EntityId == Guid.Empty)
                {
                    throw new ArgumentNullException();
                }
                if (!_dicById.ContainsKey(message.EntityId))
                {
                    return;
                }
                KernelOutputKeywordData entity = _dicById[message.EntityId];
                _dicById.Remove(entity.GetId());
                using (LiteDatabase db = new LiteDatabase(_dbFileFullName)) {
                    var col = db.GetCollection <KernelOutputKeywordData>();
                    col.Delete(message.EntityId);
                }

                VirtualRoot.RaiseEvent(new KernelOutputKeywordRemovedEvent(entity));
            });
        }
예제 #7
0
 public MinerProfile(INTMinerContext ntminerContext)
 {
     _ntminerContext = ntminerContext;
     VirtualRoot.BuildCmdPath <RefreshAutoBootStartCommand>(location: this.GetType(), LogEnum.DevConsole, path: message => {
         var minerProfileRepository = ntminerContext.ServerContext.CreateLocalRepository <MinerProfileData>();
         var data = minerProfileRepository.GetAll().FirstOrDefault();
         if (data != null && _data != null)
         {
             _data.IsAutoBoot  = data.IsAutoBoot;
             _data.IsAutoStart = data.IsAutoStart;
             VirtualRoot.RaiseEvent(new AutoBootStartRefreshedEvent());
         }
     });
     Init(ntminerContext);
 }
예제 #8
0
 public LocalMessageSet(string dbFileFullName)
 {
     if (!string.IsNullOrEmpty(dbFileFullName))
     {
         _connectionString = $"filename={dbFileFullName};journal=false";
     }
     VirtualRoot.BuildCmdPath <AddLocalMessageCommand>(action: message => {
         if (string.IsNullOrEmpty(_connectionString))
         {
             return;
         }
         InitOnece();
         var data = LocalMessageData.Create(message.Input);
         // TODO:批量持久化,异步持久化
         List <ILocalMessage> removes = new List <ILocalMessage>();
         lock (_locker) {
             _records.AddFirst(data);
             while (_records.Count > NTKeyword.LocalMessageSetCapacity)
             {
                 var toRemove = _records.Last;
                 removes.Add(toRemove.Value);
                 _records.RemoveLast();
                 using (LiteDatabase db = new LiteDatabase(_connectionString)) {
                     var col = db.GetCollection <LocalMessageData>();
                     col.Delete(toRemove.Value.Id);
                 }
             }
         }
         using (LiteDatabase db = new LiteDatabase(_connectionString)) {
             var col = db.GetCollection <LocalMessageData>();
             col.Insert(data);
         }
         VirtualRoot.RaiseEvent(new LocalMessageAddedEvent(message.Id, data, removes));
     });
     VirtualRoot.BuildCmdPath <ClearLocalMessageSetCommand>(action: message => {
         if (string.IsNullOrEmpty(_connectionString))
         {
             return;
         }
         lock (_locker) {
             _records.Clear();
         }
         using (LiteDatabase db = new LiteDatabase(_connectionString)) {
             db.DropCollection(nameof(LocalMessageData));
         }
         VirtualRoot.RaiseEvent(new LocalMessageSetClearedEvent());
     });
 }
예제 #9
0
 public AbstractAppViewFactory()
 {
     VirtualRoot.BuildCmdPath <CloseNTMinerCommand>(path: message => {
         // 不能推迟这个日志记录的时机,因为推迟会有windows异常日志
         VirtualRoot.ThisLocalInfo(nameof(AbstractAppViewFactory), $"退出{VirtualRoot.AppName}。原因:{message.Reason}");
         UIThread.Execute(() => {
             try {
                 Application.Current.Shutdown();
             }
             catch (Exception ex) {
                 Logger.ErrorDebugLine(ex);
                 Environment.Exit(0);
             }
         });
     }, location: typeof(AbstractAppViewFactory));
 }
예제 #10
0
 public LocalMessageSet()
 {
     if (ClientAppType.IsMinerClient)
     {
         LocalMessageDtoSet = new LocalMessageDtoSet();
     }
     VirtualRoot.BuildCmdPath <AddLocalMessageCommand>(location: this.GetType(), LogEnum.DevConsole, path: message => {
         InitOnece();
         var data = LocalMessageData.Create(message.Input);
         List <ILocalMessage> removeds = new List <ILocalMessage>();
         lock (_dbToInserts) {
             _records.AddFirst(data);
             _dbToInserts.Add(data);
             while (_records.Count > NTKeyword.LocalMessageSetCapacity)
             {
                 var toRemove = _records.Last.Value;
                 removeds.Add(toRemove);
                 _records.RemoveLast();
             }
             _dbToRemoveIds.AddRange(removeds.Select(a => a.Id));
         }
         LocalMessageDtoSet.Add(data.ToDto());
         VirtualRoot.RaiseEvent(new LocalMessageAddedEvent(message.MessageId, data, removeds));
     });
     VirtualRoot.BuildCmdPath <ClearLocalMessageSetCommand>(location: this.GetType(), LogEnum.DevConsole, path: message => {
         lock (_dbToInserts) {
             _records.Clear();
             _dbToRemoveIds.Clear();
             _dbToInserts.Clear();
         }
         try {
             using (LiteDatabase db = new LiteDatabase(ConnString)) {
                 db.DropCollection(nameof(LocalMessageData));
             }
         }
         catch (Exception e) {
             Logger.ErrorDebugLine(e);
         }
         VirtualRoot.RaiseEvent(new LocalMessageSetClearedEvent());
     });
     VirtualRoot.BuildEventPath <Per1MinuteEvent>("周期保存LocalMessage到数据库", LogEnum.DevConsole, this.GetType(), PathPriority.Normal, path: message => {
         SaveToDb();
     });
     VirtualRoot.BuildEventPath <AppExitEvent>("程序退出时保存LocalMessage到数据库", LogEnum.DevConsole, this.GetType(), PathPriority.Normal, path: message => {
         SaveToDb();
     });
 }
예제 #11
0
 public MineWorkSet()
 {
     VirtualRoot.BuildEventPath <MinerStudioServiceSwitchedEvent>("切换了群口后台服务类型后刷新内存", LogEnum.DevConsole, path: message => {
         _dicById.Clear();
         base.Refresh();
         // 初始化以触发MineWorkSetInitedEvent事件
         InitOnece();
     }, this.GetType());
     VirtualRoot.BuildCmdPath <AddMineWorkCommand>(path: message => {
         InitOnece();
         if (!_dicById.ContainsKey(message.Input.Id))
         {
             var repository = VirtualRoot.CreateLocalRepository <MineWorkData>();
             var data       = new MineWorkData().Update(message.Input);
             data.CreatedOn = DateTime.Now;
             _dicById.Add(data.Id, data);
             repository.Add(data);
             VirtualRoot.RaiseEvent(new MineWorkAddedEvent(message.MessageId, data));
         }
     }, this.GetType());
     VirtualRoot.BuildCmdPath <UpdateMineWorkCommand>(path: message => {
         InitOnece();
         if (_dicById.TryGetValue(message.Input.Id, out MineWorkData data))
         {
             var repository = VirtualRoot.CreateLocalRepository <MineWorkData>();
             data.Update(message.Input);
             data.ModifiedOn = DateTime.Now;
             repository.Update(data);
             VirtualRoot.RaiseEvent(new MineWorkUpdatedEvent(message.MessageId, data));
         }
     }, this.GetType());
     VirtualRoot.BuildCmdPath <RemoveMineWorkCommand>(path: message => {
         InitOnece();
         if (_dicById.TryGetValue(message.EntityId, out MineWorkData entity))
         {
             _dicById.Remove(message.EntityId);
             var repository = VirtualRoot.CreateLocalRepository <MineWorkData>();
             repository.Remove(message.EntityId);
             MinerStudioPath.DeleteMineWorkFiles(message.EntityId);
             VirtualRoot.RaiseEvent(new MineWorkRemovedEvent(message.MessageId, entity));
         }
     }, this.GetType());
 }
예제 #12
0
 public UserSet(string dbFileFullName)
 {
     _dbFileFullName = dbFileFullName;
     VirtualRoot.BuildCmdPath <AddUserCommand>(action: message => {
         if (!_dicByLoginName.ContainsKey(message.User.LoginName))
         {
             UserData entity = new UserData(message.User);
             _dicByLoginName.Add(message.User.LoginName, entity);
             using (LiteDatabase db = new LiteDatabase(_dbFileFullName)) {
                 var col = db.GetCollection <UserData>();
                 col.Insert(entity);
             }
             VirtualRoot.RaiseEvent(new UserAddedEvent(message.Id, entity));
         }
     });
     VirtualRoot.BuildCmdPath <UpdateUserCommand>(action: message => {
         if (_dicByLoginName.ContainsKey(message.User.LoginName))
         {
             UserData entity = _dicByLoginName[message.User.LoginName];
             entity.Update(message.User);
             using (LiteDatabase db = new LiteDatabase(_dbFileFullName)) {
                 var col = db.GetCollection <UserData>();
                 col.Update(entity);
             }
             VirtualRoot.RaiseEvent(new UserUpdatedEvent(message.Id, entity));
         }
     });
     VirtualRoot.BuildCmdPath <RemoveUserCommand>(action: message => {
         if (_dicByLoginName.ContainsKey(message.LoginName))
         {
             UserData entity = _dicByLoginName[message.LoginName];
             _dicByLoginName.Remove(entity.LoginName);
             using (LiteDatabase db = new LiteDatabase(_dbFileFullName)) {
                 var col = db.GetCollection <UserData>();
                 col.Delete(message.LoginName);
             }
             VirtualRoot.RaiseEvent(new UserRemovedEvent(message.Id, entity));
         }
     });
 }
예제 #13
0
 public GpuProfileSet(INTMinerContext root)
 {
     VirtualRoot.BuildCmdPath <AddOrUpdateGpuProfileCommand>(path: message => {
         GpuProfileData data = _data.GpuProfiles.FirstOrDefault(a => a.CoinId == message.Input.CoinId && a.Index == message.Input.Index);
         if (data != null)
         {
             data.Update(message.Input);
             Save();
         }
         else
         {
             data = new GpuProfileData().Update(message.Input);
             _data.GpuProfiles.Add(data);
             Save();
         }
         VirtualRoot.RaiseEvent(new GpuProfileAddedOrUpdatedEvent(message.MessageId, data));
     }, location: this.GetType());
     VirtualRoot.BuildCmdPath <CoinOverClockCommand>(path: message => {
         Task.Factory.StartNew(() => {
             CoinOverClock(root, message.CoinId);
             VirtualRoot.RaiseEvent(new CoinOverClockDoneEvent(targetPathId: message.MessageId));
         });
     }, location: this.GetType());
 }
예제 #14
0
 public MineWorkSet(INTMinerRoot root)
 {
     _root = root;
     VirtualRoot.BuildCmdPath <AddMineWorkCommand>(action: (message) => {
         InitOnece();
         if (message == null || message.Input == null || message.Input.GetId() == Guid.Empty)
         {
             throw new ArgumentNullException();
         }
         if (_dicById.ContainsKey(message.Input.GetId()))
         {
             return;
         }
         MineWorkData entity = new MineWorkData().Update(message.Input);
         var response        = Server.ControlCenterService.AddOrUpdateMineWork(entity);
         if (response.IsSuccess())
         {
             _dicById.Add(entity.Id, entity);
             VirtualRoot.RaiseEvent(new MineWorkAddedEvent(entity));
         }
         else
         {
             Write.UserFail(response?.Description);
         }
     });
     VirtualRoot.BuildCmdPath <UpdateMineWorkCommand>(action: (message) => {
         InitOnece();
         if (message == null || message.Input == null || message.Input.GetId() == Guid.Empty)
         {
             throw new ArgumentNullException();
         }
         if (!_dicById.ContainsKey(message.Input.GetId()))
         {
             return;
         }
         MineWorkData entity   = _dicById[message.Input.GetId()];
         MineWorkData oldValue = new MineWorkData().Update(entity);
         entity.Update(message.Input);
         Server.ControlCenterService.AddOrUpdateMineWorkAsync(entity, (response, exception) => {
             if (!response.IsSuccess())
             {
                 entity.Update(oldValue);
                 VirtualRoot.RaiseEvent(new MineWorkUpdatedEvent(entity));
                 Write.UserFail(response.ReadMessage(exception));
             }
         });
         VirtualRoot.RaiseEvent(new MineWorkUpdatedEvent(entity));
     });
     VirtualRoot.BuildCmdPath <RemoveMineWorkCommand>(action: (message) => {
         InitOnece();
         if (message == null || message.EntityId == Guid.Empty)
         {
             throw new ArgumentNullException();
         }
         if (!_dicById.ContainsKey(message.EntityId))
         {
             return;
         }
         MineWorkData entity = _dicById[message.EntityId];
         Server.ControlCenterService.RemoveMineWorkAsync(entity.Id, (response, exception) => {
             if (response.IsSuccess())
             {
                 _dicById.Remove(entity.Id);
                 VirtualRoot.RaiseEvent(new MineWorkRemovedEvent(entity));
             }
             else
             {
                 Write.UserFail(response.ReadMessage(exception));
             }
         });
     });
 }
예제 #15
0
        public MainWindow()
        {
            if (WpfUtil.IsInDesignMode)
            {
                return;
            }
            if (!NTMinerConsole.IsEnabled)
            {
                NTMinerConsole.Enable();
            }
            this.Vm          = new MainWindowViewModel();
            this.DataContext = Vm;
            this.MinHeight   = 430;
            this.MinWidth    = 640;
            this.Width       = AppRoot.MainWindowWidth;
            this.Height      = AppRoot.MainWindowHeight;
#if DEBUG
            NTStopwatch.Start();
#endif
            ConsoleWindow.Instance.MouseDown += (sender, e) => {
                MoveConsoleWindow();
            };
            SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;
            this.Loaded += (sender, e) => {
                ConsoleTabItemTopBorder.Margin = new Thickness(0, ConsoleTabItem.ActualHeight - 1, 0, 0);
                MoveConsoleWindow();
                hwndSource = PresentationSource.FromVisual((Visual)sender) as HwndSource;
                hwndSource.AddHook(new HwndSourceHook(Win32Proc.WindowProc));
            };
            InitializeComponent();
            _leftDrawerGripWidth    = LeftDrawerGrip.Width;
            _btnOverClockBackground = BtnOverClock.Background;
            // 下面几行是为了看见设计视图
            this.ResizeCursors.Visibility = Visibility.Visible;
            this.HideLeftDrawerGrid();
            // 上面几行是为了看见设计视图

            DateTime lastGetServerMessageOn = DateTime.MinValue;
            // 切换了主界面上的Tab时
            this.MainTabControl.SelectionChanged += (sender, e) => {
                // 延迟创建,以加快主界面的启动
                #region
                var selectedItem = MainTabControl.SelectedItem;
                if (selectedItem == TabItemSpeedTable)
                {
                    if (SpeedTableContainer.Child == null)
                    {
                        SpeedTableContainer.Child = GetSpeedTable();
                    }
                }
                else if (selectedItem == TabItemMessage)
                {
                    if (MessagesContainer.Child == null)
                    {
                        MessagesContainer.Child = new Messages();
                    }
                }
                else if (selectedItem == TabItemToolbox)
                {
                    if (ToolboxContainer.Child == null)
                    {
                        ToolboxContainer.Child = new Toolbox();
                    }
                }
                else if (selectedItem == TabItemMinerProfileOption)
                {
                    if (MinerProfileOptionContainer.Child == null)
                    {
                        MinerProfileOptionContainer.Child = new MinerProfileOption();
                    }
                }
                RpcRoot.SetIsServerMessagesVisible(selectedItem == TabItemMessage);
                if (selectedItem == TabItemMessage)
                {
                    if (lastGetServerMessageOn.AddSeconds(10) < DateTime.Now)
                    {
                        lastGetServerMessageOn = DateTime.Now;
                        VirtualRoot.Execute(new LoadNewServerMessageCommand());
                    }
                }
                if (selectedItem == ConsoleTabItem)
                {
                    ConsoleTabItemTopBorder.Visibility = Visibility.Visible;
                }
                else
                {
                    ConsoleTabItemTopBorder.Visibility = Visibility.Collapsed;
                }
                #endregion
            };
            this.IsVisibleChanged += (sender, e) => {
                #region
                if (this.IsVisible)
                {
                    NTMinerContext.IsUiVisible = true;
                }
                else
                {
                    NTMinerContext.IsUiVisible = false;
                }
                MoveConsoleWindow();
                #endregion
            };
            this.StateChanged += (s, e) => {
                #region
                if (Vm.MinerProfile.IsShowInTaskbar)
                {
                    ShowInTaskbar = true;
                }
                else
                {
                    if (WindowState == WindowState.Minimized)
                    {
                        ShowInTaskbar = false;
                    }
                    else
                    {
                        ShowInTaskbar = true;
                    }
                }
                if (WindowState == WindowState.Maximized)
                {
                    ResizeCursors.Visibility = Visibility.Collapsed;
                }
                else
                {
                    ResizeCursors.Visibility = Visibility.Visible;
                }
                MoveConsoleWindow();
                #endregion
            };
            bool isLeftClosed = false;
            this.ConsoleRectangle.IsVisibleChanged += (sender, e) => {
                if (this.ConsoleRectangle.IsVisible)
                {
                    if (isLeftClosed != (LeftDrawerGrip.Width == _leftDrawerGripWidth))
                    {
                        ConsoleWindowFit();
                    }
                }
                else
                {
                    isLeftClosed = LeftDrawerGrip.Width == _leftDrawerGripWidth;
                }
            };
            this.ConsoleRectangle.SizeChanged += (s, e) => {
                MoveConsoleWindow();
            };
            if (this.Width < 860)
            {
                NTMinerConsole.UserWarn("左侧面板已折叠,可点击侧边的'开始挖矿'按钮展开。");
            }
            this.SizeChanged += (s, e) => {
                #region
                if (this.Width < 860)
                {
                    this.CloseLeftDrawer();
                    this.BtnAboutNTMiner.Visibility = Visibility.Collapsed;
                }
                else
                {
                    this.OpenLeftDrawer(isSizeChanged: true);
                    this.BtnAboutNTMiner.Visibility = Visibility.Visible;
                }
                if (!this.ConsoleRectangle.IsVisible)
                {
                    if (e.WidthChanged)
                    {
                        ConsoleWindow.Instance.Width = e.NewSize.Width;
                    }
                    if (e.HeightChanged)
                    {
                        ConsoleWindow.Instance.Height = e.NewSize.Height;
                    }
                }
                #endregion
            };
            NotiCenterWindow.Bind(this, ownerIsTopmost: true);
            this.LocationChanged += (sender, e) => {
                MoveConsoleWindow();
            };
            VirtualRoot.BuildCmdPath <TopmostCommand>(path: message => {
                UIThread.Execute(() => {
                    if (!this.Topmost)
                    {
                        this.Topmost = true;
                    }
                });
            }, this.GetType());
            VirtualRoot.BuildCmdPath <UnTopmostCommand>(path: message => {
                UIThread.Execute(() => {
                    if (this.Topmost)
                    {
                        this.Topmost = false;
                    }
                });
            }, this.GetType());
            VirtualRoot.BuildCmdPath <CloseMainWindowCommand>(path: message => {
                UIThread.Execute(() => {
                    if (message.IsAutoNoUi)
                    {
                        SwitchToNoUi();
                    }
                    else
                    {
                        this.Close();
                    }
                });
            }, location: this.GetType());
            this.BuildEventPath <Per1MinuteEvent>("挖矿中时自动切换为无界面模式", LogEnum.DevConsole,
                                                  path: message => {
                if (NTMinerContext.IsUiVisible && NTMinerContext.Instance.MinerProfile.IsAutoNoUi && NTMinerContext.Instance.IsMining)
                {
                    if (NTMinerContext.MainWindowRendedOn.AddMinutes(NTMinerContext.Instance.MinerProfile.AutoNoUiMinutes) < message.BornOn)
                    {
                        VirtualRoot.ThisLocalInfo(nameof(MainWindow), $"挖矿中界面展示{NTMinerContext.Instance.MinerProfile.AutoNoUiMinutes}分钟后自动切换为无界面模式,可在选项页调整配置");
                        VirtualRoot.Execute(new CloseMainWindowCommand(isAutoNoUi: true));
                    }
                }
            }, location: this.GetType());
#if DEBUG
            var elapsedMilliseconds = NTStopwatch.Stop();
            if (elapsedMilliseconds.ElapsedMilliseconds > NTStopwatch.ElapsedMilliseconds)
            {
                NTMinerConsole.DevTimeSpan($"耗时{elapsedMilliseconds} {this.GetType().Name}.ctor");
            }
#endif
        }
예제 #16
0
        public MinerProfileViewModel()
        {
            if (WpfUtil.IsInDesignMode)
            {
                return;
            }
            if (Instance != null)
            {
                throw new InvalidProgramException();
            }
            if (this.IsCreateShortcut)
            {
                CreateShortcut();
            }
            this.Up = new DelegateCommand <string>(propertyName => {
                WpfUtil.Up(this, propertyName);
            });
            this.Down = new DelegateCommand <string>(propertyName => {
                WpfUtil.Down(this, propertyName);
            });
            this.WsRetry = new DelegateCommand(() => {
                RpcRoot.Client.NTMinerDaemonService.StartOrStopWsAsync(isResetFailCount: true);
                IsConnecting = true;
            });
            string GetRowArgsAssembly()
            {
                string argsAssembly = this.ArgsAssembly ?? "无";

                if (argsAssembly.Contains("{logfile}"))
                {
                    argsAssembly = Regex.Replace(argsAssembly, "\\s\\S+\\s\"\\{logfile\\}\"", string.Empty);
                }
                return(argsAssembly.Trim());
            }

            this.CopyArgsAssembly = new DelegateCommand(() => {
                string argsAssembly = GetRowArgsAssembly();
                Clipboard.SetDataObject(argsAssembly, true);
                VirtualRoot.Out.ShowSuccess("命令行", header: "复制成功");
            });
            if (ClientAppType.IsMinerClient)
            {
                if (this.IsSystemName)
                {
                    this.MinerName = NTKeyword.GetSafeMinerName(NTMinerContext.ThisPcName);
                }
                VirtualRoot.BuildCmdPath <SetAutoStartCommand>(this.GetType(), LogEnum.None, message => {
                    this.IsAutoStart = message.IsAutoStart;
                    this.IsAutoBoot  = message.IsAutoBoot;
                });
                VirtualRoot.BuildEventPath <StartingMineFailedEvent>("开始挖矿失败", LogEnum.DevConsole, location: this.GetType(), PathPriority.Normal,
                                                                     path: message => {
                    IsMining = false;
                    NTMinerConsole.UserError(message.Message);
                });
                // 群控客户端已经有一个执行RefreshWsStateCommand命令的路径了
                VirtualRoot.BuildCmdPath <RefreshWsStateCommand>(this.GetType(), LogEnum.DevConsole, message => {
                    #region
                    if (message.WsClientState != null)
                    {
                        this.WsServerIp = message.WsClientState.WsServerIp;
                        this.IsWsOnline = message.WsClientState.Status == WsClientStatus.Open;
                        if (message.WsClientState.ToOut)
                        {
                            VirtualRoot.Out.ShowWarn(message.WsClientState.Description, autoHideSeconds: 3);
                        }
                        if (!message.WsClientState.ToOut || !this.IsWsOnline)
                        {
                            this.WsDescription = message.WsClientState.Description;
                        }
                        if (!this.IsWsOnline)
                        {
                            if (message.WsClientState.LastTryOn != DateTime.MinValue)
                            {
                                this.WsLastTryOn = message.WsClientState.LastTryOn;
                            }
                            if (message.WsClientState.NextTrySecondsDelay > 0)
                            {
                                WsNextTrySecondsDelay = message.WsClientState.NextTrySecondsDelay;
                            }
                        }
                    }
                    #endregion
                });
                VirtualRoot.BuildEventPath <Per1SecondEvent>("外网群控重试秒表倒计时", LogEnum.None, this.GetType(), PathPriority.Normal, path: message => {
                    if (IsOuterUserEnabled && !IsWsOnline)
                    {
                        if (WsNextTrySecondsDelay > 0)
                        {
                            WsNextTrySecondsDelay--;
                        }
                        else if (WsLastTryOn == DateTime.MinValue)
                        {
                            this.RefreshWsDaemonState();
                        }
                        OnPropertyChanged(nameof(WsLastTryOnText));
                    }
                });
                VirtualRoot.BuildEventPath <WsServerOkEvent>("服务器Ws服务已可用", LogEnum.DevConsole, this.GetType(), PathPriority.Normal, path: message => {
                    if (IsOuterUserEnabled && !IsWsOnline)
                    {
                        StartOrStopWs();
                    }
                });
            }
            NTMinerContext.SetRefreshArgsAssembly((reason) => {
                NTMinerConsole.DevDebug(() => $"RefreshArgsAssembly" + reason, ConsoleColor.Cyan);
                #region 确保双挖权重在合法的范围内
                if (CoinVm != null && CoinVm.CoinKernel != null && CoinVm.CoinKernel.Kernel != null)
                {
                    var coinKernelProfile = CoinVm.CoinKernel.CoinKernelProfile;
                    var kernelInput       = CoinVm.CoinKernel.Kernel.KernelInputVm;
                    if (coinKernelProfile != null && kernelInput != null)
                    {
                        if (coinKernelProfile.IsDualCoinEnabled && !kernelInput.IsAutoDualWeight)
                        {
                            if (coinKernelProfile.DualCoinWeight > kernelInput.DualWeightMax)
                            {
                                coinKernelProfile.DualCoinWeight = kernelInput.DualWeightMax;
                            }
                            else if (coinKernelProfile.DualCoinWeight < kernelInput.DualWeightMin)
                            {
                                coinKernelProfile.DualCoinWeight = kernelInput.DualWeightMin;
                            }
                            NTMinerContext.Instance.MinerProfile.SetCoinKernelProfileProperty(coinKernelProfile.CoinKernelId, nameof(coinKernelProfile.DualCoinWeight), coinKernelProfile.DualCoinWeight);
                        }
                    }
                }
                #endregion
                NTMinerContext.Instance.CurrentMineContext = MineContextFactory.CreateMineContext();
                if (NTMinerContext.Instance.CurrentMineContext != null)
                {
                    this.ArgsAssembly = NTMinerContext.Instance.CurrentMineContext.CommandLine;
                }
                else
                {
                    this.ArgsAssembly = string.Empty;
                }
            });
            AppRoot.BuildEventPath <AutoBootStartRefreshedEvent>("刷新开机启动和自动挖矿的展示", LogEnum.DevConsole, location: this.GetType(), PathPriority.Normal,
                                                                 path: message => {
                this.OnPropertyChanged(nameof(IsAutoBoot));
                this.OnPropertyChanged(nameof(IsAutoStart));
            });
            AppRoot.BuildEventPath <MinerProfilePropertyChangedEvent>("MinerProfile设置变更后刷新VM内存", LogEnum.DevConsole, location: this.GetType(), PathPriority.Normal,
                                                                      path: message => {
                OnPropertyChanged(message.PropertyName);
            });

            VirtualRoot.BuildEventPath <LocalContextReInitedEventHandledEvent>("本地上下文视图模型集刷新后刷新界面", LogEnum.DevConsole, location: this.GetType(), PathPriority.Normal,
                                                                               path: message => {
                AllPropertyChanged();
                if (CoinVm != null)
                {
                    CoinVm.OnPropertyChanged(nameof(CoinVm.Wallets));
                    CoinVm.CoinKernel?.CoinKernelProfile.SelectedDualCoin?.OnPropertyChanged(nameof(CoinVm.Wallets));
                    CoinVm.CoinProfile?.OnPropertyChanged(nameof(CoinVm.CoinProfile.SelectedWallet));
                    CoinVm.CoinKernel?.CoinKernelProfile.SelectedDualCoin?.CoinProfile?.OnPropertyChanged(nameof(CoinVm.CoinProfile.SelectedDualCoinWallet));
                }
            });
            VirtualRoot.BuildEventPath <CoinAddedEvent>("Vm集添加了新币种后刷新MinerProfileVm内存", LogEnum.DevConsole, this.GetType(), PathPriority.BelowNormal, path: message => {
                OnPropertyChanged(nameof(CoinVm));
            });
            VirtualRoot.BuildEventPath <CoinRemovedEvent>("Vm集删除了新币种后刷新MinerProfileVm内存", LogEnum.DevConsole, this.GetType(), PathPriority.BelowNormal, path: message => {
                OnPropertyChanged(nameof(CoinVm));
            });
        }
예제 #17
0
 public NTMinerWalletSet()
 {
     VirtualRoot.BuildCmdPath <AddNTMinerWalletCommand>(location: this.GetType(), LogEnum.DevConsole, path: (message) => {
         if (message == null || message.Input == null || message.Input.GetId() == Guid.Empty)
         {
             throw new ArgumentNullException();
         }
         if (string.IsNullOrEmpty(message.Input.Wallet))
         {
             throw new ValidationException("NTMinerWallet Wallet can't be null or empty");
         }
         if (_dicById.ContainsKey(message.Input.GetId()))
         {
             return;
         }
         NTMinerWalletData entity = new NTMinerWalletData().Update(message.Input);
         RpcRoot.OfficialServer.NTMinerWalletService.AddOrUpdateNTMinerWalletAsync(entity, (response, e) => {
             if (response.IsSuccess())
             {
                 _dicById.Add(entity.Id, entity);
                 VirtualRoot.RaiseEvent(new NTMinerWalletAddedEvent(message.MessageId, entity));
             }
             else
             {
                 VirtualRoot.Out.ShowError(response.ReadMessage(e), autoHideSeconds: 4);
             }
         });
     });
     VirtualRoot.BuildCmdPath <UpdateNTMinerWalletCommand>(location: this.GetType(), LogEnum.DevConsole, path: (message) => {
         if (message == null || message.Input == null || message.Input.GetId() == Guid.Empty)
         {
             throw new ArgumentNullException();
         }
         if (string.IsNullOrEmpty(message.Input.Wallet))
         {
             throw new ValidationException("minerGroup Wallet can't be null or empty");
         }
         if (!_dicById.TryGetValue(message.Input.GetId(), out NTMinerWalletData entity))
         {
             return;
         }
         NTMinerWalletData oldValue = new NTMinerWalletData().Update(entity);
         entity.Update(message.Input);
         RpcRoot.OfficialServer.NTMinerWalletService.AddOrUpdateNTMinerWalletAsync(entity, (response, e) => {
             if (!response.IsSuccess())
             {
                 entity.Update(oldValue);
                 VirtualRoot.RaiseEvent(new NTMinerWalletUpdatedEvent(message.MessageId, entity));
                 VirtualRoot.Out.ShowError(response.ReadMessage(e), autoHideSeconds: 4);
             }
         });
         VirtualRoot.RaiseEvent(new NTMinerWalletUpdatedEvent(message.MessageId, entity));
     });
     VirtualRoot.BuildCmdPath <RemoveNTMinerWalletCommand>(location: this.GetType(), LogEnum.DevConsole, path: (message) => {
         if (message == null || message.EntityId == Guid.Empty)
         {
             throw new ArgumentNullException();
         }
         if (!_dicById.ContainsKey(message.EntityId))
         {
             return;
         }
         NTMinerWalletData entity = _dicById[message.EntityId];
         RpcRoot.OfficialServer.NTMinerWalletService.RemoveNTMinerWalletAsync(entity.Id, (response, e) => {
             if (response.IsSuccess())
             {
                 _dicById.Remove(entity.Id);
                 VirtualRoot.RaiseEvent(new NTMinerWalletRemovedEvent(message.MessageId, entity));
             }
             else
             {
                 VirtualRoot.Out.ShowError(response.ReadMessage(e), autoHideSeconds: 4);
             }
         });
     });
 }
예제 #18
0
        public WalletSet(INTMinerContext root)
        {
            _root = root;
            VirtualRoot.BuildCmdPath <AddWalletCommand>(path: message => {
                InitOnece();
                if (message == null || message.Input == null || message.Input.GetId() == Guid.Empty)
                {
                    throw new ArgumentNullException();
                }
                if (!root.ServerContext.CoinSet.Contains(message.Input.CoinId))
                {
                    throw new ValidationException("there is not coin with id " + message.Input.CoinId);
                }
                if (string.IsNullOrEmpty(message.Input.Address))
                {
                    throw new ValidationException("wallet code and Address can't be null or empty");
                }
                if (_dicById.ContainsKey(message.Input.GetId()))
                {
                    return;
                }
                WalletData entity = new WalletData().Update(message.Input);
                _dicById.Add(entity.Id, entity);
                var repository = root.ServerContext.CreateLocalRepository <WalletData>();
                repository.Add(entity);

                VirtualRoot.RaiseEvent(new WalletAddedEvent(message.MessageId, entity));
            }, location: this.GetType());
            VirtualRoot.BuildCmdPath <UpdateWalletCommand>(path: message => {
                InitOnece();
                if (message == null || message.Input == null || message.Input.GetId() == Guid.Empty)
                {
                    throw new ArgumentNullException();
                }
                if (!root.ServerContext.CoinSet.Contains(message.Input.CoinId))
                {
                    throw new ValidationException("there is not coin with id " + message.Input.CoinId);
                }
                if (string.IsNullOrEmpty(message.Input.Address))
                {
                    throw new ValidationException("wallet Address can't be null or empty");
                }
                if (string.IsNullOrEmpty(message.Input.Name))
                {
                    throw new ValidationException("wallet name can't be null or empty");
                }
                if (!_dicById.TryGetValue(message.Input.GetId(), out WalletData entity))
                {
                    return;
                }
                entity.Update(message.Input);
                var repository = root.ServerContext.CreateLocalRepository <WalletData>();
                repository.Update(entity);

                VirtualRoot.RaiseEvent(new WalletUpdatedEvent(message.MessageId, entity));
            }, location: this.GetType());
            VirtualRoot.BuildCmdPath <RemoveWalletCommand>(path: (message) => {
                InitOnece();
                if (message == null || message.EntityId == Guid.Empty)
                {
                    throw new ArgumentNullException();
                }
                if (!_dicById.ContainsKey(message.EntityId))
                {
                    return;
                }
                WalletData entity = _dicById[message.EntityId];
                _dicById.Remove(entity.Id);
                var repository = root.ServerContext.CreateLocalRepository <WalletData>();
                repository.Remove(entity.Id);

                VirtualRoot.RaiseEvent(new WalletRemovedEvent(message.MessageId, entity));
            }, location: this.GetType());
        }
예제 #19
0
 public NTMinerWalletSet()
 {
     VirtualRoot.BuildCmdPath <AddNTMinerWalletCommand>(action: (message) => {
         if (message == null || message.Input == null || message.Input.GetId() == Guid.Empty)
         {
             throw new ArgumentNullException();
         }
         if (string.IsNullOrEmpty(message.Input.Wallet))
         {
             throw new ValidationException("NTMinerWallet Wallet can't be null or empty");
         }
         if (_dicById.ContainsKey(message.Input.GetId()))
         {
             return;
         }
         NTMinerWalletData entity = new NTMinerWalletData().Update(message.Input);
         OfficialServer.NTMinerWalletService.AddOrUpdateNTMinerWalletAsync(entity, (response, e) => {
             if (response.IsSuccess())
             {
                 _dicById.Add(entity.Id, entity);
                 VirtualRoot.RaiseEvent(new NTMinerWalletAddedEvent(entity));
             }
             else
             {
                 Write.UserFail(response.ReadMessage(e));
             }
         });
     });
     VirtualRoot.BuildCmdPath <UpdateNTMinerWalletCommand>(action: (message) => {
         if (message == null || message.Input == null || message.Input.GetId() == Guid.Empty)
         {
             throw new ArgumentNullException();
         }
         if (string.IsNullOrEmpty(message.Input.Wallet))
         {
             throw new ValidationException("minerGroup Wallet can't be null or empty");
         }
         if (!_dicById.ContainsKey(message.Input.GetId()))
         {
             return;
         }
         NTMinerWalletData entity   = _dicById[message.Input.GetId()];
         NTMinerWalletData oldValue = new NTMinerWalletData().Update(entity);
         entity.Update(message.Input);
         OfficialServer.NTMinerWalletService.AddOrUpdateNTMinerWalletAsync(entity, (response, e) => {
             if (!response.IsSuccess())
             {
                 entity.Update(oldValue);
                 VirtualRoot.RaiseEvent(new NTMinerWalletUpdatedEvent(entity));
                 Write.UserFail(response.ReadMessage(e));
             }
         });
         VirtualRoot.RaiseEvent(new NTMinerWalletUpdatedEvent(entity));
     });
     VirtualRoot.BuildCmdPath <RemoveNTMinerWalletCommand>(action: (message) => {
         if (message == null || message.EntityId == Guid.Empty)
         {
             throw new ArgumentNullException();
         }
         if (!_dicById.ContainsKey(message.EntityId))
         {
             return;
         }
         NTMinerWalletData entity = _dicById[message.EntityId];
         OfficialServer.NTMinerWalletService.RemoveNTMinerWalletAsync(entity.Id, (response, e) => {
             if (response.IsSuccess())
             {
                 _dicById.Remove(entity.Id);
                 VirtualRoot.RaiseEvent(new NTMinerWalletRemovedEvent(entity));
             }
             else
             {
                 Write.UserFail(response.ReadMessage(e));
             }
         });
     });
 }
예제 #20
0
        public WalletSet(INTMinerRoot root)
        {
            _root = root;
            VirtualRoot.BuildCmdPath <AddWalletCommand>(action: message => {
                InitOnece();
                if (message == null || message.Input == null || message.Input.GetId() == Guid.Empty)
                {
                    throw new ArgumentNullException();
                }
                if (!_root.CoinSet.Contains(message.Input.CoinId))
                {
                    throw new ValidationException("there is not coin with id " + message.Input.CoinId);
                }
                if (string.IsNullOrEmpty(message.Input.Address))
                {
                    throw new ValidationException("wallet code and Address can't be null or empty");
                }
                if (_dicById.ContainsKey(message.Input.GetId()))
                {
                    return;
                }
                WalletData entity = new WalletData().Update(message.Input);
                _dicById.Add(entity.Id, entity);
                AddWallet(entity);

                VirtualRoot.RaiseEvent(new WalletAddedEvent(entity));
            });
            VirtualRoot.BuildCmdPath <UpdateWalletCommand>(action: message => {
                InitOnece();
                if (message == null || message.Input == null || message.Input.GetId() == Guid.Empty)
                {
                    throw new ArgumentNullException();
                }
                if (!_root.CoinSet.Contains(message.Input.CoinId))
                {
                    throw new ValidationException("there is not coin with id " + message.Input.CoinId);
                }
                if (string.IsNullOrEmpty(message.Input.Address))
                {
                    throw new ValidationException("wallet Address can't be null or empty");
                }
                if (string.IsNullOrEmpty(message.Input.Name))
                {
                    throw new ValidationException("wallet name can't be null or empty");
                }
                if (!_dicById.ContainsKey(message.Input.GetId()))
                {
                    return;
                }
                WalletData entity = _dicById[message.Input.GetId()];
                entity.Update(message.Input);
                UpdateWallet(entity);

                VirtualRoot.RaiseEvent(new WalletUpdatedEvent(entity));
            });
            VirtualRoot.BuildCmdPath <RemoveWalletCommand>(action: (message) => {
                InitOnece();
                if (message == null || message.EntityId == Guid.Empty)
                {
                    throw new ArgumentNullException();
                }
                if (!_dicById.ContainsKey(message.EntityId))
                {
                    return;
                }
                WalletData entity = _dicById[message.EntityId];
                _dicById.Remove(entity.GetId());
                RemoveWallet(entity.Id);

                VirtualRoot.RaiseEvent(new WalletRemovedEvent(entity));
            });
        }
예제 #21
0
파일: UserSet.cs 프로젝트: wind959/ntminer
 public UserSet()
 {
     VirtualRoot.BuildCmdPath <AddUserCommand>(action: message => {
         if (!_dicByLoginName.ContainsKey(message.User.LoginName))
         {
             Server.UserService.AddUserAsync(new UserData {
                 LoginName   = message.User.LoginName,
                 Password    = message.User.Password,
                 IsEnabled   = message.User.IsEnabled,
                 Description = message.User.Description
             }, (response, exception) => {
                 if (response.IsSuccess())
                 {
                     UserData entity = new UserData(message.User);
                     _dicByLoginName.Add(message.User.LoginName, entity);
                     VirtualRoot.RaiseEvent(new UserAddedEvent(entity));
                 }
                 else
                 {
                     Write.UserFail(response.ReadMessage(exception));
                 }
             });
         }
     });
     VirtualRoot.BuildCmdPath <UpdateUserCommand>(action: message => {
         if (_dicByLoginName.ContainsKey(message.User.LoginName))
         {
             UserData entity   = _dicByLoginName[message.User.LoginName];
             UserData oldValue = new UserData(entity);
             entity.Update(message.User);
             Server.UserService.UpdateUserAsync(new UserData {
                 LoginName   = message.User.LoginName,
                 Password    = message.User.Password,
                 IsEnabled   = message.User.IsEnabled,
                 Description = message.User.Description
             }, (response, exception) => {
                 if (!response.IsSuccess())
                 {
                     entity.Update(oldValue);
                     VirtualRoot.RaiseEvent(new UserUpdatedEvent(entity));
                     Write.UserFail(response.ReadMessage(exception));
                 }
             });
             VirtualRoot.RaiseEvent(new UserUpdatedEvent(entity));
         }
     });
     VirtualRoot.BuildCmdPath <RemoveUserCommand>(action: message => {
         if (_dicByLoginName.ContainsKey(message.LoginName))
         {
             UserData entity = _dicByLoginName[message.LoginName];
             Server.UserService.RemoveUserAsync(message.LoginName, (response, exception) => {
                 if (response.IsSuccess())
                 {
                     _dicByLoginName.Remove(entity.LoginName);
                     VirtualRoot.RaiseEvent(new UserRemovedEvent(entity));
                 }
                 else
                 {
                     Write.UserFail(response.ReadMessage(exception));
                 }
             });
         }
     });
 }
예제 #22
0
 public OverClockDataSet(INTMinerContext root)
 {
     _root = root;
     VirtualRoot.BuildCmdPath <AddOverClockDataCommand>(path: (message) => {
         if (message == null || message.Input == null || message.Input.GetId() == Guid.Empty)
         {
             throw new ArgumentNullException();
         }
         if (string.IsNullOrEmpty(message.Input.Name))
         {
             throw new ValidationException("OverClockData name can't be null or empty");
         }
         if (_dicById.ContainsKey(message.Input.GetId()))
         {
             return;
         }
         OverClockData entity = new OverClockData().Update(message.Input);
         RpcRoot.OfficialServer.OverClockDataService.AddOrUpdateOverClockDataAsync(entity, (response, e) => {
             if (response.IsSuccess())
             {
                 _dicById.Add(entity.Id, entity);
                 VirtualRoot.RaiseEvent(new OverClockDataAddedEvent(message.MessageId, entity));
             }
             else
             {
                 VirtualRoot.Out.ShowError(response.ReadMessage(e), autoHideSeconds: 4);
             }
         });
     }, location: this.GetType());
     VirtualRoot.BuildCmdPath <UpdateOverClockDataCommand>(path: (message) => {
         if (message == null || message.Input == null || message.Input.GetId() == Guid.Empty)
         {
             throw new ArgumentNullException();
         }
         if (string.IsNullOrEmpty(message.Input.Name))
         {
             throw new ValidationException("minerGroup name can't be null or empty");
         }
         if (!_dicById.TryGetValue(message.Input.GetId(), out OverClockData entity))
         {
             return;
         }
         OverClockData oldValue = new OverClockData().Update(entity);
         entity.Update(message.Input);
         RpcRoot.OfficialServer.OverClockDataService.AddOrUpdateOverClockDataAsync(entity, (response, e) => {
             if (!response.IsSuccess())
             {
                 entity.Update(oldValue);
                 VirtualRoot.RaiseEvent(new OverClockDataUpdatedEvent(message.MessageId, entity));
                 VirtualRoot.Out.ShowError(response.ReadMessage(e), autoHideSeconds: 4);
             }
         });
         VirtualRoot.RaiseEvent(new OverClockDataUpdatedEvent(message.MessageId, entity));
     }, location: this.GetType());
     VirtualRoot.BuildCmdPath <RemoveOverClockDataCommand>(path: (message) => {
         if (message == null || message.EntityId == Guid.Empty)
         {
             throw new ArgumentNullException();
         }
         if (!_dicById.ContainsKey(message.EntityId))
         {
             return;
         }
         OverClockData entity = _dicById[message.EntityId];
         RpcRoot.OfficialServer.OverClockDataService.RemoveOverClockDataAsync(entity.Id, (response, e) => {
             if (response.IsSuccess())
             {
                 _dicById.Remove(entity.Id);
                 VirtualRoot.RaiseEvent(new OverClockDataRemovedEvent(message.MessageId, entity));
             }
             else
             {
                 VirtualRoot.Out.ShowError(response.ReadMessage(e), autoHideSeconds: 4);
             }
         });
     }, location: this.GetType());
 }
예제 #23
0
 public MinerGroupSet(INTMinerRoot root)
 {
     _root = root;
     VirtualRoot.BuildCmdPath <AddMinerGroupCommand>(action: (message) => {
         InitOnece();
         if (message == null || message.Input == null || message.Input.GetId() == Guid.Empty)
         {
             throw new ArgumentNullException();
         }
         if (string.IsNullOrEmpty(message.Input.Name))
         {
             throw new ValidationException("minerGroup name can't be null or empty");
         }
         if (_dicById.ContainsKey(message.Input.GetId()))
         {
             return;
         }
         MinerGroupData entity = new MinerGroupData().Update(message.Input);
         Server.ControlCenterService.AddOrUpdateMinerGroupAsync(entity, (response, exception) => {
             if (response.IsSuccess())
             {
                 _dicById.Add(entity.Id, entity);
                 VirtualRoot.RaiseEvent(new MinerGroupAddedEvent(entity));
             }
             else
             {
                 Write.UserFail(response.ReadMessage(exception));
             }
         });
     });
     VirtualRoot.BuildCmdPath <UpdateMinerGroupCommand>(action: (message) => {
         InitOnece();
         if (message == null || message.Input == null || message.Input.GetId() == Guid.Empty)
         {
             throw new ArgumentNullException();
         }
         if (string.IsNullOrEmpty(message.Input.Name))
         {
             throw new ValidationException("minerGroup name can't be null or empty");
         }
         if (!_dicById.ContainsKey(message.Input.GetId()))
         {
             return;
         }
         MinerGroupData entity   = _dicById[message.Input.GetId()];
         MinerGroupData oldValue = new MinerGroupData().Update(entity);
         entity.Update(message.Input);
         Server.ControlCenterService.AddOrUpdateMinerGroupAsync(entity, (response, exception) => {
             if (!response.IsSuccess())
             {
                 entity.Update(oldValue);
                 VirtualRoot.RaiseEvent(new MinerGroupUpdatedEvent(entity));
                 Write.UserFail(response.ReadMessage(exception));
             }
         });
         VirtualRoot.RaiseEvent(new MinerGroupUpdatedEvent(entity));
     });
     VirtualRoot.BuildCmdPath <RemoveMinerGroupCommand>(action: (message) => {
         InitOnece();
         if (message == null || message.EntityId == Guid.Empty)
         {
             throw new ArgumentNullException();
         }
         if (!_dicById.ContainsKey(message.EntityId))
         {
             return;
         }
         MinerGroupData entity = _dicById[message.EntityId];
         Server.ControlCenterService.RemoveMinerGroupAsync(entity.Id, (response, exception) => {
             if (response.IsSuccess())
             {
                 _dicById.Remove(entity.Id);
                 VirtualRoot.RaiseEvent(new MinerGroupRemovedEvent(entity));
             }
             else
             {
                 Write.UserFail(response.ReadMessage(exception));
             }
         });
     });
 }
예제 #24
0
        public ClientDataSet(
            IMinerDataRedis minerRedis, IClientActiveOnRedis clientActiveOnRedis,
            ISpeedDataRedis speedDataRedis, IMinerClientMqSender mqSender)
            : base(isPull: false, getDatas: callback => {
            var getMinersTask          = minerRedis.GetAllAsync();
            var getClientActiveOnsTask = clientActiveOnRedis.GetAllAsync();
            var getSpeedsTask          = speedDataRedis.GetAllAsync();
            Task.WhenAll(getMinersTask, getClientActiveOnsTask, getSpeedsTask).ContinueWith(t => {
                NTMinerConsole.UserInfo($"从redis加载了 {getMinersTask.Result.Count} 条MinerData,和 {getSpeedsTask.Result.Count} 条SpeedData");
                Dictionary <Guid, SpeedData> speedDataDic       = getSpeedsTask.Result;
                Dictionary <string, DateTime> clientActiveOnDic = getClientActiveOnsTask.Result;
                List <ClientData> clientDatas = new List <ClientData>();
                DateTime speedOn = DateTime.Now.AddMinutes(-3);
                foreach (var minerData in getMinersTask.Result)
                {
                    var clientData = ClientData.Create(minerData);
                    if (clientActiveOnDic.TryGetValue(minerData.Id, out DateTime activeOn))
                    {
                        clientData.MinerActiveOn = activeOn;
                    }
                    clientDatas.Add(clientData);
                    if (speedDataDic.TryGetValue(minerData.ClientId, out SpeedData speedData) && speedData.SpeedOn > speedOn)
                    {
                        clientData.Update(speedData, out bool _);
                    }
                }
                callback?.Invoke(clientDatas);
            });
        }) {
            _minerRedis          = minerRedis;
            _clientActiveOnRedis = clientActiveOnRedis;
            _speedDataRedis      = speedDataRedis;
            _mqSender            = mqSender;
            VirtualRoot.BuildEventPath <Per100MinuteEvent>("周期将矿机的MinerActiveOn或NetActiveOn时间戳持久到redis", LogEnum.DevConsole, message => {
                var minerCients = _dicByObjectId.Values.ToArray();
                DateTime time   = message.BornOn.AddSeconds(-message.Seconds);
                int count       = 0;
                foreach (var minerClient in minerCients)
                {
                    // 如果活跃则更新到redis,否则就不更新了
                    DateTime activeOn = minerClient.GetActiveOn();
                    if (activeOn > time)
                    {
                        clientActiveOnRedis.SetAsync(minerClient.Id, activeOn);
                        count++;
                    }
                }
                NTMinerConsole.DevWarn($"{count.ToString()} 条活跃矿机的时间戳被持久化");
            }, this.GetType());
            // 上面的持久化时间戳到redis的目的主要是为了下面那个周期找出不活跃的矿机记录删除掉的逻辑能够在重启WebApiServer服务进程后不中断
            VirtualRoot.BuildEventPath <Per2MinuteEvent>("周期找出用不活跃的矿机记录删除掉", LogEnum.DevConsole, message => {
                var clientDatas = _dicByObjectId.Values.ToArray();
                Dictionary <string, List <ClientData> > dicByMACAddress = new Dictionary <string, List <ClientData> >();
                DateTime minerClientExpireTime = message.BornOn.AddDays(-7);
                // 因为SpeedData尺寸较大,时效性较短,可以比CientData更早删除
                DateTime minerSpeedExpireTime = message.BornOn.AddMinutes(-3);
                int count = 0;
                foreach (var clientData in clientDatas)
                {
                    DateTime activeOn = clientData.GetActiveOn();
                    // 如果7天都没有活跃了
                    if (activeOn <= minerClientExpireTime)
                    {
                        RemoveByObjectId(clientData.Id);
                        count++;
                    }
                    else if (activeOn <= minerSpeedExpireTime)
                    {
                        _speedDataRedis.DeleteByClientIdAsync(clientData.ClientId);
                    }
                    else if (!string.IsNullOrEmpty(clientData.MACAddress))
                    {
                        if (!dicByMACAddress.TryGetValue(clientData.MACAddress, out List <ClientData> list))
                        {
                            list = new List <ClientData>();
                            dicByMACAddress.Add(clientData.MACAddress, list);
                        }
                        list.Add(clientData);
                    }
                }
                if (count > 0)
                {
                    NTMinerConsole.DevWarn($"{count.ToString()} 条不活跃的矿机记录被删除");
                }
                List <string> toRemoveIds = new List <string>();
                foreach (var kv in dicByMACAddress)
                {
                    if (kv.Value.Count > 1)
                    {
                        toRemoveIds.AddRange(kv.Value.Select(a => a.Id));
                    }
                }
                if (toRemoveIds.Count > 0)
                {
                    count = 0;
                    foreach (var id in toRemoveIds)
                    {
                        RemoveByObjectId(id);
                        count++;
                    }
                    NTMinerConsole.DevWarn($"{count.ToString()} 条MAC地址重复的矿机记录被删除");
                }

                NTMinerConsole.DevDebug($"QueryClients平均耗时 {AverageQueryClientsMilliseconds.ToString()} 毫秒");
            }, this.GetType());
            // 收到Mq消息之前一定已经初始化完成,因为Mq消费者在ClientSetInitedEvent事件之后才会创建
            VirtualRoot.BuildEventPath <SpeedDatasMqEvent>("收到SpeedDatasMq消息后更新ClientData内存", LogEnum.None, path: message => {
                if (message.AppId == ServerRoot.HostConfig.ThisServerAddress)
                {
                    return;
                }
                if (message.ClientIdIps == null || message.ClientIdIps.Length == 0)
                {
                    return;
                }
                if (IsOldMqMessage(message.Timestamp))
                {
                    NTMinerConsole.UserOk(nameof(SpeedDatasMqEvent) + ":" + MqKeyword.SafeIgnoreMessage);
                    return;
                }
                speedDataRedis.GetByClientIdsAsync(message.ClientIdIps.Select(a => a.ClientId).ToArray()).ContinueWith(t => {
                    if (t.Result != null && t.Result.Length != 0)
                    {
                        foreach (var item in t.Result)
                        {
                            string minerIp = string.Empty;
                            var clientIdIp = message.ClientIdIps.FirstOrDefault(a => a.ClientId == item.ClientId);
                            if (clientIdIp != null)
                            {
                                minerIp = clientIdIp.MinerIp;
                            }
                            ReportSpeed(item.SpeedDto, minerIp, isFromWsServerNode: true);
                        }
                    }
                });
            }, this.GetType());
            VirtualRoot.BuildEventPath <MinerClientWsClosedMqEvent>("收到MinerClientWsClosedMq消息后更新NetActiveOn和IsOnline", LogEnum.None, path: message => {
                if (IsOldMqMessage(message.Timestamp))
                {
                    NTMinerConsole.UserOk(nameof(MinerClientWsClosedMqEvent) + ":" + MqKeyword.SafeIgnoreMessage);
                    return;
                }
                if (_dicByClientId.TryGetValue(message.ClientId, out ClientData clientData))
                {
                    clientData.NetActiveOn = message.Timestamp;
                    clientData.IsOnline    = false;
                }
            }, this.GetType());
            VirtualRoot.BuildEventPath <MinerClientsWsBreathedMqEvent>("收到MinerClientsWsBreathedMq消息后更新NetActiveOn", LogEnum.None, path: message => {
                if (IsOldMqMessage(message.Timestamp))
                {
                    NTMinerConsole.UserOk(nameof(MinerClientsWsBreathedMqEvent) + ":" + MqKeyword.SafeIgnoreMessage);
                    return;
                }
                if (message.ClientIds != null && message.ClientIds.Length != 0)
                {
                    foreach (var clientId in message.ClientIds)
                    {
                        if (_dicByClientId.TryGetValue(clientId, out ClientData clientData))
                        {
                            clientData.NetActiveOn = message.Timestamp;
                            clientData.IsOnline    = true;
                        }
                    }
                }
            }, this.GetType());
            VirtualRoot.BuildEventPath <MinerSignSetedMqEvent>("更新内存中的MinerData的MinerSign部分", LogEnum.None, path: message => {
                if (_dicByObjectId.TryGetValue(message.Data.Id, out ClientData clientData))
                {
                    clientData.Update(message.Data);
                }
                else
                {
                    clientData = ClientData.Create(message.Data);
                    Add(clientData);
                }
                clientData.NetActiveOn        = DateTime.Now;
                clientData.IsOnline           = true;
                clientData.IsOuterUserEnabled = true;
            }, this.GetType());
            VirtualRoot.BuildCmdPath <QueryClientsForWsMqCommand>(path: message => {
                QueryClientsResponse response = AppRoot.QueryClientsForWs(message.Query);
                _mqSender.SendResponseClientsForWs(message.AppId, message.LoginName, message.SessionId, message.MqMessageId, response);
            }, this.GetType(), LogEnum.None);
        }
예제 #25
0
 public ServerMessageSet(string dbFileFullName, bool isServer)
 {
     if (!string.IsNullOrEmpty(dbFileFullName))
     {
         _connectionString = $"filename={dbFileFullName};journal=false";
     }
     _isServer = isServer;
     if (!_isServer)
     {
         VirtualRoot.BuildCmdPath <LoadNewServerMessageCommand>(action: message => {
             DateTime localTimestamp = VirtualRoot.LocalServerMessageSetTimestamp;
             // 如果已知服务器端最新消息的时间戳不比本地已加载的最新消息新就不用加载了
             if (message.KnowServerMessageTimestamp <= Timestamp.GetTimestamp(localTimestamp))
             {
                 return;
             }
             OfficialServer.ServerMessageService.GetServerMessagesAsync(localTimestamp, (response, e) => {
                 if (response.IsSuccess() && response.Data.Count > 0)
                 {
                     LinkedList <ServerMessageData> data = new LinkedList <ServerMessageData>();
                     lock (_locker) {
                         DateTime maxTime = localTimestamp;
                         foreach (var item in response.Data.OrderBy(a => a.Timestamp))
                         {
                             if (item.Timestamp > maxTime)
                             {
                                 maxTime = item.Timestamp;
                             }
                             data.AddLast(item);
                             _linkedList.AddFirst(item);
                         }
                         if (maxTime != localTimestamp)
                         {
                             VirtualRoot.LocalServerMessageSetTimestamp = maxTime;
                         }
                     }
                     using (LiteDatabase db = new LiteDatabase(_connectionString)) {
                         var col = db.GetCollection <ServerMessageData>();
                         foreach (var item in data)
                         {
                             col.Insert(item);
                         }
                     }
                     VirtualRoot.RaiseEvent(new NewServerMessageLoadedEvent(data));
                 }
             });
         });
     }
     VirtualRoot.BuildCmdPath <AddOrUpdateServerMessageCommand>(action: message => {
         if (string.IsNullOrEmpty(_connectionString))
         {
             return;
         }
         InitOnece();
         if (_isServer)
         {
             #region Server
             ServerMessageData exist;
             List <ServerMessageData> toRemoves = new List <ServerMessageData>();
             ServerMessageData data             = null;
             lock (_locker) {
                 exist = _linkedList.FirstOrDefault(a => a.Id == message.Input.Id);
                 if (exist != null)
                 {
                     DateTime timestamp = exist.Timestamp;
                     exist.Update(message.Input);
                     // 如果更新前后时间戳没有变化则自动变更时间戳
                     if (timestamp == exist.Timestamp)
                     {
                         exist.Timestamp = DateTime.Now;
                     }
                 }
                 else
                 {
                     data = new ServerMessageData(message.Input);
                     _linkedList.AddFirst(data);
                     while (_linkedList.Count > NTKeyword.ServerMessageSetCapacity)
                     {
                         toRemoves.Add(_linkedList.Last.Value);
                         _linkedList.RemoveLast();
                     }
                 }
             }
             if (exist != null)
             {
                 using (LiteDatabase db = new LiteDatabase(_connectionString)) {
                     var col = db.GetCollection <ServerMessageData>();
                     col.Update(exist);
                 }
             }
             else
             {
                 using (LiteDatabase db = new LiteDatabase(_connectionString)) {
                     var col = db.GetCollection <ServerMessageData>();
                     if (toRemoves.Count != 0)
                     {
                         foreach (var item in toRemoves)
                         {
                             col.Delete(item.Id);
                         }
                     }
                     col.Insert(data);
                 }
             }
             #endregion
         }
         else
         {
             OfficialServer.ServerMessageService.AddOrUpdateServerMessageAsync(new ServerMessageData(message.Input), (response, ex) => {
                 if (response.IsSuccess())
                 {
                     VirtualRoot.Execute(new LoadNewServerMessageCommand());
                 }
             });
         }
     });
     VirtualRoot.BuildCmdPath <MarkDeleteServerMessageCommand>(action: message => {
         if (string.IsNullOrEmpty(_connectionString))
         {
             return;
         }
         InitOnece();
         if (_isServer)
         {
             #region Server
             ServerMessageData exist = null;
             lock (_locker) {
                 exist = _linkedList.FirstOrDefault(a => a.Id == message.EntityId);
                 if (exist != null)
                 {
                     exist.IsDeleted = true;
                     exist.Timestamp = DateTime.Now;
                 }
             }
             if (exist != null)
             {
                 using (LiteDatabase db = new LiteDatabase(_connectionString)) {
                     var col = db.GetCollection <ServerMessageData>();
                     col.Update(exist);
                 }
             }
             #endregion
         }
         else
         {
             OfficialServer.ServerMessageService.MarkDeleteServerMessageAsync(message.EntityId, (response, ex) => {
                 VirtualRoot.Execute(new LoadNewServerMessageCommand());
             });
         }
     });
     VirtualRoot.BuildCmdPath <ClearServerMessages>(action: message => {
         if (string.IsNullOrEmpty(_connectionString))
         {
             return;
         }
         InitOnece();
         // 服务端不应有清空消息的功能
         if (_isServer)
         {
             return;
         }
         using (LiteDatabase db = new LiteDatabase(_connectionString)) {
             lock (_locker) {
                 _linkedList.Clear();
             }
             db.DropCollection(nameof(ServerMessageData));
         }
         VirtualRoot.RaiseEvent(new ServerMessagesClearedEvent());
     });
 }
예제 #26
0
 public KernelOutputKeywordSet(string dbFileFullName, bool isServer)
 {
     if (string.IsNullOrEmpty(dbFileFullName))
     {
         throw new ArgumentNullException(nameof(dbFileFullName));
     }
     _connectionString = $"filename={dbFileFullName};journal=false";
     _isServer         = isServer;
     if (!isServer)
     {
         VirtualRoot.BuildCmdPath <LoadKernelOutputKeywordCommand>(action: message => {
             DateTime localTimestamp = VirtualRoot.LocalKernelOutputKeywordSetTimestamp;
             // 如果已知服务器端最新内核输出关键字时间戳不比本地已加载的最新内核输出关键字时间戳新就不用加载了
             if (message.KnowKernelOutputKeywordTimestamp <= Timestamp.GetTimestamp(localTimestamp))
             {
                 return;
             }
             OfficialServer.KernelOutputKeywordService.GetKernelOutputKeywords((response, e) => {
                 if (response.IsSuccess())
                 {
                     KernelOutputKeywordData[] toRemoves = _dicById.Where(a => a.Value.DataLevel == DataLevel.Global).Select(a => a.Value).ToArray();
                     foreach (var item in toRemoves)
                     {
                         _dicById.Remove(item.Id);
                         if (_dicByKernelOutputId.TryGetValue(item.KernelOutputId, out List <IKernelOutputKeyword> list))
                         {
                             list.Remove(item);
                         }
                     }
                     if (response.Data.Count != 0)
                     {
                         foreach (var item in response.Data)
                         {
                             item.SetDataLevel(DataLevel.Global);
                             _dicById.Add(item.Id, item);
                             if (!_dicByKernelOutputId.TryGetValue(item.KernelOutputId, out List <IKernelOutputKeyword> list))
                             {
                                 list = new List <IKernelOutputKeyword>();
                                 _dicByKernelOutputId.Add(item.KernelOutputId, list);
                             }
                             list.Add(item);
                         }
                         if (response.Timestamp != Timestamp.GetTimestamp(localTimestamp))
                         {
                             VirtualRoot.LocalKernelOutputKeywordSetTimestamp = Timestamp.FromTimestamp(response.Timestamp);
                         }
                         CacheServerKernelOutputKeywords(response.Data);
                         VirtualRoot.RaiseEvent(new KernelOutputKeywordLoadedEvent(response.Data));
                     }
                 }
             });
         });
     }
     VirtualRoot.BuildCmdPath <AddOrUpdateKernelOutputKeywordCommand>(action: (message) => {
         InitOnece();
         if (isServer || !DevMode.IsDevMode)
         {
             DataLevel dataLevel = isServer ? DataLevel.Global : DataLevel.Profile;
             if (_dicById.TryGetValue(message.Input.GetId(), out KernelOutputKeywordData exist))
             {
                 exist.Update(message.Input);
                 exist.SetDataLevel(dataLevel);
                 using (LiteDatabase db = new LiteDatabase(_connectionString)) {
                     var col = db.GetCollection <KernelOutputKeywordData>();
                     col.Update(exist);
                 }
                 if (!isServer)
                 {
                     VirtualRoot.RaiseEvent(new UserKernelOutputKeywordUpdatedEvent(message.Id, exist));
                 }
             }
             else
             {
                 KernelOutputKeywordData entity = new KernelOutputKeywordData().Update(message.Input);
                 entity.SetDataLevel(dataLevel);
                 _dicById.Add(entity.Id, entity);
                 if (!_dicByKernelOutputId.TryGetValue(entity.KernelOutputId, out List <IKernelOutputKeyword> list))
                 {
                     list = new List <IKernelOutputKeyword>();
                     _dicByKernelOutputId.Add(entity.KernelOutputId, list);
                 }
                 list.Add(entity);
                 using (LiteDatabase db = new LiteDatabase(_connectionString)) {
                     var col = db.GetCollection <KernelOutputKeywordData>();
                     col.Insert(entity);
                 }
                 if (!isServer)
                 {
                     VirtualRoot.RaiseEvent(new UserKernelOutputKeywordAddedEvent(message.Id, entity));
                 }
             }
         }
         else if (DevMode.IsDevMode)
         {
             OfficialServer.KernelOutputKeywordService.AddOrUpdateKernelOutputKeywordAsync(KernelOutputKeywordData.Create(message.Input), (response, e) => {
                 if (response.IsSuccess())
                 {
                     VirtualRoot.Execute(new LoadKernelOutputKeywordCommand());
                 }
             });
         }
     });
     VirtualRoot.BuildCmdPath <RemoveKernelOutputKeywordCommand>(action: (message) => {
         InitOnece();
         if (isServer || !DevMode.IsDevMode)
         {
             if (message == null || message.EntityId == Guid.Empty)
             {
                 return;
             }
             if (!_dicById.ContainsKey(message.EntityId))
             {
                 return;
             }
             KernelOutputKeywordData entity = _dicById[message.EntityId];
             _dicById.Remove(entity.GetId());
             if (_dicByKernelOutputId.TryGetValue(entity.KernelOutputId, out List <IKernelOutputKeyword> list))
             {
                 list.Remove(entity);
             }
             using (LiteDatabase db = new LiteDatabase(_connectionString)) {
                 var col = db.GetCollection <KernelOutputKeywordData>();
                 col.Delete(message.EntityId);
             }
             if (!isServer)
             {
                 VirtualRoot.RaiseEvent(new UserKernelOutputKeywordRemovedEvent(message.Id, entity));
             }
         }
         else if (DevMode.IsDevMode)
         {
             OfficialServer.KernelOutputKeywordService.RemoveKernelOutputKeyword(message.EntityId, (response, e) => {
                 if (response.IsSuccess())
                 {
                     VirtualRoot.Execute(new LoadKernelOutputKeywordCommand());
                 }
             });
         }
     });
 }
예제 #27
0
        public LocalIpSet()
        {
            NetworkChange.NetworkAddressChanged += (object sender, EventArgs e) => {
                // 延迟获取网络信息以防止立即获取时获取不到
                TimeSpan.FromSeconds(1).Delay().ContinueWith(t => {
                    var old   = _localIps;
                    _isInited = false;
                    InitOnece();
                    var localIps = _localIps;
                    if (localIps.Length == 0)
                    {
                        VirtualRoot.ThisLocalWarn(nameof(LocalIpSet), "网络连接已断开", toConsole: true);
                    }
                    else
                    {
                        if (old.Length == 0)
                        {
                            VirtualRoot.ThisLocalInfo(nameof(LocalIpSet), "网络连接已连接", toConsole: true);
                        }
                        else
                        {
                            bool isIpChanged = false;
                            if (old.Length != localIps.Length)
                            {
                                isIpChanged = true;
                            }
                            else
                            {
                                foreach (var item in localIps)
                                {
                                    var oldItem = old.FirstOrDefault(a => a.SettingID == item.SettingID);
                                    if (item != oldItem)
                                    {
                                        isIpChanged = true;
                                        break;
                                    }
                                }
                            }
                            VirtualRoot.ThisLocalWarn(nameof(LocalIpSet), $"网络接口的 IP 地址发生了 {(isIpChanged ? "变更" : "刷新")}", toConsole: true);
                        }
                    }
                });
            };
            NetworkChange.NetworkAvailabilityChanged += (object sender, NetworkAvailabilityEventArgs e) => {
                if (e.IsAvailable)
                {
                    VirtualRoot.ThisLocalInfo(nameof(LocalIpSet), $"网络可用", toConsole: true);
                }
                else
                {
                    VirtualRoot.ThisLocalWarn(nameof(LocalIpSet), $"网络不可用", toConsole: true);
                }
            };
            VirtualRoot.BuildCmdPath <SetLocalIpCommand>(action: message => {
                ManagementObject mo = null;
                using (ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration")) {
                    ManagementObjectCollection moc = mc.GetInstances();
                    foreach (ManagementObject item in moc)
                    {
                        if ((string)item["SettingID"] == message.Input.SettingID)
                        {
                            mo = item;
                            break;
                        }
                    }
                }
                if (mo != null)
                {
                    if (message.Input.DHCPEnabled)
                    {
                        mo.InvokeMethod("EnableStatic", null);
                        mo.InvokeMethod("SetGateways", null);
                        mo.InvokeMethod("EnableDHCP", null);
                    }
                    else
                    {
                        ManagementBaseObject inPar = mo.GetMethodParameters("EnableStatic");
                        inPar["IPAddress"]         = new string[] { message.Input.IPAddress };
                        inPar["SubnetMask"]        = new string[] { message.Input.IPSubnet };
                        mo.InvokeMethod("EnableStatic", inPar, null);
                        inPar = mo.GetMethodParameters("SetGateways");
                        inPar["DefaultIPGateway"] = new string[] { message.Input.DefaultIPGateway };
                        mo.InvokeMethod("SetGateways", inPar, null);
                    }

                    if (message.IsAutoDNSServer)
                    {
                        mo.InvokeMethod("SetDNSServerSearchOrder", null);
                    }
                    else
                    {
                        ManagementBaseObject inPar    = mo.GetMethodParameters("SetDNSServerSearchOrder");
                        inPar["DNSServerSearchOrder"] = new string[] { message.Input.DNSServer0, message.Input.DNSServer1 };
                        mo.InvokeMethod("SetDNSServerSearchOrder", inPar, null);
                    }
                }
            });
        }
예제 #28
0
 public ColumnsShowSet(INTMinerRoot root)
 {
     _root = root;
     VirtualRoot.BuildCmdPath <AddColumnsShowCommand>(action: (message) => {
         InitOnece();
         if (message == null || message.Input == null || message.Input.GetId() == Guid.Empty || message.Input.GetId() == ColumnsShowData.PleaseSelect.Id)
         {
             throw new ArgumentNullException();
         }
         if (_dicById.ContainsKey(message.Input.GetId()))
         {
             return;
         }
         ColumnsShowData entity = new ColumnsShowData().Update(message.Input);
         Server.ControlCenterService.AddOrUpdateColumnsShowAsync(entity, (response, exception) => {
             if (response.IsSuccess())
             {
                 _dicById.Add(entity.Id, entity);
                 VirtualRoot.RaiseEvent(new ColumnsShowAddedEvent(entity));
             }
             else
             {
                 Write.UserFail(response.ReadMessage(exception));
             }
         });
     });
     VirtualRoot.BuildCmdPath <UpdateColumnsShowCommand>(action: (message) => {
         InitOnece();
         if (message == null || message.Input == null || message.Input.GetId() == Guid.Empty)
         {
             throw new ArgumentNullException();
         }
         if (!_dicById.ContainsKey(message.Input.GetId()))
         {
             return;
         }
         ColumnsShowData entity   = _dicById[message.Input.GetId()];
         ColumnsShowData oldValue = new ColumnsShowData().Update(entity);
         entity.Update(message.Input);
         Server.ControlCenterService.AddOrUpdateColumnsShowAsync(entity, (response, exception) => {
             if (!response.IsSuccess())
             {
                 entity.Update(oldValue);
                 VirtualRoot.RaiseEvent(new ColumnsShowUpdatedEvent(entity));
                 Write.UserFail(response.ReadMessage(exception));
             }
         });
         VirtualRoot.RaiseEvent(new ColumnsShowUpdatedEvent(entity));
     });
     VirtualRoot.BuildCmdPath <RemoveColumnsShowCommand>(action: (message) => {
         InitOnece();
         if (message == null || message.EntityId == Guid.Empty || message.EntityId == ColumnsShowData.PleaseSelect.Id)
         {
             throw new ArgumentNullException();
         }
         if (!_dicById.ContainsKey(message.EntityId))
         {
             return;
         }
         ColumnsShowData entity = _dicById[message.EntityId];
         Server.ControlCenterService.RemoveColumnsShowAsync(entity.Id, (response, exception) => {
             if (response.IsSuccess())
             {
                 _dicById.Remove(entity.Id);
                 VirtualRoot.RaiseEvent(new ColumnsShowRemovedEvent(entity));
             }
             else
             {
                 Write.UserFail(response.ReadMessage(exception));
             }
         });
     });
 }
예제 #29
0
 public ReadOnlyNTMinerFileSet()
 {
     VirtualRoot.BuildCmdPath <RefreshNTMinerFileSetCommand>(path: message => {
         Refresh();
     }, this.GetType(), LogEnum.DevConsole);
 }
예제 #30
0
 public override void Link()
 {
     VirtualRoot.BuildCmdPath <ShowDialogWindowCommand>(action: message => {
         UIThread.Execute(() => {
             DialogWindow.ShowDialog(new DialogWindowViewModel(message: message.Message, title: message.Title, onYes: message.OnYes, icon: message.Icon));
         });
     });
     VirtualRoot.BuildCmdPath <ShowQQGroupQrCodeCommand>(action: message => {
         UIThread.Execute(() => {
             QQGroupQrCode.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <ShowCalcCommand>(action: message => {
         UIThread.Execute(() => {
             Calc.ShowWindow(message.CoinVm);
         });
     });
     VirtualRoot.BuildCmdPath <ShowLocalIpsCommand>(action: message => {
         UIThread.Execute(() => {
             LocalIpConfig.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <ShowEthNoDevFeeCommand>(action: message => {
         UIThread.Execute(() => {
             EthNoDevFeeEdit.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <ShowCalcConfigCommand>(action: message => {
         UIThread.Execute(() => {
             CalcConfig.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <ShowMinerClientsWindowCommand>(action: message => {
         UIThread.Execute(() => {
             MinerClientsWindow.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <ShowNTMinerUpdaterConfigCommand>(action: message => {
         UIThread.Execute(() => {
             NTMinerUpdaterConfig.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <ShowAboutPageCommand>(action: message => {
         UIThread.Execute(() => {
             AboutPage.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <ShowKernelOutputPageCommand>(action: message => {
         UIThread.Execute(() => {
             KernelOutputPage.ShowWindow(message.SelectedKernelOutputVm);
         });
     });
     VirtualRoot.BuildCmdPath <ShowKernelInputPageCommand>(action: message => {
         UIThread.Execute(() => {
             KernelInputPage.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <ShowTagBrandCommand>(action: message => {
         if (NTMinerRoot.IsBrandSpecified)
         {
             return;
         }
         BrandTag.ShowWindow();
     });
     VirtualRoot.BuildCmdPath <ShowCoinPageCommand>(action: message => {
         UIThread.Execute(() => {
             CoinPage.ShowWindow(message.CurrentCoin, message.TabType);
         });
     });
     VirtualRoot.BuildCmdPath <ShowGroupPageCommand>(action: message => {
         UIThread.Execute(() => {
             GroupPage.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <ShowSysDicPageCommand>(action: message => {
         UIThread.Execute(() => {
             SysDicPage.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <ShowVirtualMemoryCommand>(action: message => {
         UIThread.Execute(() => {
             VirtualMemory.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <ShowRestartWindowsCommand>(action: message => {
         UIThread.Execute(() => {
             RestartWindows.ShowDialog();
         });
     });
     VirtualRoot.BuildCmdPath <ShowNotificationSampleCommand>(action: message => {
         UIThread.Execute(() => {
             NotificationSample.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <ShowPropertyCommand>(action: message => {
         UIThread.Execute(() => {
             Property.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <ShowChartsWindowCommand>(action: message => {
         UIThread.Execute(() => {
             ChartsWindow.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <ShowOverClockDataPageCommand>(action: message => {
         UIThread.Execute(() => {
             OverClockDataPage.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <ShowNTMinerWalletPageCommand>(action: message => {
         UIThread.Execute(() => {
             NTMinerWalletPage.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <ShowMessagePathIdsCommand>(action: message => {
         UIThread.Execute(() => {
             MessagePathIds.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <ShowUserPageCommand>(action: message => {
         UIThread.Execute(() => {
             UserPage.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <ShowRemoteDesktopLoginDialogCommand>(action: message => {
         RemoteDesktopLogin.ShowWindow(message.Vm);
     });
     VirtualRoot.BuildCmdPath <ShowKernelsWindowCommand>(action: message => {
         UIThread.Execute(() => {
             KernelsWindow.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <ShowKernelDownloaderCommand>(action: message => {
         UIThread.Execute(() => {
             KernelDownloading.ShowWindow(message.KernelId, message.DownloadComplete);
         });
     });
     VirtualRoot.BuildCmdPath <EnvironmentVariableEditCommand>(action: message => {
         UIThread.Execute(() => {
             EnvironmentVariableEdit.ShowWindow(message.CoinKernelVm, message.EnvironmentVariable);
         });
     });
     VirtualRoot.BuildCmdPath <InputSegmentEditCommand>(action: message => {
         UIThread.Execute(() => {
             InputSegmentEdit.ShowWindow(message.CoinKernelVm, message.Segment);
         });
     });
     VirtualRoot.BuildCmdPath <CoinKernelEditCommand>(action: message => {
         UIThread.Execute(() => {
             CoinKernelEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.BuildCmdPath <CoinEditCommand>(action: message => {
         UIThread.Execute(() => {
             CoinEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.BuildCmdPath <ColumnsShowEditCommand>(action: message => {
         UIThread.Execute(() => {
             ColumnsShowEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.BuildCmdPath <ShowContainerWindowCommand>(action: message => {
         UIThread.Execute(() => {
             ContainerWindow window = ContainerWindow.GetWindow(message.Vm);
             window?.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <ShowSpeedChartsCommand>(action: message => {
         UIThread.Execute(() => {
             SpeedCharts.ShowWindow(message.GpuSpeedVm);
         });
     });
     VirtualRoot.BuildCmdPath <ShowFileWriterPageCommand>(action: message => {
         UIThread.Execute(() => {
             FileWriterPage.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <FileWriterEditCommand>(action: message => {
         UIThread.Execute(() => {
             FileWriterEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.BuildCmdPath <ShowFragmentWriterPageCommand>(action: message => {
         UIThread.Execute(() => {
             FragmentWriterPage.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <FragmentWriterEditCommand>(action: message => {
         UIThread.Execute(() => {
             FragmentWriterEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.BuildCmdPath <GroupEditCommand>(action: message => {
         UIThread.Execute(() => {
             GroupEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.BuildCmdPath <KernelInputEditCommand>(action: message => {
         UIThread.Execute(() => {
             KernelInputEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.BuildCmdPath <KernelOutputFilterEditCommand>(action: message => {
         UIThread.Execute(() => {
             KernelOutputFilterEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.BuildCmdPath <KernelOutputTranslaterEditCommand>(action: message => {
         UIThread.Execute(() => {
             KernelOutputTranslaterEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.BuildCmdPath <KernelOutputEditCommand>(action: message => {
         UIThread.Execute(() => {
             KernelOutputEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.BuildCmdPath <ShowPackagesWindowCommand>(action: message => {
         UIThread.Execute(() => {
             PackagesWindow.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <KernelEditCommand>(action: message => {
         UIThread.Execute(() => {
             KernelEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.BuildCmdPath <ShowLogColorCommand>(action: message => {
         UIThread.Execute(() => {
             LogColor.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <ShowMinerClientSettingCommand>(action: message => {
         UIThread.Execute(() => {
             MinerClientSetting.ShowWindow(message.Vm);
         });
     });
     VirtualRoot.BuildCmdPath <ShowMinerNamesSeterCommand>(action: message => {
         UIThread.Execute(() => {
             MinerNamesSeter.ShowWindow(message.Vm);
         });
     });
     VirtualRoot.BuildCmdPath <ShowGpuProfilesPageCommand>(action: message => {
         UIThread.Execute(() => {
             GpuProfilesPage.ShowWindow(message.MinerClientsWindowVm);
         });
     });
     VirtualRoot.BuildCmdPath <ShowMinerClientAddCommand>(action: message => {
         UIThread.Execute(() => {
             MinerClientAdd.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <MinerGroupEditCommand>(action: message => {
         UIThread.Execute(() => {
             MinerGroupEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.BuildCmdPath <NTMinerWalletEditCommand>(action: message => {
         UIThread.Execute(() => {
             NTMinerWalletEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.BuildCmdPath <MineWorkEditCommand>(action: message => {
         UIThread.Execute(() => {
             MineWorkEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.BuildCmdPath <OverClockDataEditCommand>(action: message => {
         UIThread.Execute(() => {
             OverClockDataEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.BuildCmdPath <PackageEditCommand>(action: message => {
         UIThread.Execute(() => {
             PackageEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.BuildCmdPath <PoolKernelEditCommand>(action: message => {
         UIThread.Execute(() => {
             PoolKernelEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.BuildCmdPath <PoolEditCommand>(action: message => {
         UIThread.Execute(() => {
             PoolEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.BuildCmdPath <ShowControlCenterHostConfigCommand>(action: message => {
         UIThread.Execute(() => {
             ControlCenterHostConfig.ShowWindow();
         });
     });
     VirtualRoot.BuildCmdPath <SysDicItemEditCommand>(action: message => {
         UIThread.Execute(() => {
             SysDicItemEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.BuildCmdPath <SysDicEditCommand>(action: message => {
         UIThread.Execute(() => {
             SysDicEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.BuildCmdPath <UserEditCommand>(action: message => {
         UIThread.Execute(() => {
             UserEdit.ShowWindow(message.FormType, message.Source);
         });
     });
     VirtualRoot.BuildCmdPath <WalletEditCommand>(action: message => {
         UIThread.Execute(() => {
             WalletEdit.ShowWindow(message.FormType, message.Source);
         });
     });
 }