private static void ContinueCreateProcess(IMineContext mineContext)
            {
                Thread.Sleep(1000);
                if (mineContext != Instance.LockedMineContext)
                {
                    Write.UserWarn("挖矿停止");
                    return;
                }
                // 解压内核包
                if (!mineContext.Kernel.ExtractPackage())
                {
                    VirtualRoot.RaiseEvent(new StartingMineFailedEvent("内核解压失败,请卸载内核重试。"));
                }
                else
                {
                    Write.UserOk("内核包解压成功");
                }

                // 执行文件书写器
                mineContext.ExecuteFileWriters();

                // 分离命令名和参数
                GetCmdNameAndArguments(mineContext, out string kernelExeFileFullName, out string arguments);
                // 这是不应该发生的,如果发生很可能是填写命令的时候拼写错误了
                if (!File.Exists(kernelExeFileFullName))
                {
                    Write.UserError(kernelExeFileFullName + "文件不存在,可能是被杀软删除导致,请退出杀毒软件重试或者QQ群联系小编,解释:大部分挖矿内核会报毒,不是开源矿工的问题也不是杀软的问题,也不是挖矿内核的问题,是挖矿这件事情的问题,可能是挖矿符合了病毒的定义。");
                }
                if (mineContext.KernelProcessType == KernelProcessType.Logfile)
                {
                    arguments = arguments.Replace(NTKeyword.LogFileParameterName, mineContext.LogFileFullName);
                }
                Write.UserOk($"\"{kernelExeFileFullName}\" {arguments}");
                Write.UserInfo($"有请内核上场:{mineContext.KernelProcessType}");
                if (mineContext != Instance.LockedMineContext)
                {
                    Write.UserWarn("挖矿停止");
                    return;
                }
                switch (mineContext.KernelProcessType)
                {
                case KernelProcessType.Logfile:
                    CreateLogfileProcess(mineContext, kernelExeFileFullName, arguments);
                    break;

                case KernelProcessType.Pip:
                    CreatePipProcess(mineContext, kernelExeFileFullName, arguments);
                    break;

                default:
                    throw new InvalidProgramException();
                }
                VirtualRoot.RaiseEvent(new MineStartedEvent(mineContext));
            }
Esempio n. 2
0
        private void SetServerJsonVersion(string serverJsonVersion)
        {
            AppSettingData appSettingData = new AppSettingData()
            {
                Key   = NTKeyword.ServerJsonVersionAppSettingKey,
                Value = serverJsonVersion
            };
            string oldVersion = GetServerJsonVersion();

            VirtualRoot.Execute(new SetLocalAppSettingCommand(appSettingData));
            VirtualRoot.RaiseEvent(new ServerJsonVersionChangedEvent(oldVersion, serverJsonVersion));
        }
Esempio n. 3
0
        static void Main()
        {
            NTMinerConsole.SetIsMainUiOk(true);
            NTMinerConsole.DisbleQuickEditMode();
            DevMode.SetDevMode();

            Windows.ConsoleHandler.Register(Exit);

            Console.Title = $"{ServerAppType.WsServer.GetName()}_{ServerRoot.HostConfig.ThisServerAddress}";
            // 通过WsServer的网络缓解对WebApiServer的外网流量的压力。WsServer调用WebApiServer的时候走内网调用节省外网带宽
            RpcRoot.SetOfficialServerAddress(ServerRoot.HostConfig.RpcServerLocalAddress);
            // 用本节点的地址作为队列名,消费消息时根据路由键区分消息类型
            string queue        = $"{ServerAppType.WsServer.GetName()}.{ServerRoot.HostConfig.ThisServerAddress}";
            string durableQueue = queue + MqKeyword.DurableQueueEndsWith;

            AbstractMqMessagePath[] mqMessagePaths = new AbstractMqMessagePath[] {
                new ReadOnlyUserMqMessagePath(durableQueue),
                new MinerSignMqMessagePath(durableQueue),
                new WsServerNodeMqMessagePath(queue),
                new OperationMqMessagePath(queue)
            };
            if (!ServerConnection.Create(ServerAppType.WsServer, mqMessagePaths, out IServerConnection serverConfig))
            {
                NTMinerConsole.UserError("启动失败,无法继续,因为服务器上下文创建失败");
                return;
            }
            MinerClientMqSender    = new MinerClientMqSender(serverConfig);
            SpeedDataRedis         = new SpeedDataRedis(serverConfig);
            WsServerNodeRedis      = new WsServerNodeRedis(serverConfig);
            OperationMqSender      = new OperationMqSender(serverConfig);
            UserMqSender           = new UserMqSender(serverConfig);
            _wsServerNodeMqSender  = new WsServerNodeMqSender(serverConfig);
            WsServerNodeAddressSet = new WsServerNodeAddressSet(WsServerNodeRedis, _wsServerNodeMqSender);
            var minerRedis = new ReadOnlyMinerRedis(serverConfig);
            var userRedis  = new ReadOnlyUserRedis(serverConfig);

            VirtualRoot.StartTimer();
            RpcRoot.SetRpcUser(new RpcUser(ServerRoot.HostConfig.RpcLoginName, HashUtil.Sha1(ServerRoot.HostConfig.RpcPassword)));
            RpcRoot.SetIsOuterNet(false);
            // 构造函数中异步访问redis初始化用户列表,因为是异步的所以提前构造
            ReadOnlyUserSet       = new ReadOnlyUserSet(userRedis);
            MinerSignSet          = new MinerSignSet(minerRedis);
            _wsServer             = new SharpWsServer(ServerRoot.HostConfig);
            MinerClientSessionSet = new MinerClientSessionSet(_wsServer.MinerClientWsSessionsAdapter);
            MinerStudioSessionSet = new MinerStudioSessionSet(_wsServer.MinerStudioWsSessionsAdapter);
            _wsServer.Start();
            VirtualRoot.RaiseEvent(new WebSocketServerStatedEvent());
            _started = true;

            Console.ReadKey(true);
            Exit();
        }
Esempio n. 4
0
 /// <summary>
 /// 如果给定的服务器版本比本地版本高则发布AppVersionChangedEvent事件
 /// </summary>
 /// <param name="serverVersion"></param>
 public static void PublishIfNewVersion(string serverVersion)
 {
     if (!string.IsNullOrEmpty(serverVersion) && serverVersion != MainAssemblyInfo.CurrentVersion.ToString())
     {
         if (Version.TryParse(serverVersion, out Version v))
         {
             if (v > MainAssemblyInfo.CurrentVersion)
             {
                 NTMinerRoot.ServerVersion = v;
                 VirtualRoot.RaiseEvent(new AppVersionChangedEvent());
             }
         }
     }
 }
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            base.OnActionExecuting(actionContext);
            string ip = actionContext.Request.GetRemoteIp();

            if (IPAddress.TryParse(ip, out IPAddress remoteIp))
            {
                VirtualRoot.RaiseEvent(new WebApiRequestEvent(remoteIp));
            }
            string controllerName = actionContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            string actionName     = $"{controllerName}.{actionContext.ActionDescriptor.ActionName}";

            AppRoot.Action(actionName);
        }
