public static void CheckForUpdates(bool silent) { try { // if updates exist var checkResult = UpdateChecker.Check(UpdateCheckURL, true, ReleaseDate); if (checkResult != UpdateChecker.UpdateCheckResult.Nothing) { string message = string.Format(My.Resources.Local.NewVersionAvailable, Tools.GetAssemblyProduct()); if (MessageBox.Show(message, Tools.GetAssemblyProduct(), MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK) { OpenURL(ResExHomePage); } } else { if (!silent) { MessageBox.Show(My.Resources.Local.YouHaveTheLatestVersion, Tools.GetAssemblyProduct(), MessageBoxButtons.OK, MessageBoxIcon.Information); } } } catch (Exception) { if (!silent) { throw; } } }
private void UpdateLoop() { while (IsRunning) { Thread.Sleep(6000); UpdateChecker.Check(); } }
private void btnCheckUpdates_Click(object sender, EventArgs e) { Config.DismissedUpdate = null; btnCheckUpdates.Enabled = false; updateCheckEventId = updates.Check(true); }
private void CheckUpdate() { var updater = new UpdateChecker(); updater.NewVersionFound += (o, args) => { NotifyTip($"{i18N.Translate(@"New version available", ": ")}{updater.LatestVersionNumber}"); }; updater.Check(false, Global.Settings.CheckBetaUpdate); }
private void CheckUpdate() { _updater.NewVersionFound += (o, args) => { NotifyTip($"{i18N.Translate(@"New version available", ": ")}{_updater.LatestVersionNumber}"); NewVersionLabel.Visible = true; }; _updater.Check(Global.Settings.CheckBetaUpdate); }
private void CheckForUpdate() { updateChecker.UpdateAvailableEvent += (info) => { versionAvailableLabel.Enabled = true; versionAvailableLabel.Text = $"New version available ({info.Version})"; }; updateChecker.Check(); }
static void Main(string[] args) { if (!MainLogic.Init()) { return; } UpdateChecker.Check(); MainLogic.Run(); }
/// <summary> /// Check for available updates. /// </summary> private void OnUpdateCheckDoWork(object sender, DoWorkEventArgs e) { var result = checker.Check(); if (result != UpdateCheckResult.CheckFailed) { UserPreferences.Preferences.LastUpdateCheck = DateTime.Now.ToBinary(); UserPreferences.SaveNow(); } e.Result = result; }
private void CheckUpdate() { _updater.NewVersionFound += (o, args) => { if (_updater.LatestVersionDownloadUrl.EndsWith(".zip", StringComparison.OrdinalIgnoreCase)) { NotifyTip($"{i18N.Translate(@"New version available", ": ")}{_updater.LatestVersionNumber}"); NewVersionLabel.Visible = true; } }; _updater.Check(Global.Settings.CheckBetaUpdate); }
private void CheckUpdate() { var updater = new UpdateChecker(); updater.NewVersionFound += (o, args) => { NotifyIcon.ShowBalloonTip(5, UpdateChecker.Name, $"{Utils.i18N.Translate(@"New version available")}{Utils.i18N.Translate(@": ")}{updater.LatestVersionNumber}", ToolTipIcon.Info); }; updater.Check(false, false); }
/// <summary> /// Check for available updates. /// </summary> private void OnUpdateCheckDoWork(object sender, System.ComponentModel.DoWorkEventArgs e) { var prefs = UserPreferences.Preferences; var lastCheck = DateTime.FromBinary(prefs.LastUpdateCheck); if (DateTime.Now.Subtract(lastCheck).TotalMinutes > 15) { var checker = new UpdateChecker(); checker.UpdateAvailable += this.Synchronize <PropertyEventArgs <Version> >((s, x) => UpdateAvailable(checker, x.Value)); checker.Check(); prefs.LastUpdateCheck = DateTime.Now.ToBinary(); UserPreferences.SaveNow(); } }
private void Main_Shown(object sender, EventArgs e) { if (auto) { auto = false; Run(); Close(); return; } updater = new UpdateChecker(this); updater.OnHasUpdate += HasUpdate; updater.Check(); }
// TODO: Threading now available again // TODO: API public MainForm() { var mainThread = ThreadRunner.Instance.GetMainTaskThread(); UpdateChecker.Check(); InitializeComponent(); StartThreads(); SetupControls(); FormDisplay = new TaskRunnerDisplay(mainThread.TaskRunner, this, FControls); UpdateVersionLabel(); StartProcessing(); }
private async void CheckForUpdates() { UpdateChecker.Update update = await UpdateChecker.Check(WinTools.GetGitStyleVersion(), UpdateChecker.Platform.Windows); if (update == null) { return; } MessageBoxResult downloadNew = MessageBox.Show($"There is a new update available for NexDirect (version {update.Version}).\nIt was published on GitHub at {update.PublishedAt.ToString("g")}.\n\nOpen your browser now to download the latest update?", "NexDirect - Update Available", MessageBoxButton.YesNo, MessageBoxImage.Question); if (downloadNew == MessageBoxResult.No) { return; } Process.Start(update.Url); }
public void CheckForUpdatesTest() { var fullyUpdated = new DateTime(2009, 12, 1); var hasLastReleaseButNotTheBeta = new DateTime(2009, 11, 1); var hasOldRelease = new DateTime(2009, 10, 1); Assert.AreEqual(UpdateChecker.UpdateCheckResult.Nothing, UpdateChecker.Check(@"UpdateCheckerFeed.xml", false, fullyUpdated)); Assert.AreEqual(UpdateChecker.UpdateCheckResult.Nothing, UpdateChecker.Check(@"UpdateCheckerFeed.xml", true, fullyUpdated)); Assert.AreEqual(UpdateChecker.UpdateCheckResult.Nothing, UpdateChecker.Check(@"UpdateCheckerFeed.xml", false, hasLastReleaseButNotTheBeta)); Assert.AreEqual(UpdateChecker.UpdateCheckResult.NewBeta, UpdateChecker.Check(@"UpdateCheckerFeed.xml", true, hasLastReleaseButNotTheBeta)); Assert.AreEqual(UpdateChecker.UpdateCheckResult.NewRelease, UpdateChecker.Check(@"UpdateCheckerFeed.xml", false, hasOldRelease)); Assert.AreEqual(UpdateChecker.UpdateCheckResult.NewBeta, UpdateChecker.Check(@"UpdateCheckerFeed.xml", true, hasOldRelease)); }
private async void CheckForUpdates() { UpdateChecker.Update update = await UpdateChecker.Check(WinTools.GetGitStyleVersion(), UpdateChecker.Platform.Windows); if (update == null) { return; } bool daylight = TimeZoneInfo.FindSystemTimeZoneById("AUS Eastern Standard Time").IsDaylightSavingTime(update.PublishedAt); MessageBoxResult downloadNew = MessageBox.Show($"There is a new update available for NexDirect (version {update.Version}).\nIt was published on GitHub at {WinTools.ToAustralianEasternTime(update.PublishedAt).ToString("g")} AE{(daylight ? "D" : "S")}T (Australian Eastern {(daylight ? "Daylight" : "Standard")} Time).\n\nOpen your browser now to download the latest update?", "NexDirect - Update Available", MessageBoxButton.YesNo, MessageBoxImage.Question); if (downloadNew == MessageBoxResult.No) { return; } Process.Start(update.Url); }
private void AboutDialog_Load(object sender, EventArgs e) { try { lblAppVersion.Text = UpdateChecker.AssemblyVersion.ToAppFormat(); lnkDownloadUpdate.Visible = false; var checker = new UpdateChecker(); checker.UpdateAvailable += new EventHandler <UpdateCheckEventArgs>(checker_UpdateAvailable); checker.NoUpdateAvailable += new EventHandler <UpdateCheckEventArgs>(checker_NoUpdateAvailable); checker.UpdateCheckFailed += new EventHandler <UpdateCheckEventArgs>(checker_UpdateCheckFailed); checker.Check(); } catch (Exception ex) { MessageBox.Show(this, String.Format(Res.Exception_GetAppVersion, ex.Message), Res.Error_Caption, MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public MainWindow() { InitializeComponent(); this.Width = Core.Util.Preferences.Default.MainWidth; this.Height = Core.Util.Preferences.Default.MainHeight; this.WindowState = Core.Util.Preferences.Default.MainMaximized ? WindowState.Maximized : WindowState.Normal; ThemeManager.LoadTheme(); // TODO : move to program entry point progVM = this.Resources["progVM"] as ProgressBarViewModel; progVM.Subscribe(DocManager.Inst); progVM.Foreground = ThemeManager.NoteFillBrushes[0]; this.CloseButtonClicked += (o, e) => { CmdExit(); }; CompositionTargetEx.FrameUpdating += RenderLoop; viewScaler.Max = UIConstants.TrackMaxHeight; viewScaler.Min = UIConstants.TrackMinHeight; viewScaler.Value = UIConstants.TrackDefaultHeight; trackVM = this.Resources["tracksVM"] as TracksViewModel; trackVM.TimelineCanvas = this.timelineCanvas; trackVM.TrackCanvas = this.trackCanvas; trackVM.HeaderCanvas = this.headerCanvas; trackVM.Subscribe(DocManager.Inst); CmdNewFile(); if (UpdateChecker.Check()) { var menuItem = new MenuItem() { Header = (string)FindResource("menu.updateavail"), Foreground = ThemeManager.WhiteKeyNameBrushNormal, }; menuItem.Click += (sender, e) => { System.Diagnostics.Process.Start("https://github.com/stakira/OpenUtau"); }; mainMenu.Items.Add(menuItem); } }
public MainWindow() { InitializeComponent(); this.Width = Core.Util.Preferences.Default.MainWidth; this.Height = Core.Util.Preferences.Default.MainHeight; this.WindowState = Core.Util.Preferences.Default.MainMaximized ? WindowState.Maximized : WindowState.Normal; ThemeManager.LoadTheme(); // TODO : move to program entry point progVM = this.Resources["progVM"] as ProgressBarViewModel; progVM.Subscribe(DocManager.Inst); progVM.Foreground = ThemeManager.NoteFillBrushes[0]; this.CloseButtonClicked += (o, e) => { CmdExit(); }; CompositionTargetEx.FrameUpdating += RenderLoop; viewScaler.Max = UIConstants.TrackMaxHeight; viewScaler.Min = UIConstants.TrackMinHeight; viewScaler.Value = UIConstants.TrackDefaultHeight; trackVM = this.Resources["tracksVM"] as TracksViewModel; trackVM.TimelineCanvas = this.timelineCanvas; trackVM.TrackCanvas = this.trackCanvas; trackVM.HeaderCanvas = this.headerCanvas; trackVM.Subscribe(DocManager.Inst); CmdNewFile(); if (UpdateChecker.Check()) { this.mainMenu.Items.Add(new MenuItem() { Header = @"Update available", Foreground = ThemeManager.WhiteKeyNameBrushNormal }); } }
private static async void CheckUpdateAsync() { var updater = new UpdateChecker(); updater.NewVersionFound += (o, args) => { var msg = $@"发现新版本:{updater.LatestVersionNumber} > {UpdateChecker.Version}"; Debug.WriteLine(msg); var res = MessageBox.Show( $@"{msg}{Environment.NewLine}是否跳转到下载页?", UpdateChecker.Name, MessageBoxButton.YesNo, MessageBoxImage.Question); if (res == MessageBoxResult.Yes) { Utils.Utils.OpenUrl(updater.LatestVersionUrl); } }; updater.NewVersionFoundFailed += (o, args) => { Debug.WriteLine(@"检查更新失败"); }; updater.NewVersionNotFound += (o, args) => { Debug.WriteLine($@"已是最新版本:{UpdateChecker.Version} ≥ {updater.LatestVersionNumber}"); }; await updater.Check(true, true); }
static void Main(string[] args) { if (System.Diagnostics.Process.GetProcessesByName(Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location)).Count() > 1) { return; } if (!MainLogic.Init()) { return; } UpdateChecker.Check(); Thread notifyThread = new Thread( delegate() { notifyIcon.DoubleClick += (s, e) => { Visible = !Visible; SetConsoleWindowVisibility(Visible); }; notifyIcon.Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath); notifyIcon.Visible = true; notifyIcon.Text = "AnimeDiscordRichPresence"; var contextMenu = new ContextMenuStrip(); contextMenu.Opening += new System.ComponentModel.CancelEventHandler((object sender, System.ComponentModel.CancelEventArgs e) => { if (MainLogic.IsPause) { AboutItem.Text = "Anime Detection Paused."; } else if (MainLogic.lastAnime == null) { AboutItem.Text = "No Anime Detected."; } else { AboutItem.Text = MainLogic.lastAnime.name; AboutItem.Text += string.IsNullOrEmpty(MainLogic.lastAnime.episode) ? "" : $" Episode {MainLogic.lastAnime.episode}"; AboutItem.Text += string.IsNullOrEmpty(MainLogic.lastAnime.website) ? "" : $" On {MainLogic.lastAnime.website}"; } }); contextMenu.Items.Add($"AnimeDiscordRichPresence {UpdateChecker.currentVersion}").Enabled = false; AboutItem = contextMenu.Items.Add("No Anime Detected."); AboutItem.Enabled = false; contextMenu.Items.Add(new ToolStripSeparator()); ToolStripMenuItem optionsMenuItem = (ToolStripMenuItem)contextMenu.Items.Add("Options"); PauseButton = optionsMenuItem.DropDownItems.Add("Pause", null, (s, e) => { if (MainLogic.IsPause) { PauseButton.Text = "Pause"; MainLogic.Resume(); } else { PauseButton.Text = "Resume"; MainLogic.Pause(); } }); optionsMenuItem.DropDownItems.Add(new ToolStripSeparator()); optionsMenuItem.DropDownItems.Add("Open Config", null, (s, e) => { MainLogic.Log("Opening config.json..."); if (!File.Exists("config.json")) { MainLogic.Log("config.json not found."); MessageBox.Show("config.json not found.", "ADRP"); } try { var startInfo = new System.Diagnostics.ProcessStartInfo("cmd.exe", "/c \"config.json\"") { UseShellExecute = true, WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden }; System.Diagnostics.Process.Start(startInfo); } catch (Exception ex) { MainLogic.Log("Cannot open config.json."); MessageBox.Show("Cannot open config.json.", "ADRP"); Console.WriteLine(ex); } }); optionsMenuItem.DropDownItems.Add("Reload Config", null, (s, e) => { MainLogic.ReloadConfig(); }); optionsMenuItem.DropDownItems.Add(new ToolStripSeparator()); optionsMenuItem.DropDownItems.Add("Force Update", null, (s, e) => { MainLogic.ForceUpdate(); }); optionsMenuItem.DropDownItems.Add("Force Reconnect", null, (s, e) => { MainLogic.ForceReconnect(); }); HideButton = contextMenu.Items.Add("Show Console", null, (s, e) => { Visible = !Visible; SetConsoleWindowVisibility(Visible); }); contextMenu.Items.Add("Exit", null, (s, e) => { MainLogic.Stop(); notifyIcon.Dispose(); Application.Exit(); }); notifyIcon.ContextMenuStrip = contextMenu; Application.Run(); }); notifyThread.Start(); Visible = false; SetConsoleWindowVisibility(Visible); try { MainLogic.Run(); } catch (Exception ex) { File.WriteAllText("Error.txt", ex.ToString()); Console.WriteLine("Uncaught Error Detected."); Console.WriteLine(ex); SetConsoleWindowVisibility(true); Console.ReadKey(); notifyIcon.Dispose(); Application.Exit(); } }
public static void CommandRead(string cmd) { if (cmd == null) { if (ConfUCS.IsConsoleMode) { ManageConsole(); } } try { switch (cmd.ToLower()) { case "/help": Console.WriteLine("/start <-- Start the server"); Console.WriteLine("/ban <PlayerID> <-- Ban a client"); // Console.WriteLine("/banip <PlayerID> <-- Ban a client by IP"); Console.WriteLine("/unban <PlayerID> <-- Unban a client"); // Console.WriteLine("/unbanip <PlayerID> <-- Unban a client"); // Console.WriteLine("/tempban <PlayerID> <Seconds> <-- Temporary ban a client"); // Console.WriteLine("/tempbanip <PlayerID> <Seconds> <-- Temporary ban a client by IP"); Console.WriteLine("/kick <PlayerID> <-- Kick a client from the server"); // Console.WriteLine("/mute <PlayerID> <-- Mute a client"); // Console.WriteLine("/unmute <PlayerID> <-- Unmute a client"); // Console.WriteLine("/setlevel <PlayerID> <Level> <-- Set a level for a player"); Console.WriteLine("/update <-- Check if update is available"); // Console.WriteLine("/say <Text> <-- Send a text to all"); // Console.WriteLine("/sayplayer <PlayerID> <Text> <-- Send a text to a player"); Console.WriteLine("/stop or /shutdown <-- Stop the server and save data"); Console.WriteLine("/forcestop <-- Force stop the server"); Console.WriteLine("/restart <-- Save data and then restart"); Console.WriteLine("/send sysinfo <-- Send server info to all players"); Console.WriteLine("/status <-- Get server status"); Console.WriteLine("/switch <-- Switch to GUI/Console mode"); break; case "/start": if (!ConfUCS.IsServerOnline) { ConsoleThread CT = new ConsoleThread(); CT.Start(); } else { Console.WriteLine("Server already online!"); } break; case "/stop": case "/shutdown": Console.WriteLine("Shutting down... Saving all data, wait."); foreach (var onlinePlayer in ResourcesManager.GetOnlinePlayers()) { var p = new ShutdownStartedMessage(onlinePlayer.GetClient()); p.SetCode(5); PacketManager.ProcessOutgoingPacket(p); } ConsoleManage.FreeConsole(); Environment.Exit(0); break; case "/forcestop": Console.WriteLine("Force shutting down... All progress not saved will be lost!"); Process.GetCurrentProcess().Kill(); break; case "/uptime": Console.WriteLine("Up time: " + ControlTimer.ElapsedTime); break; case "/restart": Console.WriteLine("System Restarting...."); var mail = new AllianceMailStreamEntry(); mail.SetId((int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds); mail.SetSenderId(0); mail.SetSenderAvatarId(0); mail.SetSenderName("System Manager"); mail.SetIsNew(0); mail.SetAllianceId(0); mail.SetAllianceBadgeData(0); mail.SetAllianceName("Legendary Administrator"); mail.SetMessage("System is about to restart in a few moments."); mail.SetSenderLevel(500); mail.SetSenderLeagueId(22); foreach (var onlinePlayer in ResourcesManager.GetOnlinePlayers()) { var pm = new GlobalChatLineMessage(onlinePlayer.GetClient()); var ps = new ShutdownStartedMessage(onlinePlayer.GetClient()); var p = new AvatarStreamEntryMessage(onlinePlayer.GetClient()); ps.SetCode(5); p.SetAvatarStreamEntry(mail); pm.SetChatMessage("System is about to restart in a few moments."); pm.SetPlayerId(0); pm.SetLeagueId(22); pm.SetPlayerName("System Manager"); PacketManager.ProcessOutgoingPacket(p); PacketManager.ProcessOutgoingPacket(ps); PacketManager.ProcessOutgoingPacket(pm); } Console.WriteLine("Saving all data..."); foreach (var l in ResourcesManager.GetOnlinePlayers()) { //DatabaseManager.Singelton.Save(l); } Console.WriteLine("Restarting now"); Process.Start(Application.ResourceAssembly.Location); Process.GetCurrentProcess().Kill(); break; case "/clear": Console.WriteLine("Console cleared"); if (ConfUCS.IsConsoleMode) { Console.Clear(); } else { MainWindow.RemoteWindow.RTB_Console.Clear(); } break; case "/status": Console.WriteLine("Server IP: " + ConfUCS.GetIP() + " on port 9339"); Console.WriteLine("IP Address (public): " + new WebClient().DownloadString("http://bot.whatismyipaddress.com/")); Console.WriteLine("Online Player: " + ResourcesManager.GetOnlinePlayers().Count); Console.WriteLine("Connected Player: " + ResourcesManager.GetConnectedClients().Count); Console.WriteLine("Starting Gold: " + int.Parse(ConfigurationManager.AppSettings["StartingGold"])); Console.WriteLine("Starting Elixir: " + int.Parse(ConfigurationManager.AppSettings["StartingElixir"])); Console.WriteLine("Starting Dark Elixir: " + int.Parse(ConfigurationManager.AppSettings["StartingDarkElixir"])); Console.WriteLine("Starting Gems: " + int.Parse(ConfigurationManager.AppSettings["StartingGems"])); Console.WriteLine("CoC Version: " + ConfigurationManager.AppSettings["ClientVersion"]); if (Convert.ToBoolean(ConfigurationManager.AppSettings["useCustomPatch"])) { Console.WriteLine("Patch: Active"); Console.WriteLine("Patching Server: " + ConfigurationManager.AppSettings["patchingServer"]); } else { Console.WriteLine("Patch: Disable"); } if (Convert.ToBoolean(ConfigurationManager.AppSettings["maintenanceMode"])) { Console.WriteLine("Maintance Mode: Active"); Console.WriteLine("Maintance time: " + Convert.ToInt32(ConfigurationManager.AppSettings["maintenanceTimeleft"]) + " Seconds"); } else { Console.WriteLine("Maintance Mode: Disable"); } break; case "/send sysinfo": Console.WriteLine("Server Status is now sent to all online players"); var mail1 = new AllianceMailStreamEntry(); mail1.SetId((int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds); mail1.SetSenderId(0); mail1.SetSenderAvatarId(0); mail1.SetSenderName("System Manager"); mail1.SetIsNew(0); mail1.SetAllianceId(0); mail1.SetAllianceBadgeData(0); mail1.SetAllianceName("Legendary Administrator"); mail1.SetMessage("Latest Server Status:\nConnected Players:" + ResourcesManager.GetConnectedClients().Count + "\nIn Memory Alliances:" + ObjectManager.GetInMemoryAlliances().Count + "\nIn Memory Levels:" + ResourcesManager.GetInMemoryLevels().Count); mail1.SetSenderLeagueId(22); mail1.SetSenderLevel(500); foreach (var onlinePlayer in ResourcesManager.GetOnlinePlayers()) { var p = new AvatarStreamEntryMessage(onlinePlayer.GetClient()); var pm = new GlobalChatLineMessage(onlinePlayer.GetClient()); pm.SetChatMessage("Our current Server Status is now sent at your mailbox!"); pm.SetPlayerId(0); pm.SetLeagueId(22); pm.SetPlayerName("System Manager"); p.SetAvatarStreamEntry(mail1); PacketManager.ProcessOutgoingPacket(p); PacketManager.ProcessOutgoingPacket(pm); } break; case "/update": UpdateChecker.Check(); break; case "/kick": var CommGet = cmd.Split(' '); if (CommGet.Length >= 2) { try { var id = Convert.ToInt64(CommGet[1]); var l = ResourcesManager.GetPlayer(id); if (ResourcesManager.IsPlayerOnline(l)) { ResourcesManager.LogPlayerOut(l); var p = new OutOfSyncMessage(l.GetClient()); PacketManager.ProcessOutgoingPacket(p); } else { Console.WriteLine("Kick failed: id " + id + " not found"); } } catch (FormatException) { Console.WriteLine("The given id is not a valid number"); } catch (Exception ex) { Console.WriteLine("Kick failed with error: " + ex); } } else { Console.WriteLine("Not enough arguments"); } break; case "/ban": var CommGet1 = cmd.Split(' '); if (CommGet1.Length >= 2) { try { var id = Convert.ToInt64(CommGet1[1]); var l = ResourcesManager.GetPlayer(id); if (l != null) { l.SetAccountStatus(99); l.SetAccountPrivileges(0); if (ResourcesManager.IsPlayerOnline(l)) { var p = new OutOfSyncMessage(l.GetClient()); PacketManager.ProcessOutgoingPacket(p); } } else { Console.WriteLine("Ban failed: id " + id + " not found"); } } catch (FormatException) { Console.WriteLine("The given id is not a valid number"); } catch (Exception ex) { Console.WriteLine("Ban failed with error: " + ex); } } else { Console.WriteLine("Not enough arguments"); } break; case "/unban": var CommGet2 = cmd.Split(' '); if (CommGet2.Length >= 2) { try { var id = Convert.ToInt64(CommGet2[1]); var l = ResourcesManager.GetPlayer(id); if (l != null) { l.SetAccountStatus(0); } else { Console.WriteLine("Unban failed: id " + id + " not found"); } } catch (FormatException) { Console.WriteLine("The given id is not a valid number"); } catch (Exception ex) { Console.WriteLine("Unban failed with error: " + ex); } } else { Console.WriteLine("Not enough arguments"); } break; case "/switch": if (ConfUCS.IsConsoleFirst) { Console.WriteLine("Sorry, you need to launch UCS in GUI mode first."); } else { if (ConfUCS.IsConsoleMode) { ConfUCS.IsConsoleMode = false; ConsoleManage.HideConsole(); InterfaceThread.Start(); Console.WriteLine("Switched to GUI"); ControlTimer.SwitchTimer(); } else { ConfUCS.IsConsoleMode = true; ConsoleManage.ShowConsole(); Console.SetOut(AllocateConsole.StandardConsole); MainWindow.RemoteWindow.Hide(); Console.Title = ConfUCS.UnivTitle; Console.WriteLine("Switched to Console"); ControlTimer.SwitchTimer(); ManageConsole(); } } break; default: Console.WriteLine("Unknown command. Type \"/help\" for a list containing all available commands."); break; } } catch (Exception) { Console.WriteLine("Something wrong happens..."); //throw; } //else if (cmd.ToLower().StartsWith("/mute")) //{ // var CommGet = cmd.Split(' '); // if (CommGet.Length >= 2) // { // try // { // var id = Convert.ToInt64(CommGet[1]); // var l = ResourcesManager.GetPlayer(id); // if (ResourcesManager.IsPlayerOnline(l)) // { // var p = new BanChatTrigger(l.GetClient()); // p.SetCode(999999999); // PacketManager.ProcessOutgoingPacket(p); // } // else // { // Console.WriteLineDebug("Chat Mute failed: id " + id + " not found", CoreWriter.level.DEBUGLOG); // } // } // catch (FormatException) // { // Console.WriteLineDebug("The given id is not a valid number", CoreWriter.level.DEBUGFATAL); // } // catch (Exception ex) // { // Console.WriteLineDebug("Chat Mute failed with error: " + ex, CoreWriter.level.DEBUGFATAL); // } // } // else Console.WriteLineDebug("Not enough arguments", CoreWriter.level.DEBUGFATAL); //} if (ConfUCS.IsConsoleMode) { ManageConsole(); } }
private async void _RunUpdateChecker(bool background_check) { // Do update check, with or without a progress dialog ProgressDialog progress = null; if (!background_check) { progress = new ProgressDialog(this, " "); progress.CounterFormat = ""; progress.Interval = 0; progress.Events.Start(-1, Translate._("MainWindow.UpdateCheck.Progress.Title"), " "); } string changelog = null; Task <string> check = Task.Run(() => { string vers_url = string.Format("{0}?u={1}&v={2}", Helpers.Unpack("yygpKSi20tc3STNKsUw008vPy8nMS9UtTi0qSy3SS87JL03RL8vxM0jzjAop8IhMTDL2MPDITc/QB0oXZ+bn6WbmpeXrVeTmAAA="), Settings.USER_KEY, Settings.APPVERSION.Replace(" ", "_")); UpdateChecker checker = new UpdateChecker(vers_url, progress != null? progress.Events : null, Logger.LOG); string url = checker.Check(Settings.APPTITLE, Settings.APPVERSION, out changelog); checker.Close(); checker = null; return(url); }); await check; string dl_url = check.Result; if (progress != null) { progress.Close(); } progress = null; if (string.IsNullOrEmpty(dl_url)) { if (!background_check) { MessageBox.Show(Translate._("MainWindow.UpdateCheck.NoUpdateAvail"), Translate._("MainWindow.UpdateCheck.Title")); } return; } // Prompt user to continue installation bool update = false; if (string.IsNullOrEmpty(changelog)) { var ret = MessageBox.Show(Translate._("MainWindow.UpdateCheck.NewVersionAvail"), Translate._("MainWindow.UpdateCheck.Title"), MessageBoxButton.YesNo, MessageBoxImage.Question); update = (ret == MessageBoxResult.Yes); } else { string[] buttons = new string[] { Translate._("Yes"), Translate._("No"), Translate._("MainWindow.UpdateCheck.NewVersionAvail") }; update = ShowHtmlResDialog.Show(Translate._("MainWindow.UpdateCheck.Title"), changelog, buttons); } if (!update) { return; } // Download installer package, ... string dest_file = Path.Combine(Settings.APPPATH, Path.GetFileName(dl_url)); using (Stream strm = File.Create(dest_file)) { Downloader dl = new Downloader(dl_url, null, Logger.LOG); if (!dl.Download(strm)) { MessageBox.Show(Translate._("MainWindow.UpdateCheck.DownloadFailed"), Translate._("MainWindow.UpdateCheck.Title")); return; } } // ..., and start installer in silent mode (installer will wait until program has closed) ProcessStartInfo info = new ProcessStartInfo() { FileName = dest_file, Arguments = "/S", WorkingDirectory = Settings.APPPATH, UseShellExecute = false, ErrorDialog = false, }; Process process = Process.Start(info); if (process == null || process.HasExited) { MessageBox.Show(Translate._("MainWindow.UpdateCheck.InstallFailed"), Translate._("MainWindow.UpdateCheck.Title")); if (process != null) { process.Dispose(); } return; } // End program and let installer do its job Close(); }
public void UpdateCheckTest() { UpdateChecker uc = new UpdateChecker(); Assert.AreEqual <bool>(false, uc.Check()); }
private void 检查更新MenuItem_Click(object sender, EventArgs e) { UpdateChecker updateChecker = new UpdateChecker(); updateChecker.Check(); }
public static void CommandRead(string cmd) { if (cmd == null) { if (ConfUCS.IsConsoleMode) { ManageConsole(); } } try { switch (cmd.ToLower()) { case "/help": Console.WriteLine("/start <-- Inicia el servidor"); Console.WriteLine("/ban <PlayerID> <-- Banear un jugador"); Console.WriteLine("/banip <PlayerID> <-- Banear un jugador mediante IP"); Console.WriteLine("/unban <PlayerID> <-- Unbanear un jugador"); Console.WriteLine("/unbanip <PlayerID> <-- Unbanear un jugador"); Console.WriteLine("/tempban <PlayerID> <Seconds> <-- Banea un jugador temporalmente"); Console.WriteLine("/tempbanip <PlayerID> <Seconds> <-- Banea temporalmente un jugador mediante IP"); Console.WriteLine("/kick <PlayerID> <-- Expulsa un jugador del servidor"); Console.WriteLine("/mute <PlayerID> <-- Silencia a un jugador"); Console.WriteLine("/unmute <PlayerID> <-- Quita silencio a jugador"); Console.WriteLine("/setlevel <PlayerID> <Level> <-- Fija un level a un jugador"); Console.WriteLine("/update <-- Comprueba si hay actualizaciónes disponibles"); Console.WriteLine("/say <Text> <-- Envia un mensaje a todos los jugadores"); Console.WriteLine("/sayplayer <PlayerID> <Text> <-- Envia un mensaje al jugador especificado"); Console.WriteLine("/stop or /shutdown <-- Detiene el servidor y guarda todos los datos"); Console.WriteLine("/forcestop <-- Fuerza el cierre del servidor !! ATENCION SE PIERDEN LOS DATOS!!"); Console.WriteLine("/restart <-- Guarda los datos y reinicia el servidor"); Console.WriteLine("/send sysinfo <-- Envia la información del servidor a los jugadores conectados"); Console.WriteLine("/status <-- Obtiene el estado el servidor"); Console.WriteLine("/uptime <-- Obtiene el tiempo activo del servidor"); Console.WriteLine("/switch <-- Cambiar modo GUI/Console"); Console.WriteLine("/clear <-- Limpia todos los mensajes de a consola"); break; case "/start": if (!ConfUCS.IsServerOnline) { ConsoleThread CT = new ConsoleThread(); CT.Start(); } else { Core.Debug.Write("El servidor esta activo!"); } break; case "/stop": case "/shutdown": Core.Debug.Write("Apagando servidor... Guardando datos, esperare..."); foreach (var onlinePlayer in ResourcesManager.GetOnlinePlayers()) { var p = new ShutdownStartedMessage(onlinePlayer.GetClient()); p.SetCode(5); p.Send(); } ConsoleManage.FreeConsole(); Environment.Exit(0); break; case "/forcestop": Core.Debug.Write("Terminado proceso del servidor... los ultimos datos se perderan!"); Process.GetCurrentProcess().Kill(); break; case "/uptime": Core.Debug.Write("Tiempo servidor iniciado: " + ControlTimer.ElapsedTime); break; case "/restart": Core.Debug.Write("Reiniciando servidor...."); var mail = new AllianceMailStreamEntry(); mail.SetId((int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds); mail.SetSenderId(0); mail.SetSenderAvatarId(0); mail.SetSenderName("System Manager"); mail.SetIsNew(0); mail.SetAllianceId(0); mail.SetAllianceBadgeData(0); mail.SetAllianceName("JJBreaker Administrador"); mail.SetMessage("El servidor se reiniciará en breve."); mail.SetSenderLevel(500); mail.SetSenderLeagueId(22); foreach (var onlinePlayer in ResourcesManager.GetOnlinePlayers()) { var pm = new GlobalChatLineMessage(onlinePlayer.GetClient()); var ps = new ShutdownStartedMessage(onlinePlayer.GetClient()); var p = new AvatarStreamEntryMessage(onlinePlayer.GetClient()); ps.SetCode(5); p.SetAvatarStreamEntry(mail); pm.SetChatMessage("El servidor se reiniciará en breve."); pm.SetPlayerId(0); pm.SetLeagueId(22); pm.SetPlayerName("System Manager"); p.Send(); ps.Send(); pm.Send(); } Console.WriteLine("Guaradndo datos..."); DatabaseManager.Save(ResourcesManager.GetInMemoryLevels()); Console.WriteLine("Restarting now"); Process.Start(Application.ResourceAssembly.Location); Process.GetCurrentProcess().Kill(); break; case "/clear": Core.Debug.Write("Consola limpiada"); if (ConfUCS.IsConsoleMode) { Console.Clear(); } else { MainWindow.RemoteWindow.RTB_Console.Clear(); } break; case "/status": Console.WriteLine("Server IP: " + ConfUCS.GetIP() + " on port 9339"); Console.WriteLine("IP Address (public): " + new WebClient().DownloadString("http://bot.whatismyipaddress.com/")); Console.WriteLine("Online Player: " + ResourcesManager.GetOnlinePlayers().Count); Console.WriteLine("Connected Player: " + ResourcesManager.GetConnectedClients().Count); Console.WriteLine("Starting Gold: " + Settings.StartingGold); Console.WriteLine("Starting Gems: " + Settings.StartingGems); var versionData = FingerPrint.version.Split('.'); Console.WriteLine("CRS Version: " + versionData[0] + "." + versionData[1] + "." + versionData[2]); if (Convert.ToBoolean(Constants.Patching)) { Console.WriteLine("Patch: Active"); Console.WriteLine("Patching Server: " + Constants.PatchURL); } else { Console.WriteLine("Patch: Disable"); } if (Convert.ToBoolean(Settings.Maintenance)) { Console.WriteLine("Maintance Mode: Active"); Console.WriteLine("Maintance time: " + Convert.ToInt32(Settings.MaintenanceDuration) + " Seconds"); } else { Core.Debug.Write("Maintance Mode: Disable"); } break; case "/send sysinfo": Console.WriteLine("Server Status is now sent to all online players"); var mail1 = new AllianceMailStreamEntry(); mail1.SetId((int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds); mail1.SetSenderId(0); mail1.SetSenderAvatarId(0); mail1.SetSenderName("System Manager"); mail1.SetIsNew(0); mail1.SetAllianceId(0); mail1.SetAllianceBadgeData(0); mail1.SetAllianceName("Legendary Administrator"); mail1.SetMessage("Latest Server Status:\nConnected Players:" + ResourcesManager.GetConnectedClients().Count + "\nIn Memory Alliances:" + ObjectManager.GetInMemoryAlliances().Count + "\nIn Memory Levels:" + ResourcesManager.GetInMemoryLevels().Count); mail1.SetSenderLeagueId(22); mail1.SetSenderLevel(500); foreach (var onlinePlayer in ResourcesManager.GetOnlinePlayers()) { var p = new AvatarStreamEntryMessage(onlinePlayer.GetClient()); var pm = new GlobalChatLineMessage(onlinePlayer.GetClient()); pm.SetChatMessage("Our current Server Status is now sent at your mailbox!"); pm.SetPlayerId(0); pm.SetLeagueId(22); pm.SetPlayerName("System Manager"); p.SetAvatarStreamEntry(mail1); p.Send(); pm.Send(); } break; case "/update": UpdateChecker.Check(); break; case "/kick": var CommGet = cmd.Split(' '); if (CommGet.Length >= 2) { try { var id = Convert.ToInt64(CommGet[1]); var l = ResourcesManager.GetPlayer(id); if (ResourcesManager.IsPlayerOnline(l)) { ResourcesManager.LogPlayerOut(l); var p = new OutOfSyncMessage(l.GetClient()); p.Send(); } else { Console.WriteLine("Kick failed: id " + id + " not found"); } } catch (FormatException) { Console.WriteLine("The given id is not a valid number"); } catch (Exception ex) { Console.WriteLine("Kick failed with error: " + ex); } } else { Console.WriteLine("Not enough arguments"); } break; case "/ban": var CommGet1 = cmd.Split(' '); if (CommGet1.Length >= 2) { try { var id = Convert.ToInt64(CommGet1[1]); var l = ResourcesManager.GetPlayer(id); if (l != null) { l.SetAccountStatus(99); l.SetAccountPrivileges(0); if (ResourcesManager.IsPlayerOnline(l)) { new OutOfSyncMessage(l.GetClient()).Send(); } } else { Console.WriteLine("Ban failed: id " + id + " not found"); } } catch (FormatException) { Console.WriteLine("The given id is not a valid number"); } catch (Exception ex) { Console.WriteLine("Ban failed with error: " + ex); } } else { Console.WriteLine("Not enough arguments"); } break; case "/unban": var CommGet2 = cmd.Split(' '); if (CommGet2.Length >= 2) { try { var id = Convert.ToInt64(CommGet2[1]); var l = ResourcesManager.GetPlayer(id); if (l != null) { l.SetAccountStatus(0); } else { Core.Debug.Write("Unban failed: id " + id + " not found"); } } catch (FormatException) { Core.Debug.Write("The given id is not a valid number"); } catch (Exception ex) { Core.Debug.Write("Unban failed with error: " + ex); } } else { Core.Debug.Write("Not enough arguments"); } break; case "/switch": if (ConfUCS.IsConsoleFirst) { Core.Debug.Write("Sorry, you need to launch UCS in GUI mode first."); } else { if (ConfUCS.IsConsoleMode) { ConfUCS.IsConsoleMode = false; ConsoleManage.HideConsole(); InterfaceThread.Start(); Core.Debug.Write("Switched to GUI"); ControlTimer.SwitchTimer(); } else { ConfUCS.IsConsoleMode = true; ConsoleManage.ShowConsole(); Console.SetOut(AllocateConsole.StandardConsole); MainWindow.RemoteWindow.Hide(); Console.Title = ConfUCS.UnivTitle; Core.Debug.Write("Switched to Console"); ControlTimer.SwitchTimer(); ManageConsole(); } } break; default: Core.Debug.Write("Unknown command ( " + cmd + " ). Type \"/help\" for a list containing all available commands."); break; } } catch (Exception) { Core.Debug.Write("Something wrong happens..."); // throw; } // else if (cmd.ToLower().StartsWith("/mute")) // { // var CommGet = cmd.Split(' '); // if (CommGet.Length >= 2) // { // try // { // var id = Convert.ToInt64(CommGet[1]); // var l = ResourcesManager.GetPlayer(id); // if (ResourcesManager.IsPlayerOnline(l)) // { // var p = new BanChatTrigger(l.GetClient()); // p.SetCode(999999999); // PacketManager.ProcessOutgoingPacket(p); // } // else // { // Console.WriteLineDebug("Chat Mute failed: id " + id + " not found", CoreWriter.level.DEBUGLOG); // } // } // catch (FormatException) // { // Console.WriteLineDebug("The given id is not a valid number", CoreWriter.level.DEBUGFATAL); // } // catch (Exception ex) // { // Console.WriteLineDebug("Chat Mute failed with error: " + ex, CoreWriter.level.DEBUGFATAL); // } // } // else Console.WriteLineDebug("Not enough arguments", CoreWriter.level.DEBUGFATAL); // } if (ConfUCS.IsConsoleMode) { ManageConsole(); } }