/// <summary> /// Sends a message depending on the test's state. /// </summary> /// <param name="message">The message sent by the user.</param> public async void OnMessageReceived(Message message) { if (TestMode) { Evaluate(message); } else if (message.Text.StartsWith("/test")) { TestMode = true; Controller = new MainController(new MainModel(), this); Controller.Start(); CurrentStep = Controller.CurrentStep; Evaluate(message); } else if (message.Text.StartsWith("/about")) { // TODO Add /about message to explain this research. var help = "Este bot foi implementado para a condução de uma pesquisa " + "do Laboratório de Neurociência e Comportamento da Universidade " + "de Brasília. Esclarecer quaisquer dúvidas mandando e-mail para " + "Cristiano Silva Jr. <*****@*****.**>."; await Bot.SendTextMessageAsync(message.Chat.Id, help, replyMarkup : new ReplyKeyboardHide()); } else { var usage = @"Uso: /test - Começar um novo teste. /about - Mostra informações sobre o Bot e sobre a pesquisa sendo realizada. "; await Bot.SendTextMessageAsync(message.Chat.Id, usage, replyMarkup : new ReplyKeyboardHide()); } }
private static void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { try { if (MainController != null) { MainController.Start(); Logging.Info("controller started"); } } catch (Exception ex) { Logging.LogUsefulException(ex); } finally { try { System.Timers.Timer timer = (System.Timers.Timer)sender; timer.Enabled = false; timer.Stop(); timer.Dispose(); } catch (Exception ex) { Logging.LogUsefulException(ex); } } }
// ReSharper disable InconsistentNaming private static void Main(string[] args) // ReSharper restore InconsistentNaming { Arguments commandLine = new Arguments(args); bool owned; Mutex mutex = new Mutex(true, "HotBabe_" + Assembly.GetExecutingAssembly().FullName, out owned); if (!owned) { return; } GC.KeepAlive(mutex); ZipHelper.Register(); ResourceHelper.Register(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); sSettingsManager = string.IsNullOrEmpty(commandLine.ConfigFilePath) ? new XmlSettingsManager() : new XmlSettingsManager(commandLine.ConfigFilePath); MainView view = new MainView { DebugEnabled = commandLine.Debug }; sMainController = new MainController(view, sSettingsManager); sMainController.EditSettings += controllerEditSettings; sMainController.Start(); }
//private void _dispatcherTimer_Tick(object sender, object e) //{ // //_mainViewModel.BrewKettleViewModel.MashTemperature = _vessel.GetMashTemperature(); // //_mainViewModel.BrewKettleViewModel.VesselTemperature = _vessel.GetVesselTemperature(); //} //string _logfilePath; private async void btnStartClick(object sender, RoutedEventArgs e) { var vm = new BrewerViewModel(); vm.Brewers = Brewer.Loader.Load(); vm.SelectedBrewer = vm.Brewers[0]; var dialog = new StartProgram(); dialog.DataContext = vm; await dialog.ShowAsync(); // Show Dialog if (dialog.BrewerSelected) { _mainController.Start(vm.SelectedBrewer.Name); _mainViewModel.InfoBoxViewModel.BrewerName = vm.SelectedBrewer.Name; _mainViewModel.ExpectedFinish = new TimeSpan(0, 0, 0); _mainViewModel.StepCountDown = new TimeSpan(0, 0, 0); _mainViewModel.StepTemperature = 0.0; _mainViewModel.ProcessIsRunning = true; //_logfilePath = ""; } }
private static void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e) { switch (e.Mode) { case PowerModes.Resume: logger.Info("os wake up"); if (MainController != null) { System.Threading.Tasks.Task.Factory.StartNew(() => { Thread.Sleep(10 * 1000); try { MainController.Start(false); logger.Info("controller started"); } catch (Exception ex) { logger.LogUsefulException(ex); } }); } break; case PowerModes.Suspend: if (MainController != null) { MainController.Stop(); logger.Info("controller stopped"); } logger.Info("os suspend"); break; } }
private void buttonStart_Click(object sender, EventArgs e) { if (stopped) { int port; if (int.TryParse(textBoxPort.Text, out port)) { stopped = false; buttonStart.Text = "Stop"; chartTimer.Enabled = true; Settings.Default.LastCom = textBoxPort.Text; controller.Start(port); } else { MessageBox.Show("Please enter valid port.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } } else { stopped = true; buttonStart.Text = "Start"; chartTimer.Enabled = false; controller.Stop(); } }
public static void Main(string[] args) { Application.Initialize (); MainController mainController = new MainController (args); mainController.Start (); mainController.AllWidgetsAreClosed += HandleAllWidgetsAreClosed; Application.Run (); }
private void OnStartup(object sender, StartupEventArgs e) { var mainController = new MainController(); mainController.Start(); Dispatcher.UnhandledException += OnException; }
private async Task ControlFun() { Configuration.Save(); if (State == State.Waiting || State == State.Stopped) { // 服务器、模式 需选择 if (!(ServerComboBox.SelectedItem is Server server)) { MessageBoxX.Show(i18N.Translate("Please select a server first")); return; } if (!(ModeComboBox.SelectedItem is Models.Mode mode)) { MessageBoxX.Show(i18N.Translate("Please select a mode first")); return; } // 清除模式搜索框文本选择 ModeComboBox.Select(0, 0); State = State.Starting; if (await MainController.Start(server, mode)) { State = State.Started; _ = Task.Run(() => { Bandwidth.NetTraffic(); }); // 如果勾选启动后最小化 if (Global.Settings.MinimizeWhenStarted) { WindowState = FormWindowState.Minimized; if (_isFirstCloseWindow) { // 显示提示语 NotifyTip(i18N.Translate("Netch is now minimized to the notification bar, double click this icon to restore.")); _isFirstCloseWindow = false; } Hide(); } } else { State = State.Stopped; StatusText(i18N.Translate("Start failed")); } } else { // 停止 State = State.Stopping; await MainController.Stop(); State = State.Stopped; } }
public void Start_CreatesNewLinkData_SetsToView() { ILinkerView view = MockRepository.GenerateMock <ILinkerView>(); MainController controller = new MainController(view, null, null, null, null); controller.Start(); view.AssertWasCalled(v => v.SetOperationData(Arg <LinkOperationData> .Is.NotNull)); }
private async void UpdateACL(bool useProxy) { void DisableItems(bool v) { UpdateACLToolStripMenuItem.Enabled = updateACLWithProxyToolStripMenuItem.Enabled = v; } if (useProxy && ServerComboBox.SelectedIndex == -1) { MessageBoxX.Show(i18N.Translate("Please select a server first")); return; } DisableItems(false); NotifyTip(i18N.Translate("Updating in the background")); try { if (useProxy) { var mode = new Models.Mode { Remark = "ProxyUpdate", Type = 5 }; State = State.Starting; await MainController.Start(ServerComboBox.SelectedItem as Models.Server, mode); } var req = WebUtil.CreateRequest(Global.Settings.ACL); if (useProxy) { req.Proxy = new WebProxy($"http://127.0.0.1:{Global.Settings.HTTPLocalPort}"); } await WebUtil.DownloadFileAsync(req, Path.Combine(Global.NetchDir, "bin\\default.acl")); NotifyTip(i18N.Translate("ACL updated successfully")); } catch (Exception e) { NotifyTip(i18N.Translate("ACL update failed") + "\n" + e.Message, info: false); Logging.Error("更新 ACL 失败!" + e); } finally { if (useProxy) { await MainController.Stop(); State = State.Stopped; } DisableItems(true); } }
static void Main(string[] args) { var inputSerivce = new InputService(); var outputService = new OutputService(); var ioService = new IOService(inputSerivce, outputService); var mainController = new MainController(ioService, outputService); mainController.Start(); }
static void Main(string[] args) { var player = new Player(); var game = new Game(new AllAvailableCategoriesStrategy()); var diceView = new DiceView(game.GetDice()); var view = new EnglishMainView(diceView); var controller = new MainController(view, player, game); controller.Start(); }
public void Start_RegisterValidatorPassedIn_ViewValidationDelegateIsRegistered() { ILinkerView view = MockRepository.GenerateMock <ILinkerView>(); IPathValidation validator = MockRepository.GenerateMock <IPathValidation>(); MainController controller = new MainController(view, validator, null, null, null); controller.Start(); view.AssertWasCalled(v => v.ValidatePath += Arg <PathValidater> .Is.NotNull); }
public void WhenRunningStartViewGetUsernameIsCalled() { var mockView = new Mock <MainView>(); var mockPlayer = new Mock <Player>(); var mockCategory = new Mock <AvailableCategoriesStrategy>(); var mockGame = new Mock <Game>(mockCategory.Object); mockView.Setup(view => view.GetUsername()).Returns("test"); var c = new MainController(mockView.Object, mockPlayer.Object, mockGame.Object); c.Start(); mockView.Verify(view => view.GetUsername(), Times.Once()); }
static void Main(string[] args) { List <ITask> tasks = new List <ITask>() { new Individual() }; IInputService inputService = new InputService(); IOutputService outputService = new OutputService(); MainController mainController = new MainController(inputService, outputService, tasks); mainController.Start(); }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); MainController mc = new MainController(); mc.Start(); //ApplicationContext applicationContext = new ApplicationContext(); //Application.Run(); }
private void updateACLWithProxyToolStripMenuItem_Click(object sender, EventArgs e) { updateACLWithProxyToolStripMenuItem.Enabled = false; // 当前 ServerComboBox 中至少有一项 if (ServerComboBox.SelectedIndex == -1) { MessageBoxX.Show(i18N.Translate("Please select a server first")); return; } MenuStrip.Enabled = ConfigurationGroupBox.Enabled = ControlButton.Enabled = SettingsButton.Enabled = false; ControlButton.Text = "..."; Task.Run(() => { var mode = new Models.Mode { Remark = "ProxyUpdate", Type = 5 }; _mainController = new MainController(); _mainController.Start(ServerComboBox.SelectedItem as Models.Server, mode); using var client = new WebClient(); client.Proxy = new WebProxy($"http://127.0.0.1:{Global.Settings.HTTPLocalPort}"); StatusText(i18N.Translate("Updating in the background")); try { client.DownloadFile(Global.Settings.ACL, "bin\\default.acl"); NotifyIcon.ShowBalloonTip(5, UpdateChecker.Name, i18N.Translate("ACL updated successfully"), ToolTipIcon.Info); } catch (Exception e) { Logging.Error("使用代理更新 ACL 失败!" + e); MessageBoxX.Show(i18N.Translate("ACL update failed") + "\n" + e); } finally { State = State.Waiting; _mainController.Stop(); } }); }
public void WhenRunningStartViewUserNameIsSetInPlayer() { var mockView = new Mock <MainView>(); var player = new Player(); var mockCategory = new Mock <AvailableCategoriesStrategy>(); var mockGame = new Mock <Game>(mockCategory.Object); var c = new MainController(mockView.Object, player, mockGame.Object); string expected = "Test"; mockView.Setup(v => v.GetUsername()).Returns(expected); c.Start(); Assert.Equal(expected, player.GetName()); }
public override void Resume() { if (EnergyCounter == 0) { MainController.Start(new AIGame(CurrentLevel.Id + 1, Score, Lives, MainController)); } else if (Timer != 0) { base.Resume(); } else { Restart(); } }
static void Main(string[] args) { List <ITask> tasks = new List <ITask> { new TaskA(), new TaskB(), new TaskC(), new TaskD(), new TaskE() }; IInputService inputService = new InputService(); IOutputService outputService = new OutputService(); MainController mainController = new MainController(inputService, outputService, tasks); mainController.Start(); }
static void Main() { string dataDir; #if DEBUG dataDir = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"..\..")); #else dataDir = AppDomain.CurrentDomain.BaseDirectory; #endif AppDomain.CurrentDomain.SetData("DataDirectory", dataDir); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); IShopModel shopModel = new ShopModel(new ShopDBFactory()); MainController mainController = new MainController(shopModel); IBaseController registerContoller = new RegisterController(shopModel, new RegisterForm("RegisterForm")); IBaseController loginController = new LoginController(shopModel, new LoginForm("LoginForm")); IBaseController shopProductsContoller = new ShopProductsController(shopModel, new ShopProductsMainForm("ShopProductsForm")); IBaseController selectController = new SelectController(shopModel, new SelectControl("SelectControl")); IBaseController insertController = new InsertController(shopModel, new InsertControl("InsertControl")); IBaseController updateController = new UpdateController(shopModel, new UpdateControl("UpdateControl")); IBaseController deleteController = new DeleteController(shopModel, new DeleteControl("DeleteControl")); IBaseController cartController = new CartController(shopModel, new CartControl("CartControl")); mainController.AddControler(registerContoller); mainController.AddControler(loginController); mainController.AddControler(shopProductsContoller); ((ShopProductsController)shopProductsContoller).AddPage(selectController, "Все товары"); ((ShopProductsController)shopProductsContoller).AddPage(insertController, "Добавление"); ((ShopProductsController)shopProductsContoller).AddPage(updateController, "Изменение"); ((ShopProductsController)shopProductsContoller).AddPage(deleteController, "Удаление"); ((ShopProductsController)shopProductsContoller).AddPage(cartController, "Корзина"); mainController.Start(loginController); Application.Run(); }
static void Main() { Directory.SetCurrentDirectory(Application.StartupPath); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); if (!Logging.OpenLogFile()) { MessageBox.Show(string.Format(I18N.GetString("Can't access the file '{0}', it is maybe used by another process."), Logging.LogFilePath), I18N.GetString("Error"), MessageBoxButtons.OK, MessageBoxIcon.Warning); } controller = new MainController(); MenuViewController viewController = new MenuViewController(controller); controller.Start(); Application.ApplicationExit += Application_ApplicationExit; SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged; Application.Run(); }
static void Main() { Directory.SetCurrentDirectory(Application.StartupPath); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); if (!Logging.OpenLogFile()) { MessageBox.Show($"Can't access the file '{Logging.LogFilePath}', it is maybe used by another process.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); } controller = new MainController(); MenuViewController viewController = new MenuViewController(controller); controller.Start(); Application.ApplicationExit += Application_ApplicationExit; Application.Run(); }
private void StartToolStripButton_Click(object sender, EventArgs e) { mainController.Start(); }
private void ControlButton_Click(object sender, EventArgs e) { if (State == Models.State.Waiting || State == Models.State.Stopped) { // 当前 ServerComboBox 中至少有一项 if (ServerComboBox.SelectedIndex == -1) { MessageBox.Show(Utils.i18N.Translate("Please select a server first"), Utils.i18N.Translate("Information"), MessageBoxButtons.OK, MessageBoxIcon.Information); return; } // 当前 ModeComboBox 中至少有一项 if (ModeComboBox.SelectedIndex == -1) { MessageBox.Show(Utils.i18N.Translate("Please select an mode first"), Utils.i18N.Translate("Information"), MessageBoxButtons.OK, MessageBoxIcon.Information); return; } MenuStrip.Enabled = ConfigurationGroupBox.Enabled = ControlButton.Enabled = SettingsButton.Enabled = false; ControlButton.Text = "..."; StatusLabel.Text = $"{Utils.i18N.Translate("Status")}{Utils.i18N.Translate(": ")}{Utils.i18N.Translate("Starting")}"; State = Models.State.Starting; Task.Run(() => { var server = ServerComboBox.SelectedItem as Models.Server; var mode = ModeComboBox.SelectedItem as Models.Mode; MainController = new MainController(); if (MainController.Start(server, mode)) { //if (mode.Type == 0) if (false) { UsedBandwidthLabel.Visible = UploadSpeedLabel.Visible = DownloadSpeedLabel.Visible = true; MainController.pNFController.OnBandwidthUpdated += OnBandwidthUpdated; } ControlButton.Enabled = true; ControlButton.Text = Utils.i18N.Translate("Stop"); if (mode.Type != 3 && mode.Type != 5) { if (server.Type != "Socks5") { if (Global.Settings.LocalAddress == "0.0.0.0") { StatusLabel.Text = $"{Utils.i18N.Translate("Status")}{Utils.i18N.Translate(": ")}{Utils.i18N.Translate("Started")} ({Utils.i18N.Translate("Allow other Devices to connect")} Socks5 {Utils.i18N.Translate("Local Port")}{Utils.i18N.Translate(": ")}{Global.Settings.Socks5LocalPort})"; } else { StatusLabel.Text = $"{Utils.i18N.Translate("Status")}{Utils.i18N.Translate(": ")}{Utils.i18N.Translate("Started")} (Socks5 {Utils.i18N.Translate("Local Port")}{Utils.i18N.Translate(": ")}{Global.Settings.Socks5LocalPort}{")"}"; } } else { StatusLabel.Text = $"{Utils.i18N.Translate("Status")}{Utils.i18N.Translate(": ")}{Utils.i18N.Translate("Started")}"; } } else { if (server.Type != "Socks5") { if (Global.Settings.LocalAddress == "0.0.0.0") { StatusLabel.Text = $"{Utils.i18N.Translate("Status")}{Utils.i18N.Translate(": ")}{Utils.i18N.Translate("Started")} ({Utils.i18N.Translate("Allow other Devices to connect")} Socks5 {Utils.i18N.Translate("Local Port")}{Utils.i18N.Translate(": ")}{Global.Settings.Socks5LocalPort} | HTTP {Utils.i18N.Translate("Local Port")}{Utils.i18N.Translate(": ")}{Global.Settings.HTTPLocalPort}{")"}"; } else { StatusLabel.Text = $"{Utils.i18N.Translate("Status")}{Utils.i18N.Translate(": ")}{Utils.i18N.Translate("Started")} (Socks5 {Utils.i18N.Translate("Local Port")}{Utils.i18N.Translate(": ")}{Global.Settings.Socks5LocalPort} | HTTP {Utils.i18N.Translate("Local Port")}{Utils.i18N.Translate(": ")}{Global.Settings.HTTPLocalPort})"; } } else { if (Global.Settings.LocalAddress == "0.0.0.0") { StatusLabel.Text = $"{Utils.i18N.Translate("Status")}{Utils.i18N.Translate(": ")}{Utils.i18N.Translate("Started")} ({Utils.i18N.Translate("Allow other Devices to connect")} HTTP {Utils.i18N.Translate("Local Port")}{Utils.i18N.Translate(": ")}{Global.Settings.HTTPLocalPort}{")"}"; } else { StatusLabel.Text = $"{Utils.i18N.Translate("Status")}{Utils.i18N.Translate(": ")}{Utils.i18N.Translate("Started")} (HTTP {Utils.i18N.Translate("Local Port")}{Utils.i18N.Translate(": ")}{Global.Settings.HTTPLocalPort})"; } } } State = Models.State.Started; } else { MenuStrip.Enabled = ConfigurationGroupBox.Enabled = ControlButton.Enabled = SettingsButton.Enabled = true; ControlButton.Text = Utils.i18N.Translate("Start"); StatusLabel.Text = $"{Utils.i18N.Translate("Status")}{Utils.i18N.Translate(": ")}{Utils.i18N.Translate("Start failed")}"; State = Models.State.Stopped; } }); } else { ControlButton.Enabled = false; ControlButton.Text = "..."; StatusLabel.Text = $"{Utils.i18N.Translate("Status")}{Utils.i18N.Translate(": ")}{Utils.i18N.Translate("Stopping")}"; State = Models.State.Stopping; MenuStrip.Enabled = ConfigurationGroupBox.Enabled = SettingsButton.Enabled = true; ProfileGroupBox.Enabled = false; Task.Run(() => { var server = ServerComboBox.SelectedItem as Models.Server; var mode = ModeComboBox.SelectedItem as Models.Mode; MainController.Stop(); //if (mode.Type == 0) if (false) { LastUploadBandwidth = 0; LastDownloadBandwidth = 0; UploadSpeedLabel.Text = "↑: 0 KB/s"; DownloadSpeedLabel.Text = "↓: 0 KB/s"; UsedBandwidthLabel.Text = $"{Utils.i18N.Translate("Used")}{Utils.i18N.Translate(": ")}0 KB"; UsedBandwidthLabel.Visible = UploadSpeedLabel.Visible = DownloadSpeedLabel.Visible = false; } ControlButton.Enabled = true; ProfileGroupBox.Enabled = true; ControlButton.Text = Utils.i18N.Translate("Start"); StatusLabel.Text = $"{Utils.i18N.Translate("Status")}{Utils.i18N.Translate(": ")}{Utils.i18N.Translate("Stopped")}"; State = Models.State.Stopped; TestServer(); }); } }
private void UpdateServersFromSubscribeLinksToolStripMenuItem_Click(object sender, EventArgs e) { if (Global.Settings.UseProxyToUpdateSubscription) { // 当前 ServerComboBox 中至少有一项 if (ServerComboBox.SelectedIndex == -1) { MessageBox.Show(Utils.i18N.Translate("Please select a server first"), Utils.i18N.Translate("Information"), MessageBoxButtons.OK, MessageBoxIcon.Information); return; } MenuStrip.Enabled = ConfigurationGroupBox.Enabled = ControlButton.Enabled = SettingsButton.Enabled = false; ControlButton.Text = "..."; } if (Global.Settings.SubscribeLink.Count > 0) { DeletePictureBox.Enabled = false; Task.Run(() => { if (Global.Settings.UseProxyToUpdateSubscription) { var mode = new Models.Mode() { Remark = "ProxyUpdate", Type = 5 }; MainController = new MainController(); MainController.Start(ServerComboBox.SelectedItem as Models.Server, mode); } foreach (var item in Global.Settings.SubscribeLink) { using (var client = new Override.WebClient()) { try { if (!String.IsNullOrEmpty(item.UserAgent)) { client.Headers.Add("User-Agent", item.UserAgent); } else { client.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36"); } if (Global.Settings.UseProxyToUpdateSubscription) { client.Proxy = new System.Net.WebProxy($"http://127.0.0.1:{Global.Settings.HTTPLocalPort}"); } var response = client.DownloadString(item.Link); try { response = Utils.ShareLink.URLSafeBase64Decode(response); } catch (Exception) { // 跳过 } var list = new List <Models.Server>(); foreach (var server in Global.Settings.Server) { if (server.Group != item.Remark) { list.Add(server); } } Global.Settings.Server = list; using (var sr = new StringReader(response)) { string text; while ((text = sr.ReadLine()) != null) { var result = Utils.ShareLink.Parse(text); if (result != null) { foreach (var x in result) { x.Group = item.Remark; } Global.Settings.Server.AddRange(result); } } } } catch (Exception) { continue; } } } InitServer(); DeletePictureBox.Enabled = true; if (Global.Settings.UseProxyToUpdateSubscription) { MenuStrip.Enabled = ConfigurationGroupBox.Enabled = ControlButton.Enabled = SettingsButton.Enabled = true; ControlButton.Text = Utils.i18N.Translate("Start"); MainController.Stop(); } MessageBox.Show(this, Utils.i18N.Translate("Update completed"), Utils.i18N.Translate("Information"), MessageBoxButtons.OK, MessageBoxIcon.Information); Utils.Configuration.Save(); }); MessageBox.Show(Utils.i18N.Translate("Updating in the background"), Utils.i18N.Translate("Information"), MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show(Utils.i18N.Translate("No subscription link"), Utils.i18N.Translate("Information"), MessageBoxButtons.OK, MessageBoxIcon.Information); } }
public void ControlFun() { SaveConfigs(); if (State == State.Waiting || State == State.Stopped) { // 服务器、模式 需选择 if (ServerComboBox.SelectedIndex == -1) { MessageBoxX.Show(i18N.Translate("Please select a server first")); return; } if (ModeComboBox.SelectedIndex == -1) { MessageBoxX.Show(i18N.Translate("Please select an mode first")); return; } //MenuStrip.Enabled = ConfigurationGroupBox.Enabled = ControlButton.Enabled = SettingsButton.Enabled = false; UpdateStatus(State.Starting); Firewall.AddNetchFwRules(); Task.Run(() => { var server = ServerComboBox.SelectedItem as Models.Server; var mode = ModeComboBox.SelectedItem as Models.Mode; MainController ??= new MainController(); var startResult = MainController.Start(server, mode); if (startResult) { Task.Run(() => { UpdateStatus(State.Started); StatusText(i18N.Translate(StateExtension.GetStatusString(State)) + PortText(server.Type, mode.Type)); LastUploadBandwidth = 0; //LastDownloadBandwidth = 0; //UploadSpeedLabel.Text = "↑: 0 KB/s"; DownloadSpeedLabel.Text = "↑↓: 0 KB/s"; UsedBandwidthLabel.Text = $"{i18N.Translate("Used",": ")}0 KB"; UsedBandwidthLabel.Visible = UploadSpeedLabel.Visible = DownloadSpeedLabel.Visible = true; UploadSpeedLabel.Visible = false; Bandwidth.NetTraffic(server, mode, MainController); }); // 如果勾选启动后最小化 if (Global.Settings.MinimizeWhenStarted) { WindowState = FormWindowState.Minimized; NotifyIcon.Visible = true; if (IsFirstOpened) { // 显示提示语 NotifyIcon.ShowBalloonTip(5, UpdateChecker.Name, i18N.Translate( "Netch is now minimized to the notification bar, double click this icon to restore."), ToolTipIcon.Info); IsFirstOpened = false; } Hide(); } if (Global.Settings.StartedTcping) { // 自动检测延迟 Task.Run(() => { while (true) { if (State == State.Started) { server.Test(); // 重载服务器列表 InitServer(); Thread.Sleep(Global.Settings.StartedTcping_Interval * 1000); } else { break; } } }); } } else { UpdateStatus(State.Stopped); StatusText(i18N.Translate("Start failed")); } }); } else { // 停止 UpdateStatus(State.Stopping); MainController.Stop(); UpdateStatus(State.Stopped); Task.Run(() => { TestServer(); }); } }
public void ControlFun() { SaveConfigs(); if (State == State.Waiting || State == State.Stopped) { // 服务器、模式 需选择 if (ServerComboBox.SelectedIndex == -1) { MessageBoxX.Show(i18N.Translate("Please select a server first")); return; } if (ModeComboBox.SelectedIndex == -1) { MessageBoxX.Show(i18N.Translate("Please select an mode first")); return; } //MenuStrip.Enabled = ConfigurationGroupBox.Enabled = ControlButton.Enabled = SettingsButton.Enabled = false; UpdateStatus(State.Starting); Firewall.AddNetchFwRules(); Task.Run(() => { var server = ServerComboBox.SelectedItem as Models.Server; var mode = ModeComboBox.SelectedItem as Models.Mode; MainController = new MainController(); var startResult = MainController.Start(server, mode); if (startResult) { Task.Run(() => { LastUploadBandwidth = 0; //LastDownloadBandwidth = 0; //UploadSpeedLabel.Text = "↑: 0 KB/s"; DownloadSpeedLabel.Text = "↑↓: 0 KB/s"; UsedBandwidthLabel.Text = $"{i18N.Translate("Used",": ")}0 KB"; UsedBandwidthLabel.Visible = UploadSpeedLabel.Visible = DownloadSpeedLabel.Visible = true; UploadSpeedLabel.Visible = false; Bandwidth.NetTraffic(server, mode, MainController); }); //MainController.pNFController.OnBandwidthUpdated += OnBandwidthUpdated; // 如果勾选启动后最小化 if (Global.Settings.MinimizeWhenStarted) { WindowState = FormWindowState.Minimized; NotifyIcon.Visible = true; if (IsFirstOpened) { // 显示提示语 NotifyIcon.ShowBalloonTip(5, UpdateChecker.Name, i18N.Translate( "Netch is now minimized to the notification bar, double click this icon to restore."), ToolTipIcon.Info); IsFirstOpened = false; } Hide(); } // TODO 是否需要移到一个函数中 var text = new StringBuilder(" ("); text.Append(Global.Settings.LocalAddress == "0.0.0.0" ? i18N.Translate("Allow other Devices to connect") + " " : ""); if (server.Type == "Socks5") { // 不可控Socks5 if (mode.Type == 3 && mode.Type == 5) { // 可控HTTP text.Append( $"HTTP {i18N.Translate("Local Port", ": ")}{Global.Settings.HTTPLocalPort}"); } else { // 不可控HTTP text.Clear(); } } else { // 可控Socks5 text.Append( $"Socks5 {i18N.Translate("Local Port", ": ")}{Global.Settings.Socks5LocalPort}"); if (mode.Type == 3 || mode.Type == 5) { //有HTTP text.Append( $" | HTTP {i18N.Translate("Local Port", ": ")}{Global.Settings.HTTPLocalPort}"); } } if (text.Length > 0) { text.Append(")"); } UpdateStatus(State.Started); StatusText(i18N.Translate(StateExtension.GetStatusString(State)) + text); if (Global.Settings.StartedTcping) { // 自动检测延迟 Task.Run(() => { while (true) { if (State == State.Started) { server.Test(); // 重载服务器列表 InitServer(); Thread.Sleep(Global.Settings.StartedTcping_Interval * 1000); } else { break; } } }); } } else { UpdateStatus(State.Stopped); StatusText(i18N.Translate("Start failed")); } }); } else { // 停止 UpdateStatus(State.Stopping); Task.Run(() => { var server = ServerComboBox.SelectedItem as Models.Server; var mode = ModeComboBox.SelectedItem as Models.Mode; MainController.Stop(); UpdateStatus(State.Stopped); TestServer(); }); } }
private void UpdateServersFromSubscribeLinksToolStripMenuItem_Click(object sender, EventArgs e) { var bak_State = State; var bak_StateText = StatusLabel.Text; if (Global.Settings.UseProxyToUpdateSubscription && ServerComboBox.SelectedIndex == -1) { Global.Settings.UseProxyToUpdateSubscription = false; } if (Global.Settings.UseProxyToUpdateSubscription) { // 当前 ServerComboBox 中至少有一项 if (ServerComboBox.SelectedIndex == -1) { MessageBoxX.Show(i18N.Translate("Please select a server first")); return; } MenuStrip.Enabled = ConfigurationGroupBox.Enabled = ControlButton.Enabled = SettingsButton.Enabled = false; ControlButton.Text = "..."; } if (Global.Settings.SubscribeLink.Count > 0) { StatusText(i18N.Translate("Starting update subscription")); DeleteServerPictureBox.Enabled = false; UpdateServersFromSubscribeLinksToolStripMenuItem.Enabled = false; Task.Run(() => { if (Global.Settings.UseProxyToUpdateSubscription) { var mode = new Models.Mode { Remark = "ProxyUpdate", Type = 5 }; _mainController = new MainController(); _mainController.Start(ServerComboBox.SelectedItem as Models.Server, mode); } foreach (var item in Global.Settings.SubscribeLink) { using var client = new WebClient(); try { if (!string.IsNullOrEmpty(item.UserAgent)) { client.Headers.Add("User-Agent", item.UserAgent); } else { client.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36"); } if (Global.Settings.UseProxyToUpdateSubscription) { client.Proxy = new WebProxy($"http://127.0.0.1:{Global.Settings.HTTPLocalPort}"); } var response = client.DownloadString(item.Link); try { response = ShareLink.URLSafeBase64Decode(response); } catch (Exception) { // ignored } Global.Settings.Server = Global.Settings.Server.Where(server => server.Group != item.Remark).ToList(); var result = ShareLink.Parse(response); if (result != null) { foreach (var x in result) { x.Group = item.Remark; } Global.Settings.Server.AddRange(result); NotifyIcon.ShowBalloonTip(5, UpdateChecker.Name, string.Format(i18N.Translate("Update {1} server(s) from {0}"), item.Remark, result.Count), ToolTipIcon.Info); } else { NotifyIcon.ShowBalloonTip(5, UpdateChecker.Name, string.Format(i18N.Translate("Update servers error from {0}"), item.Remark), ToolTipIcon.Error); } } catch (Exception) { } } InitServer(); DeleteServerPictureBox.Enabled = true; if (Global.Settings.UseProxyToUpdateSubscription) { MenuStrip.Enabled = ConfigurationGroupBox.Enabled = ControlButton.Enabled = SettingsButton.Enabled = true; ControlButton.Text = i18N.Translate("Start"); _mainController.Stop(); NatTypeStatusLabel.Text = ""; } Configuration.Save(); StatusText(i18N.Translate("Subscription updated")); MenuStrip.Enabled = ConfigurationGroupBox.Enabled = ControlButton.Enabled = SettingsButton.Enabled = true; State = bak_State; StatusLabel.Text = bak_StateText; }).ContinueWith(task => { BeginInvoke(new Action(() => { UpdateServersFromSubscribeLinksToolStripMenuItem.Enabled = true; })); }); NotifyIcon.ShowBalloonTip(5, UpdateChecker.Name, i18N.Translate("Updating in the background"), ToolTipIcon.Info); } else { MessageBoxX.Show(i18N.Translate("No subscription link")); } }
private async Task UpdateServersFromSubscribe() { void DisableItems(bool v) { MenuStrip.Enabled = ConfigurationGroupBox.Enabled = ProfileGroupBox.Enabled = ControlButton.Enabled = v; } if (Global.Settings.UseProxyToUpdateSubscription && ServerComboBox.SelectedIndex == -1) { Global.Settings.UseProxyToUpdateSubscription = false; } if (Global.Settings.UseProxyToUpdateSubscription && ServerComboBox.SelectedIndex == -1) { MessageBoxX.Show(i18N.Translate("Please select a server first")); return; } if (Global.Settings.SubscribeLink.Count <= 0) { MessageBoxX.Show(i18N.Translate("No subscription link")); return; } StatusText(i18N.Translate("Starting update subscription")); DisableItems(false); var useProxyToUpdateSubscription = Global.Settings.UseProxyToUpdateSubscription; try { string proxyServer = null; if (useProxyToUpdateSubscription) { var mode = new Models.Mode { Remark = "ProxyUpdate", Type = 5 }; await MainController.Start(ServerComboBox.SelectedItem as Server, mode); proxyServer = $"http://127.0.0.1:{Global.Settings.HTTPLocalPort}"; } await Subscription.UpdateServersAsync(proxyServer); InitServer(); Configuration.Save(); StatusText(i18N.Translate("Subscription updated")); } catch (Exception) { // ignored } finally { if (useProxyToUpdateSubscription) { try { await MainController.Stop(); } catch { // ignored } } DisableItems(true); } }