Esempio n. 6
0
 /// <summary>
 /// 如果给定的服务器版本比本地版本高则发布AppVersionChangedEvent事件
 /// </summary>
 /// <param name="serverVersion"></param>
 public static void PublishIfNewVersion(string serverVersion)
 {
     if (!string.IsNullOrEmpty(serverVersion) && serverVersion != EntryAssemblyInfo.CurrentVersionStr)
     {
         if (Version.TryParse(serverVersion, out Version v))
         {
             if (v > EntryAssemblyInfo.CurrentVersion)
             {
                 NTMinerContext.SetServerVersion(v);
                 VirtualRoot.RaiseEvent(new AppVersionChangedEvent());
             }
         }
     }
 }
Esempio n. 7
0
 private void ContextReInit(bool isWork)
 {
     ReInitServerJson();
     IsJsonServer = !DevMode.IsDevMode || VirtualRoot.IsMinerStudio || isWork;
     this.ServerContext.ReInit();
     // CoreContext的视图模型集此时刷新
     VirtualRoot.RaiseEvent(new ServerContextReInitedEvent());
     // CoreContext的视图模型集已全部刷新,此时刷新视图界面
     VirtualRoot.RaiseEvent(new ServerContextVmsReInitedEvent());
     if (isWork)
     {
         // 有可能是由非作业切换为作业,所以需要对IsJsonLocal赋值
         IsJsonLocal = true;
         ReInitMinerProfile();
     }
 }
 private WalletViewModels()
 {
     if (WpfUtil.IsInDesignMode)
     {
         return;
     }
     VirtualRoot.AddEventPath <LocalContextReInitedEvent>("LocalContext刷新后刷新钱包Vm内存", LogEnum.None,
                                                          action: message => {
         _dicById.Clear();
         Init();
     }, location: this.GetType());
     AddEventPath <WalletAddedEvent>("添加了钱包后调整VM内存", LogEnum.DevConsole,
                                     action: (message) => {
         _dicById.Add(message.Source.GetId(), new WalletViewModel(message.Source));
         OnPropertyChanged(nameof(WalletList));
         if (CoinVms.TryGetCoinVm(message.Source.CoinId, out CoinViewModel coin))
         {
             coin.OnPropertyChanged(nameof(CoinViewModel.Wallets));
             coin.OnPropertyChanged(nameof(CoinViewModel.WalletItems));
             coin.CoinKernel?.CoinKernelProfile?.SelectedDualCoin?.OnPropertyChanged(nameof(CoinViewModel.Wallets));
         }
         VirtualRoot.RaiseEvent(new WalletVmAddedEvent(message));
     }, location: this.GetType());
     AddEventPath <WalletRemovedEvent>("删除了钱包后调整VM内存", LogEnum.DevConsole,
                                       action: (message) => {
         _dicById.Remove(message.Source.GetId());
         OnPropertyChanged(nameof(WalletList));
         if (CoinVms.TryGetCoinVm(message.Source.CoinId, out CoinViewModel coin))
         {
             coin.OnPropertyChanged(nameof(CoinViewModel.Wallets));
             coin.OnPropertyChanged(nameof(CoinViewModel.WalletItems));
             coin.CoinProfile?.OnPropertyChanged(nameof(CoinProfileViewModel.SelectedWallet));
             coin.CoinKernel?.CoinKernelProfile?.SelectedDualCoin?.OnPropertyChanged(nameof(CoinViewModel.Wallets));
         }
         VirtualRoot.RaiseEvent(new WalletVmRemovedEvent(message));
     }, location: this.GetType());
     AddEventPath <WalletUpdatedEvent>("更新了钱包后调整VM内存", LogEnum.DevConsole,
                                       action: (message) => {
         if (_dicById.TryGetValue(message.Source.GetId(), out WalletViewModel vm))
         {
             vm.Update(message.Source);
         }
     }, location: this.GetType());
     Init();
 }
Esempio n. 9
0
        public void Test()
        {
            List <PathPriority> list = new List <PathPriority>();

            VirtualRoot.BuildEventPath <Event1>("Normal", LogEnum.DevConsole, this.GetType(), PathPriority.Normal, message => {
                list.Add(PathPriority.Normal);
            });
            VirtualRoot.BuildEventPath <Event1>("BelowNormal", LogEnum.DevConsole, this.GetType(), PathPriority.BelowNormal, message => {
                list.Add(PathPriority.BelowNormal);
            });
            VirtualRoot.BuildEventPath <Event1>("AboveNormal", LogEnum.DevConsole, this.GetType(), PathPriority.AboveNormal, message => {
                list.Add(PathPriority.AboveNormal);
            });
            VirtualRoot.RaiseEvent(new Event1());
            Assert.AreEqual(list[0], PathPriority.AboveNormal);
            Assert.AreEqual(list[1], PathPriority.Normal);
            Assert.AreEqual(list[2], PathPriority.BelowNormal);
        }
Esempio n. 10
0
 private void ContextReInit(bool isWork)
 {
     foreach (var handler in _serverContextHandlers)
     {
         VirtualRoot.DeletePath(handler);
     }
     _serverContextHandlers.Clear();
     if (isWork)
     {
         ReInitServerJson();
     }
     ServerContextInit(isWork);
     // CoreContext的视图模型集此时刷新
     VirtualRoot.RaiseEvent(new ServerContextReInitedEvent());
     // CoreContext的视图模型集已全部刷新,此时刷新视图界面
     VirtualRoot.RaiseEvent(new ServerContextVmsReInitedEvent());
     if (isWork)
     {
         // 有可能是由非作业切换为作业,所以需要对IsJsonLocal赋值
         IsJsonLocal = true;
         ReInitMinerProfile();
     }
 }
Esempio n. 11
0
 private void ShowMainWindow(bool isToggle)
 {
     UIThread.Execute(() => {
         _appViewFactory.ShowMainWindow(isToggle);
         // 使状态栏显示显示最新状态
         if (NTMinerRoot.Instance.IsMining)
         {
             var mainCoin = NTMinerRoot.Instance.LockedMineContext.MainCoin;
             if (mainCoin == null)
             {
                 return;
             }
             var coinShare = NTMinerRoot.Instance.CoinShareSet.GetOrCreate(mainCoin.GetId());
             VirtualRoot.RaiseEvent(new ShareChangedEvent(Guid.Empty, coinShare));
             if ((NTMinerRoot.Instance.LockedMineContext is IDualMineContext dualMineContext) && dualMineContext.DualCoin != null)
             {
                 coinShare = NTMinerRoot.Instance.CoinShareSet.GetOrCreate(dualMineContext.DualCoin.GetId());
                 VirtualRoot.RaiseEvent(new ShareChangedEvent(Guid.Empty, coinShare));
             }
             AppContext.Instance.GpuSpeedVms.Refresh();
         }
     });
 }
Esempio n. 12
0
        public static void Init(Application app)
        {
            _app = app;
            AppDomain.CurrentDomain.UnhandledException += (object sender, UnhandledExceptionEventArgs e) => {
                if (e.ExceptionObject is Exception exception)
                {
                    Handle(exception);
                }
            };

            app.DispatcherUnhandledException += (object sender, DispatcherUnhandledExceptionEventArgs e) => {
                Handle(e.Exception);
                e.Handled = true;
            };

            UIThread.InitializeWithDispatcher(app.Dispatcher);
            Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("zh-CN");
            app.SessionEnding += (sender, e) => {
                OsSessionEndingEvent.ReasonSessionEnding reason;
                switch (e.ReasonSessionEnding)
                {
                case ReasonSessionEnding.Logoff:
                    reason = OsSessionEndingEvent.ReasonSessionEnding.Logoff;
                    break;

                case ReasonSessionEnding.Shutdown:
                    reason = OsSessionEndingEvent.ReasonSessionEnding.Shutdown;
                    break;

                default:
                    reason = OsSessionEndingEvent.ReasonSessionEnding.Unknown;
                    break;
                }
                VirtualRoot.RaiseEvent(new OsSessionEndingEvent(reason));
            };
        }
Esempio n. 13
0
        public void Test()
        {
            List <PathPriority>   list  = new List <PathPriority>();
            List <IMessagePathId> paths = new List <IMessagePathId> {
                VirtualRoot.BuildEventPath <Event1>("Normal", LogEnum.DevConsole, this.GetType(), PathPriority.Normal, message => {
                    list.Add(PathPriority.Normal);
                }),
                VirtualRoot.BuildEventPath <Event1>("BelowNormal", LogEnum.DevConsole, this.GetType(), PathPriority.BelowNormal, message => {
                    list.Add(PathPriority.BelowNormal);
                }),
                VirtualRoot.BuildEventPath <Event1>("AboveNormal", LogEnum.DevConsole, this.GetType(), PathPriority.AboveNormal, message => {
                    list.Add(PathPriority.AboveNormal);
                })
            };

            VirtualRoot.RaiseEvent(new Event1());
            Assert.AreEqual(PathPriority.AboveNormal, list[0]);
            Assert.AreEqual(PathPriority.Normal, list[1]);
            Assert.AreEqual(PathPriority.BelowNormal, list[2]);
            foreach (var path in paths)
            {
                VirtualRoot.RemoveMessagePath(path);
            }
        }
Esempio n. 14
0
        static void Main(string[] args)
        {
            if (args.Length != 0)
            {
                if (args.Contains("--sha1"))
                {
                    File.WriteAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "sha1"), Sha1);
                    return;
                }
            }
            try {
                SystemEvents.SessionEnding += (sender, e) => {
                    OsSessionEndingEvent.ReasonSessionEnding reason;
                    switch (e.Reason)
                    {
                    case SessionEndReasons.Logoff:
                        reason = OsSessionEndingEvent.ReasonSessionEnding.Logoff;
                        break;

                    case SessionEndReasons.SystemShutdown:
                        reason = OsSessionEndingEvent.ReasonSessionEnding.Shutdown;
                        break;

                    default:
                        reason = OsSessionEndingEvent.ReasonSessionEnding.Unknown;
                        break;
                    }
                    VirtualRoot.RaiseEvent(new OsSessionEndingEvent(reason));
                };
                VirtualRoot.StartTimer();
                _waitHandle = new AutoResetEvent(false);
                bool mutexCreated;
                try {
                    _sMutexApp = new Mutex(true, "NTMinerDaemonAppMutex", out mutexCreated);
                }
                catch {
                    mutexCreated = false;
                }
                if (mutexCreated)
                {
                    NTMinerRegistry.SetDaemonVersion(Sha1);
                    NTMinerRegistry.SetAutoBoot("NTMinerDaemon", true);
                    bool isAutoBoot = MinerProfileUtil.GetIsAutoBoot();
                    if (isAutoBoot)
                    {
                        string location = NTMinerRegistry.GetLocation();
                        if (!string.IsNullOrEmpty(location) && File.Exists(location))
                        {
                            string    processName = Path.GetFileName(location);
                            Process[] processes   = Process.GetProcessesByName(processName);
                            if (processes.Length == 0)
                            {
                                string arguments = NTMinerRegistry.GetArguments();
                                if (NTMinerRegistry.GetIsLastIsWork())
                                {
                                    arguments = "--work " + arguments;
                                }
                                try {
                                    Process.Start(location, arguments);
                                    Write.DevOk($"启动挖矿端 {location} {arguments}");
                                }
                                catch (Exception e) {
                                    Logger.ErrorDebugLine($"启动挖矿端失败因为异常 {location} {arguments}", e);
                                }
                            }
                            else
                            {
                                Write.DevDebug($"挖矿端已经在运行中无需启动");
                            }
                        }
                    }
                    else
                    {
                        Write.DevDebug($"挖矿端未设置为自动启动");
                    }
                    Run();
                }
            }
            catch (Exception e) {
                Logger.ErrorDebugLine(e);
            }
        }
 private CoinKernelViewModels()
 {
     if (WpfUtil.IsInDesignMode)
     {
         return;
     }
     VirtualRoot.BuildEventPath <ServerContextReInitedEvent>("刷新VM内存", LogEnum.DevConsole,
                                                             path: message => {
         _dicById.Clear();
         Init();
     }, location: this.GetType());
     VirtualRoot.BuildEventPath <ServerContextReInitedEventHandledEvent>("刷新视图界面", LogEnum.DevConsole,
                                                                         path: message => {
         OnPropertyChanged(nameof(AllCoinKernels));
     }, location: this.GetType());
     BuildEventPath <CoinKernelAddedEvent>("刷新VM内存", LogEnum.DevConsole,
                                           path: (message) => {
         var coinKernelVm = new CoinKernelViewModel(message.Source);
         _dicById.Add(message.Source.GetId(), coinKernelVm);
         OnPropertyChanged(nameof(AllCoinKernels));
         var kernelVm = coinKernelVm.Kernel;
         if (kernelVm != null)
         {
             kernelVm.OnPropertyChanged(nameof(kernelVm.CoinKernels));
             kernelVm.OnPropertyChanged(nameof(kernelVm.CoinVms));
             kernelVm.OnPropertyChanged(nameof(kernelVm.SupportedCoinVms));
             kernelVm.OnPropertyChanged(nameof(kernelVm.SupportedCoins));
         }
         VirtualRoot.RaiseEvent(new CoinKernelVmAddedEvent(message));
     }, location: this.GetType());
     BuildEventPath <CoinKernelUpdatedEvent>("刷新VM内存", LogEnum.DevConsole,
                                             path: (message) => {
         if (_dicById.TryGetValue(message.Source.GetId(), out CoinKernelViewModel vm))
         {
             var supportedGpu     = vm.SupportedGpu;
             Guid dualCoinGroupId = vm.DualCoinGroupId;
             vm.Update(message.Source);
             if (supportedGpu != vm.SupportedGpu)
             {
                 var coinKernels = AllCoinKernels.Where(a => a.KernelId == vm.Id);
                 foreach (var coinKernel in coinKernels)
                 {
                     if (CoinVms.TryGetCoinVm(coinKernel.CoinId, out CoinViewModel coinVm))
                     {
                         coinVm.OnPropertyChanged(nameof(coinVm.IsSupported));
                         coinVm.OnPropertyChanged(nameof(coinVm.CoinKernels));
                     }
                 }
                 var kernelVm = vm.Kernel;
                 kernelVm.OnPropertyChanged(nameof(kernelVm.CoinKernels));
             }
         }
     }, location: this.GetType());
     BuildEventPath <CoinKernelRemovedEvent>("刷新VM内存", LogEnum.DevConsole,
                                             path: (message) => {
         if (_dicById.TryGetValue(message.Source.GetId(), out CoinKernelViewModel coinKernelVm))
         {
             _dicById.Remove(message.Source.GetId());
             OnPropertyChanged(nameof(AllCoinKernels));
             var kernelVm = coinKernelVm.Kernel;
             kernelVm.OnPropertyChanged(nameof(kernelVm.CoinKernels));
             kernelVm.OnPropertyChanged(nameof(kernelVm.CoinVms));
             kernelVm.OnPropertyChanged(nameof(kernelVm.SupportedCoinVms));
             kernelVm.OnPropertyChanged(nameof(kernelVm.SupportedCoins));
             VirtualRoot.RaiseEvent(new CoinKernelVmRemovedEvent(message));
         }
     }, location: this.GetType());
     Init();
 }
Esempio n. 16
0
        private void BuildPaths()
        {
            VirtualRoot.AddCmdPath <MinerClientActionCommand>(action: message => {
                #region
                try {
                    switch (message.ActionType)
                    {
                    case MinerClientActionType.SwitchRadeonGpuOn:
                        VirtualRoot.Execute(new SwitchRadeonGpuCommand(on: true));
                        break;

                    case MinerClientActionType.SwitchRadeonGpuOff:
                        VirtualRoot.Execute(new SwitchRadeonGpuCommand(on: false));
                        break;

                    case MinerClientActionType.BlockWAU:
                        VirtualRoot.Execute(new BlockWAUCommand());
                        break;

                    default:
                        break;
                    }
                }
                catch (Exception e) {
                    Logger.ErrorDebugLine(e);
                }
                #endregion
            }, location: this.GetType());
            #region 处理显示主界面命令
            VirtualRoot.AddCmdPath <ShowMainWindowCommand>(action: message => {
                UIThread.Execute(() => {
                    _appViewFactory.ShowMainWindow(message.IsToggle, out Window _);
                    // 使状态栏显示显示最新状态
                    if (NTMinerContext.Instance.IsMining)
                    {
                        var mainCoin = NTMinerContext.Instance.LockedMineContext.MainCoin;
                        if (mainCoin == null)
                        {
                            return;
                        }
                        var coinShare = NTMinerContext.Instance.CoinShareSet.GetOrCreate(mainCoin.GetId());
                        VirtualRoot.RaiseEvent(new ShareChangedEvent(PathId.Empty, coinShare));
                        if ((NTMinerContext.Instance.LockedMineContext is IDualMineContext dualMineContext) && dualMineContext.DualCoin != null)
                        {
                            coinShare = NTMinerContext.Instance.CoinShareSet.GetOrCreate(dualMineContext.DualCoin.GetId());
                            VirtualRoot.RaiseEvent(new ShareChangedEvent(PathId.Empty, coinShare));
                        }
                        AppRoot.GpuSpeedVms.Refresh();
                    }
                });
            }, location: this.GetType());
            #endregion
            #region 周期确保守护进程在运行
            VirtualRoot.AddEventPath <Per1MinuteEvent>("周期确保守护进程在运行", LogEnum.DevConsole,
                                                       action: message => {
                Daemon.DaemonUtil.RunNTMinerDaemon();
                NoDevFee.NoDevFeeUtil.RunNTMinerNoDevFee();
            }, location: this.GetType());
            #endregion
            #region 开始和停止挖矿后
            VirtualRoot.AddEventPath <StartingMineEvent>("开始挖矿时更新挖矿按钮状态", LogEnum.DevConsole,
                                                         action: message => {
                AppRoot.MinerProfileVm.IsMining = true;
                // 因为无界面模式不一定会构建挖矿状态按钮,所以放在这里而不放在挖矿按钮的VM中
                StartStopMineButtonViewModel.Instance.BtnStopText = "正在挖矿";
            }, location: this.GetType());
            VirtualRoot.AddEventPath <MineStartedEvent>("启动1080ti小药丸、启动DevConsole? 更新挖矿按钮状态", LogEnum.DevConsole,
                                                        action: message => {
                // 启动DevConsole
                if (NTMinerContext.IsUseDevConsole)
                {
                    var mineContext     = message.MineContext;
                    string poolIp       = mineContext.MainCoinPool.GetIp();
                    string consoleTitle = mineContext.MainCoinPool.Server;
                    Daemon.DaemonUtil.RunDevConsoleAsync(poolIp, consoleTitle);
                }
                OhGodAnETHlargementPill.OhGodAnETHlargementPillUtil.Start();
            }, location: this.GetType());
            VirtualRoot.AddEventPath <MineStopedEvent>("停止挖矿后停止1080ti小药丸 挖矿停止后更新界面挖矿状态", LogEnum.DevConsole,
                                                       action: message => {
                AppRoot.MinerProfileVm.IsMining = false;
                // 因为无界面模式不一定会构建挖矿状态按钮,所以放在这里而不放在挖矿按钮的VM中
                StartStopMineButtonViewModel.Instance.BtnStopText = "尚未开始";
                OhGodAnETHlargementPill.OhGodAnETHlargementPillUtil.Stop();
            }, location: this.GetType());
            #endregion
            #region 处理禁用win10系统更新
            VirtualRoot.AddCmdPath <BlockWAUCommand>(action: message => {
                NTMiner.Windows.WindowsUtil.BlockWAU().ContinueWith(t => {
                    if (t.Exception == null)
                    {
                        VirtualRoot.ThisLocalInfo(nameof(App), "禁用windows系统更新成功", OutEnum.Success);
                    }
                    else
                    {
                        VirtualRoot.ThisLocalError(nameof(App), "禁用windows系统更新失败", OutEnum.Error);
                    }
                });
            }, location: this.GetType());
            #endregion
            #region 优化windows
            VirtualRoot.AddCmdPath <Win10OptimizeCommand>(action: message => {
                NTMiner.Windows.WindowsUtil.Win10Optimize(e => {
                    if (e == null)
                    {
                        VirtualRoot.ThisLocalInfo(nameof(App), "优化Windows成功", OutEnum.Success);
                    }
                    else
                    {
                        VirtualRoot.ThisLocalError(nameof(App), "优化Windows失败", OutEnum.Error);
                    }
                });
            }, location: this.GetType());
            #endregion
            #region 处理开启A卡计算模式
            VirtualRoot.AddCmdPath <SwitchRadeonGpuCommand>(action: message => {
                if (NTMinerContext.Instance.GpuSet.GpuType == GpuType.AMD)
                {
                    AppRoot.SwitchRadeonGpu(message.On);
                }
            }, location: this.GetType());
            #endregion
            #region 处理A卡驱动签名
            VirtualRoot.AddCmdPath <AtikmdagPatcherCommand>(action: message => {
                if (NTMinerContext.Instance.GpuSet.GpuType == GpuType.AMD)
                {
                    AppRoot.OpenAtikmdagPatcher();
                }
            }, location: this.GetType());
            #endregion
            #region 启用或禁用windows远程桌面
            VirtualRoot.AddCmdPath <EnableRemoteDesktopCommand>(action: message => {
                if (NTMinerRegistry.GetIsRdpEnabled())
                {
                    return;
                }
                string msg = "确定启用Windows远程桌面吗?";
                DialogWindow.ShowSoftDialog(new DialogWindowViewModel(
                                                message: msg,
                                                title: "确认",
                                                onYes: () => {
                    NTMinerRegistry.SetIsRdpEnabled(true);
                    Firewall.AddRdpRule();
                }));
            }, location: this.GetType());
            #endregion
            #region 启用或禁用windows开机自动登录
            VirtualRoot.AddCmdPath <EnableOrDisableWindowsAutoLoginCommand>(action: message => {
                if (NTMiner.Windows.OS.Instance.IsAutoAdminLogon)
                {
                    return;
                }
                if (NTMiner.Windows.OS.Instance.IsGEWindows2004)
                {
                    WindowsAutoLogon.ShowWindow();
                }
                else
                {
                    VirtualRoot.Execute(new UnTopmostCommand());
                    NTMiner.Windows.Cmd.RunClose("control", "userpasswords2");
                }
            }, location: this.GetType());
            #endregion
        }
Esempio n. 17
0
 protected override void OnExit(ExitEventArgs e)
 {
     VirtualRoot.RaiseEvent(new AppExitEvent());
     base.OnExit(e);
     NTMinerConsole.Free();
 }
Esempio n. 18
0
        private void BuildPaths()
        {
            VirtualRoot.BuildCmdPath <MinerClientActionCommand>(path: message => {
                #region
                try {
                    switch (message.ActionType)
                    {
                    case MinerClientActionType.SwitchRadeonGpuOn:
                        VirtualRoot.Execute(new SwitchRadeonGpuCommand(on: true));
                        break;

                    case MinerClientActionType.SwitchRadeonGpuOff:
                        VirtualRoot.Execute(new SwitchRadeonGpuCommand(on: false));
                        break;

                    default:
                        break;
                    }
                }
                catch (Exception e) {
                    Logger.ErrorDebugLine(e);
                }
                #endregion
            }, location: this.GetType());
            #region 处理显示主界面命令
            VirtualRoot.BuildCmdPath <ShowMainWindowCommand>(path: message => {
                UIThread.Execute(() => {
                    _appViewFactory.ShowMainWindow(message.IsToggle, out Window _);
                    // 使状态栏显示显示最新状态
                    if (NTMinerContext.Instance.IsMining)
                    {
                        var mainCoin = NTMinerContext.Instance.LockedMineContext.MainCoin;
                        if (mainCoin == null)
                        {
                            return;
                        }
                        var coinShare = NTMinerContext.Instance.CoinShareSet.GetOrCreate(mainCoin.GetId());
                        VirtualRoot.RaiseEvent(new ShareChangedEvent(PathId.Empty, coinShare));
                        if ((NTMinerContext.Instance.LockedMineContext is IDualMineContext dualMineContext) && dualMineContext.DualCoin != null)
                        {
                            coinShare = NTMinerContext.Instance.CoinShareSet.GetOrCreate(dualMineContext.DualCoin.GetId());
                            VirtualRoot.RaiseEvent(new ShareChangedEvent(PathId.Empty, coinShare));
                        }
                        AppRoot.GpuSpeedVms.Refresh();
                    }
                });
            }, location: this.GetType());
            #endregion
            #region 周期确保守护进程在运行
            VirtualRoot.BuildEventPath <Per1MinuteEvent>("周期确保守护进程在运行", LogEnum.DevConsole,
                                                         path: message => {
                Daemon.DaemonUtil.RunNTMinerDaemon();
                NoDevFee.NoDevFeeUtil.RunNTMinerNoDevFee();
            }, location: this.GetType());
            #endregion
            #region 开始和停止挖矿后
            VirtualRoot.BuildEventPath <StartingMineEvent>("开始挖矿时更新挖矿按钮状态", LogEnum.DevConsole,
                                                           path: message => {
                AppRoot.MinerProfileVm.IsMining = true;
                // 因为无界面模式不一定会构建挖矿状态按钮,所以放在这里而不放在挖矿按钮的VM中
                StartStopMineButtonViewModel.Instance.MineBtnText = "正在挖矿";
            }, location: this.GetType());
            VirtualRoot.BuildEventPath <MineStartedEvent>("启动1080ti小药丸、启动DevConsole? 更新挖矿按钮状态", LogEnum.DevConsole,
                                                          path: message => {
                // 启动DevConsole
                if (NTMinerContext.IsUseDevConsole)
                {
                    var mineContext     = message.MineContext;
                    string poolIp       = mineContext.MainCoinPool.GetIp();
                    string consoleTitle = mineContext.MainCoinPool.Server;
                    Daemon.DaemonUtil.RunDevConsoleAsync(poolIp, consoleTitle);
                }
            }, location: this.GetType());
            VirtualRoot.BuildEventPath <MineStopedEvent>("停止挖矿后停止1080ti小药丸 挖矿停止后更新界面挖矿状态", LogEnum.DevConsole,
                                                         path: message => {
                AppRoot.MinerProfileVm.IsMining = false;
                // 因为无界面模式不一定会构建挖矿状态按钮,所以放在这里而不放在挖矿按钮的VM中
                StartStopMineButtonViewModel.Instance.MineBtnText = "尚未开始";
            }, location: this.GetType());
            #endregion
            #region 处理开启A卡计算模式
            VirtualRoot.BuildCmdPath <SwitchRadeonGpuCommand>(path: message => {
                if (AdlHelper.IsHasATIGpu)
                {
                    AppRoot.SwitchRadeonGpu(message.On);
                }
            }, location: this.GetType());
            #endregion
            #region 处理A卡驱动签名
            VirtualRoot.BuildCmdPath <AtikmdagPatcherCommand>(path: message => {
                if (AdlHelper.IsHasATIGpu)
                {
                    AppRoot.OpenAtikmdagPatcher();
                }
            }, location: this.GetType());
            #endregion
        }
            private CoinKernelViewModels()
            {
                if (WpfUtil.IsInDesignMode)
                {
                    return;
                }
#if DEBUG
                NTStopwatch.Start();
#endif
                VirtualRoot.AddEventPath <ServerContextReInitedEvent>("ServerContext刷新后刷新VM内存", LogEnum.DevConsole,
                                                                      action: message => {
                    _dicById.Clear();
                    Init();
                }, location: this.GetType());
                VirtualRoot.AddEventPath <ServerContextVmsReInitedEvent>("ServerContext的VM集刷新后刷新视图界面", LogEnum.DevConsole,
                                                                         action: message => {
                    OnPropertyChanged(nameof(AllCoinKernels));
                }, location: this.GetType());
                AddEventPath <CoinKernelAddedEvent>("添加了币种内核后刷新VM内存", LogEnum.DevConsole,
                                                    action: (message) => {
                    var coinKernelVm = new CoinKernelViewModel(message.Source);
                    _dicById.Add(message.Source.GetId(), coinKernelVm);
                    OnPropertyChanged(nameof(AllCoinKernels));
                    var kernelVm = coinKernelVm.Kernel;
                    if (kernelVm != null)
                    {
                        kernelVm.OnPropertyChanged(nameof(kernelVm.CoinKernels));
                        kernelVm.OnPropertyChanged(nameof(kernelVm.CoinVms));
                        kernelVm.OnPropertyChanged(nameof(kernelVm.SupportedCoinVms));
                        kernelVm.OnPropertyChanged(nameof(kernelVm.SupportedCoins));
                    }
                    VirtualRoot.RaiseEvent(new CoinKernelVmAddedEvent(message));
                }, location: this.GetType());
                AddEventPath <CoinKernelUpdatedEvent>("更新了币种内核后刷新VM内存", LogEnum.DevConsole,
                                                      action: (message) => {
                    if (_dicById.TryGetValue(message.Source.GetId(), out CoinKernelViewModel vm))
                    {
                        var supportedGpu     = vm.SupportedGpu;
                        Guid dualCoinGroupId = vm.DualCoinGroupId;
                        vm.Update(message.Source);
                        if (supportedGpu != vm.SupportedGpu)
                        {
                            var coinKernels = AllCoinKernels.Where(a => a.KernelId == vm.Id);
                            foreach (var coinKernel in coinKernels)
                            {
                                if (CoinVms.TryGetCoinVm(coinKernel.CoinId, out CoinViewModel coinVm))
                                {
                                    coinVm.OnPropertyChanged(nameof(coinVm.IsSupported));
                                    coinVm.OnPropertyChanged(nameof(coinVm.CoinKernels));
                                }
                            }
                            var kernelVm = vm.Kernel;
                            kernelVm.OnPropertyChanged(nameof(kernelVm.CoinKernels));
                        }
                    }
                }, location: this.GetType());
                AddEventPath <CoinKernelRemovedEvent>("移除了币种内核后刷新VM内存", LogEnum.DevConsole,
                                                      action: (message) => {
                    if (_dicById.TryGetValue(message.Source.GetId(), out CoinKernelViewModel coinKernelVm))
                    {
                        _dicById.Remove(message.Source.GetId());
                        OnPropertyChanged(nameof(AllCoinKernels));
                        var kernelVm = coinKernelVm.Kernel;
                        kernelVm.OnPropertyChanged(nameof(kernelVm.CoinKernels));
                        kernelVm.OnPropertyChanged(nameof(kernelVm.CoinVms));
                        kernelVm.OnPropertyChanged(nameof(kernelVm.SupportedCoinVms));
                        kernelVm.OnPropertyChanged(nameof(kernelVm.SupportedCoins));
                        VirtualRoot.RaiseEvent(new CoinKernelVmRemovedEvent(message));
                    }
                }, location: this.GetType());
                Init();
#if DEBUG
                var elapsedMilliseconds = NTStopwatch.Stop();
                if (elapsedMilliseconds.ElapsedMilliseconds > NTStopwatch.ElapsedMilliseconds)
                {
                    Write.DevTimeSpan($"耗时{elapsedMilliseconds} {this.GetType().Name}.ctor");
                }
#endif
            }
Esempio n. 20
0
            // 创建管道,将输出通过管道转送到日志文件,然后读取日志文件内容打印到控制台
            private static void CreatePipProcess(IMineContext mineContext, string kernelExeFileFullName, string arguments)
            {
                SECURITY_ATTRIBUTES saAttr = new SECURITY_ATTRIBUTES {
                    bInheritHandle       = true,
                    lpSecurityDescriptor = IntPtr.Zero,
                    length = Marshal.SizeOf(typeof(SECURITY_ATTRIBUTES))
                };

                //set the bInheritHandle flag so pipe handles are inherited

                saAttr.lpSecurityDescriptor = IntPtr.Zero;
                //get handle to current stdOut

                IntPtr mypointer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(STARTUPINFO)));

                Marshal.StructureToPtr(saAttr, mypointer, true);
                var bret = CreatePipe(out var hReadOut, out var hWriteOut, mypointer, 0);

                if (!bret)
                {
                    int lasterr = Marshal.GetLastWin32Error();
                    VirtualRoot.RaiseEvent(new StartingMineFailedEvent($"管道型进程创建失败 lasterr:{lasterr.ToString()}"));
                    return;
                }

                const uint STARTF_USESHOWWINDOW  = 0x00000001;
                const uint STARTF_USESTDHANDLES  = 0x00000100;
                const uint NORMAL_PRIORITY_CLASS = 0x00000020;
                //const short SW_SHOW = 5;
                const short SW_HIDE             = 0;
                const int   HANDLE_FLAG_INHERIT = 1;

                //ensure the read handle to pipe for stdout is not inherited
                SetHandleInformation(hReadOut, HANDLE_FLAG_INHERIT, 0);
                ////Create pipe for the child process's STDIN
                STARTUPINFO lpStartupInfo = new STARTUPINFO {
                    cb          = (uint)Marshal.SizeOf(typeof(STARTUPINFO)),
                    dwFlags     = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW,
                    wShowWindow = SW_HIDE, // SW_HIDE; //SW_SHOW
                    hStdOutput  = hWriteOut,
                    hStdError   = hWriteOut,
                    hStdInput   = IntPtr.Zero
                };
                StringBuilder lpEnvironment = new StringBuilder();
                // 复制父进程的环境变量
                IDictionary dic = Environment.GetEnvironmentVariables();

                // 追加环境变量
                foreach (var item in mineContext.CoinKernel.EnvironmentVariables)
                {
                    dic.Add(item.Key, item.Value);
                }
                foreach (var key in dic.Keys)
                {
                    if (key == null || key.ToString().Contains("\0"))
                    {
                        continue;
                    }
                    var value = dic[key];
                    if (value == null || value.ToString().Contains("\0"))
                    {
                        continue;
                    }
                    lpEnvironment.Append($"{key.ToString()}={value.ToString()}\0");
                }
                if (CreateProcess(
                        lpApplicationName: null,
                        lpCommandLine: new StringBuilder($"\"{kernelExeFileFullName}\" {arguments}"),
                        lpProcessAttributes: IntPtr.Zero,
                        lpThreadAttributes: IntPtr.Zero,
                        bInheritHandles: true,
                        dwCreationFlags: NORMAL_PRIORITY_CLASS,
                        lpEnvironment: lpEnvironment,
                        lpCurrentDirectory: Path.GetDirectoryName(kernelExeFileFullName),
                        lpStartupInfo: ref lpStartupInfo,
                        lpProcessInformation: out PROCESS_INFORMATION processInfo))
                {
                    try {
                        mineContext.KernelProcess = Process.GetProcessById((int)processInfo.dwProcessId);
                    }
                    catch {
                        CloseHandle(hReadOut);
                        VirtualRoot.RaiseEvent(new StartingMineFailedEvent($"内核已退出"));
                        return;
                    }
                    IMessagePathId closeHandle = null;
                    KernelProcessDaemon(mineContext, () => {
                        CloseHandle(hWriteOut);
                        VirtualRoot.DeletePath(closeHandle);
                    });
                    closeHandle = VirtualRoot.AddOnecePath <MineStopedEvent>("挖矿停止后关闭非托管的日志句柄", LogEnum.DevConsole,
                                                                             action: message => {
                        ReleaseKernelProcessDaemon(mineContext);
                    }, location: typeof(MinerProcess), pathId: Guid.Empty);

                    Task.Factory.StartNew(() => {
                        using (FileStream fs = new FileStream(mineContext.LogFileFullName, FileMode.OpenOrCreate, FileAccess.ReadWrite)) {
                            const byte r  = (byte)'\r';
                            byte[] buffer = new byte[1024];
                            int ret;
                            // Read会阻塞,直到读取到字符或者hWriteOut被关闭
                            while ((ret = Read(buffer, 0, buffer.Length, hReadOut)) > 0)
                            {
                                byte[] data = new byte[ret];
                                int n       = 0;
                                for (int i = 0; i < ret; i++)
                                {
                                    if (buffer[i] != r)
                                    {
                                        data[n] = buffer[i];
                                        n++;
                                    }
                                }
                                fs.Write(data, 0, n);
                                fs.Flush();
                            }
                        }
                        CloseHandle(hReadOut);
                    }, TaskCreationOptions.LongRunning);
                    ReadPrintLoopLogFileAsync(mineContext, isWriteToConsole: true);
                }
Esempio n. 21
0
        static void Main()
        {
            VirtualRoot.SetOut(new ConsoleOut());
            NTMinerConsole.MainUiOk();
            NTMinerConsole.DisbleQuickEditMode();
            DevMode.SetDevMode();

            Windows.ConsoleHandler.Register(Exit);

            string thisServerAddress = ServerRoot.HostConfig.ThisServerAddress;

            Console.Title = $"{nameof(ServerAppType.WsServer)}_{thisServerAddress}";
            // 用本节点的地址作为队列名,消费消息时根据路由键区分消息类型
            string queue        = $"{nameof(ServerAppType.WsServer)}.{thisServerAddress}";
            string durableQueue = queue + MqKeyword.DurableQueueEndsWith;

            AbstractMqMessagePath[] mqMessagePaths = new AbstractMqMessagePath[] {
                new ReadOnlyUserMqMessagePath(durableQueue),
                new CalcConfigMqMessagePath(queue),
                new MinerSignMqMessagePath(queue),
                new WsServerNodeMqMessagePath(queue),
                new OperationMqMessagePath(queue),
                new MinerClientMqMessagePath(queue, thisServerAddress),
                new ClientTestIdMqMessagePath(queue)
            };
            if (!MqRedis.Create(ServerAppType.WsServer, mqMessagePaths, out IMqRedis mqRedis))
            {
                NTMinerConsole.UserError("启动失败,无法继续,因为服务器上下文创建失败");
                return;
            }
            IRedis redis = mqRedis;
            IMq    mq    = mqRedis;

            MinerClientMqSender    = new MinerClientMqSender(mq);
            SpeedDataRedis         = new SpeedDataRedis(redis);
            WsServerNodeRedis      = new WsServerNodeRedis(redis);
            OperationMqSender      = new OperationMqSender(mq);
            UserMqSender           = new UserMqSender(mq);
            _wsServerNodeMqSender  = new WsServerNodeMqSender(mq);
            WsServerNodeAddressSet = new WsServerNodeAddressSet(WsServerNodeRedis, _wsServerNodeMqSender);
            var minerRedis      = new MinerDataRedis(redis);
            var userRedis       = new ReadOnlyUserDataRedis(redis);
            var calcConfigRedis = new CalcConfigDataRedis(redis);

            VirtualRoot.StartTimer();
            // 构造函数中异步访问redis初始化用户列表,因为是异步的所以提前构造
            UserSet               = new ReadOnlyUserSet(userRedis);
            MinerSignSet          = new MinerSignSet(minerRedis);
            _wsServer             = new SharpWsServerAdapter(ServerRoot.HostConfig);
            CalcConfigSet         = new ReadOnlyCalcConfigSet(calcConfigRedis);
            MinerClientSessionSet = new MinerClientSessionSet(_wsServer.MinerClientWsSessions);
            MinerStudioSessionSet = new MinerStudioSessionSet(_wsServer.MinerStudioWsSessions);
            _started              = _wsServer.Start();
            if (!_started)
            {
                NTMinerConsole.UserError("启动失败,无法继续,因为_wsServer启动失败");
                return;
            }
            VirtualRoot.RaiseEvent(new WebSocketServerStatedEvent());

            Console.ReadKey(true);
            Exit();
        }
Esempio n. 22
0
            private CoinViewModels()
            {
#if DEBUG
                NTStopwatch.Start();
#endif
                if (WpfUtil.IsInDesignMode)
                {
                    return;
                }
                VirtualRoot.AddEventPath <ServerContextReInitedEvent>("ServerContext刷新后刷新VM内存", LogEnum.DevConsole,
                                                                      action: message => {
                    _dicById.Clear();
                    Init();
                }, location: this.GetType());
                VirtualRoot.AddEventPath <ServerContextVmsReInitedEvent>("ServerContext的VM集刷新后刷新视图界面", LogEnum.DevConsole,
                                                                         action: message => {
                    AllPropertyChanged();
                }, location: this.GetType());
                AddEventPath <CoinAddedEvent>("添加了币种后刷新VM内存", LogEnum.DevConsole,
                                              action: (message) => {
                    _dicById.Add(message.Source.GetId(), new CoinViewModel(message.Source));
                    AllPropertyChanged();
                    VirtualRoot.RaiseEvent(new CoinVmAddedEvent(message));
                }, location: this.GetType());
                AddEventPath <CoinRemovedEvent>("移除了币种后刷新VM内存", LogEnum.DevConsole,
                                                action: message => {
                    _dicById.Remove(message.Source.GetId());
                    AllPropertyChanged();
                    VirtualRoot.RaiseEvent(new CoinVmRemovedEvent(message));
                }, location: this.GetType());
                AddEventPath <CoinKernelVmAddedEvent>("币种内核Vm集添加了新Vm后刷新币种Vm集的关联内存", LogEnum.DevConsole, action: message => {
                    if (_dicById.TryGetValue(message.Event.Source.CoinId, out CoinViewModel coinVm))
                    {
                        coinVm.OnPropertyChanged(nameof(CoinViewModel.CoinKernel));
                        coinVm.OnPropertyChanged(nameof(CoinViewModel.CoinKernels));
                        coinVm.OnPropertyChanged(nameof(CoinViewModel.IsSupported));
                    }
                }, this.GetType());
                AddEventPath <CoinKernelVmRemovedEvent>("币种内核Vm集删除了新Vm后刷新币种Vm集的关联内存", LogEnum.DevConsole, action: message => {
                    if (_dicById.TryGetValue(message.Event.Source.CoinId, out CoinViewModel coinVm))
                    {
                        coinVm.OnPropertyChanged(nameof(CoinViewModel.CoinKernel));
                        coinVm.OnPropertyChanged(nameof(CoinViewModel.CoinKernels));
                        coinVm.OnPropertyChanged(nameof(CoinViewModel.IsSupported));
                    }
                }, this.GetType());
                AddEventPath <CoinUpdatedEvent>("更新了币种后刷新VM内存", LogEnum.DevConsole,
                                                action: message => {
                    if (_dicById.TryGetValue(message.Source.GetId(), out CoinViewModel vm))
                    {
                        bool justAsDualCoin = vm.JustAsDualCoin;
                        vm.Update(message.Source);
                        vm.TestWalletVm.Address = message.Source.TestWallet;
                        vm.OnPropertyChanged(nameof(vm.Wallets));
                        vm.OnPropertyChanged(nameof(vm.WalletItems));
                        if (MinerProfileVm.CoinId == message.Source.GetId())
                        {
                            MinerProfileVm.OnPropertyChanged(nameof(MinerProfileVm.CoinVm));
                        }
                        CoinKernelViewModel coinKernelVm = MinerProfileVm.CoinVm.CoinKernel;
                        if (coinKernelVm != null &&
                            coinKernelVm.CoinKernelProfile.SelectedDualCoin != null &&
                            coinKernelVm.CoinKernelProfile.SelectedDualCoin.GetId() == message.Source.GetId())
                        {
                            coinKernelVm.CoinKernelProfile.OnPropertyChanged(nameof(coinKernelVm.CoinKernelProfile.SelectedDualCoin));
                        }
                        if (justAsDualCoin != vm.JustAsDualCoin)
                        {
                            OnPropertyChanged(nameof(MainCoins));
                        }
                    }
                }, location: this.GetType());
                AddEventPath <CoinIconDownloadedEvent>("下载了币种图标后", LogEnum.DevConsole,
                                                       action: message => {
                    try {
                        if (string.IsNullOrEmpty(message.Source.Icon))
                        {
                            return;
                        }
                        string iconFileFullName = TempPath.GetIconFileFullName(message.Source.Icon);
                        if (string.IsNullOrEmpty(iconFileFullName) || !File.Exists(iconFileFullName))
                        {
                            return;
                        }
                        if (_dicById.TryGetValue(message.Source.GetId(), out CoinViewModel coinVm))
                        {
                            try {
                                coinVm.IconImageSource = new Uri(iconFileFullName, UriKind.Absolute).ToString();
                            }
                            catch (Exception e) {
                                File.Delete(iconFileFullName);
                                Logger.ErrorDebugLine(e);
                            }
                        }
                    }
                    catch (Exception e) {
                        Logger.ErrorDebugLine(e);
                    }
                }, location: this.GetType());
                Init();
#if DEBUG
                var elapsedMilliseconds = NTStopwatch.Stop();
                if (elapsedMilliseconds.ElapsedMilliseconds > NTStopwatch.ElapsedMilliseconds)
                {
                    Write.DevTimeSpan($"耗时{elapsedMilliseconds} {this.GetType().Name}.ctor");
                }
#endif
            }
Esempio n. 23
0
 private CoinViewModels()
 {
     if (WpfUtil.IsInDesignMode)
     {
         return;
     }
     VirtualRoot.BuildEventPath <ServerContextReInitedEvent>("刷新VM内存", LogEnum.DevConsole,
                                                             path: message => {
         _dicById.Clear();
         Init();
     }, location: this.GetType());
     VirtualRoot.BuildEventPath <ServerContextReInitedEventHandledEvent>("刷新视图界面", LogEnum.DevConsole,
                                                                         path: message => {
         AllPropertyChanged();
     }, location: this.GetType());
     BuildEventPath <CoinAddedEvent>("刷新VM内存", LogEnum.DevConsole,
                                     path: (message) => {
         _dicById.Add(message.Source.GetId(), new CoinViewModel(message.Source));
         AllPropertyChanged();
         VirtualRoot.RaiseEvent(new CoinVmAddedEvent(message));
     }, location: this.GetType());
     BuildEventPath <CoinRemovedEvent>("刷新VM内存", LogEnum.DevConsole,
                                       path: message => {
         _dicById.Remove(message.Source.GetId());
         AllPropertyChanged();
         VirtualRoot.RaiseEvent(new CoinVmRemovedEvent(message));
     }, location: this.GetType());
     BuildEventPath <CoinKernelVmAddedEvent>("刷新币种Vm集的关联内存", LogEnum.DevConsole, path: message => {
         if (_dicById.TryGetValue(message.Event.Source.CoinId, out CoinViewModel coinVm))
         {
             coinVm.OnPropertyChanged(nameof(CoinViewModel.CoinKernel));
             coinVm.OnPropertyChanged(nameof(CoinViewModel.CoinKernels));
             coinVm.OnPropertyChanged(nameof(CoinViewModel.IsSupported));
         }
     }, this.GetType());
     BuildEventPath <CoinKernelVmRemovedEvent>("刷新币种Vm集的关联内存", LogEnum.DevConsole, path: message => {
         if (_dicById.TryGetValue(message.Event.Source.CoinId, out CoinViewModel coinVm))
         {
             coinVm.OnPropertyChanged(nameof(CoinViewModel.CoinKernel));
             coinVm.OnPropertyChanged(nameof(CoinViewModel.CoinKernels));
             coinVm.OnPropertyChanged(nameof(CoinViewModel.IsSupported));
         }
     }, this.GetType());
     BuildEventPath <CoinUpdatedEvent>("刷新VM内存", LogEnum.DevConsole,
                                       path: message => {
         if (_dicById.TryGetValue(message.Source.GetId(), out CoinViewModel vm))
         {
             bool justAsDualCoin = vm.JustAsDualCoin;
             vm.Update(message.Source);
             vm.TestWalletVm.Address = message.Source.TestWallet;
             vm.OnPropertyChanged(nameof(vm.Wallets));
             vm.OnPropertyChanged(nameof(vm.WalletItems));
             if (MinerProfileVm.CoinId == message.Source.GetId())
             {
                 MinerProfileVm.OnPropertyChanged(nameof(MinerProfileVm.CoinVm));
             }
             CoinKernelViewModel coinKernelVm = MinerProfileVm.CoinVm.CoinKernel;
             if (coinKernelVm != null &&
                 coinKernelVm.CoinKernelProfile.SelectedDualCoin != null &&
                 coinKernelVm.CoinKernelProfile.SelectedDualCoin.GetId() == message.Source.GetId())
             {
                 coinKernelVm.CoinKernelProfile.OnPropertyChanged(nameof(coinKernelVm.CoinKernelProfile.SelectedDualCoin));
             }
             if (justAsDualCoin != vm.JustAsDualCoin)
             {
                 OnPropertyChanged(nameof(MainCoins));
             }
         }
     }, location: this.GetType());
     BuildEventPath <CoinIconDownloadedEvent>("刷新图标", LogEnum.DevConsole,
                                              path: message => {
         try {
             if (string.IsNullOrEmpty(message.Source.Icon))
             {
                 return;
             }
             string iconFileFullName = MinerClientTempPath.GetIconFileFullName(message.Source.Icon);
             if (string.IsNullOrEmpty(iconFileFullName) || !File.Exists(iconFileFullName))
             {
                 return;
             }
             if (_dicById.TryGetValue(message.Source.GetId(), out CoinViewModel coinVm))
             {
                 try {
                     coinVm.IconImageSource = new Uri(iconFileFullName, UriKind.Absolute).ToString();
                 }
                 catch (Exception e) {
                     File.Delete(iconFileFullName);
                     Logger.ErrorDebugLine(e);
                 }
             }
         }
         catch (Exception e) {
             Logger.ErrorDebugLine(e);
         }
     }, location: this.GetType());
     Init();
 }