public void RefilterServers() { //If we don't have an active server list we want to return if (ServerInfo.ActiveServers == null) { return; } var previousSelectedServer = GetSelectedServer(); OFilteredServerList.Clear(); this.TotalPlayersOnline = 0; foreach (ServerInfo info in ServerInfo.ActiveServers) { this.TotalPlayersOnline += info.PlayerCount; if (sv_ServerSearch.Text != "") { if (info.ServerName.ToLower().Contains(sv_ServerSearch.Text.ToLower()) || info.IPAddress == sv_ServerSearch.Text || info.IPWithPort == sv_ServerSearch.Text) { OFilteredServerList.Add(info); } } else { OFilteredServerList.Add(info); } } bool SameVersionOnly = (SD_Filter_SameVersionOnly.IsChecked.HasValue) ? SD_Filter_SameVersionOnly.IsChecked.Value : false; for (int i = OFilteredServerList.Count - 1; i > -1; i--) { if (OFilteredServerList[i].PlayerCount < filter_MinPlayers) { OFilteredServerList.RemoveAt(i); continue; } if (OFilteredServerList[i].PlayerCount > filter_MaxPlayers) { OFilteredServerList.RemoveAt(i); continue; } if (SameVersionOnly && VersionCheck.GetGameVersionName() != "" && OFilteredServerList[i].GameVersion != VersionCheck.GetGameVersionName()) { OFilteredServerList.RemoveAt(i); continue; } } if (previousSelectedServer != null) { SetSelectedServer(previousSelectedServer.IPWithPort); } }
void ShowGameUpdateWindow(out bool wasUpdated) { RxLogger.Logger.Instance.Write("Showing game update window"); UpdateAvailableWindow theWindow = new UpdateAvailableWindow(); theWindow.LatestVersionText.Content = VersionCheck.GetLatestGameVersionName(); theWindow.GameVersionText.Content = VersionCheck.GetGameVersionName(); theWindow.WindowTitle.Content = "Game update available!"; theWindow.Owner = this; theWindow.ShowDialog(); if (!theWindow.WantsToUpdate) { wasUpdated = false; } else { //Get the previous vid that plays and store it. Nullify the playing vid so no handle is open Uri previousVid = sv_MapPreviewVid.Source; sv_MapPreviewVid.Source = null; // Close any other instances of the RenX-Launcher if (InstanceHandler.IsAnotherInstanceRunning()) { InstanceHandler.KillDuplicateInstance(); } var targetDir = GameInstallation.GetRootPath(); var applicationDir = Path.Combine(GameInstallation.GetRootPath(), "patch"); var patchPath = VersionCheck.GamePatchPath; var patchUrls = VersionCheck.GamePatchUrls; var patchVersion = VersionCheck.GetLatestGameVersionName(); var progress = new Progress <DirectoryPatcherProgressReport>(); var cancellationTokenSource = new CancellationTokenSource(); RxLogger.Logger.Instance.Write($"Starting game update | TargetDir: {targetDir} | AppDir: {applicationDir} | PatchPath: {patchPath},| PatchVersion: {patchVersion}"); Task task = RxPatcher.Instance.ApplyPatchFromWeb(patchPath, targetDir, applicationDir, progress, cancellationTokenSource.Token, VersionCheck.InstructionsHash); RxLogger.Logger.Instance.Write("Download complete, Showing ApplyUpdateWindow"); var window = new ApplyUpdateWindow(task, RxPatcher.Instance, progress, patchVersion, cancellationTokenSource, ApplyUpdateWindow.UpdateWindowType.Update); window.Owner = this; window.ShowDialog(); VersionCheck.UpdateGameVersion(); wasUpdated = true; //Resume playback of vid sv_MapPreviewVid.Source = previousVid; sv_MapPreviewVid.Play(); // Refresh server list StartRefreshingServers(); } }
public MainWindow() { OFilteredServerList = new TrulyObservableCollection <ServerInfo>(); SourceInitialized += (s, a) => { StartCheckingVersions(); if (ServerRefreshRate > 0) { _refreshTimer = new DispatcherTimer(); _refreshTimer.Interval = new TimeSpan(0, 0, ServerRefreshRate); _refreshTimer.Tick += (object sender, EventArgs e) => StartRefreshingServers(); _refreshTimer.Start(); } StartRefreshingServers(); if (VersionCheck.GetGameVersionName() == "Unknown") { Properties.Settings.Default.Installed = false; Properties.Settings.Default.Save(); #region PrimaryStartupInstallation //Show the dialog that asks to install the game this.InitFirstInstall(); #endregion PrimaryStartupInstallation } else { Properties.Settings.Default.Installed = true; Properties.Settings.Default.Save(); if (Properties.Settings.Default.Username != "") { SD_Username.Content = Properties.Settings.Default.Username; } else { ShowUsernameBox(); } } }; InitializeComponent(); //SetMessageboxText(MESSAGE_IDLE); // This must be set before any asynchronous code runs, as it might otherwise be overridden. ServerInfoGrid.Items.SortDescriptions.Add(new SortDescription(PlayerCountColumn.SortMemberPath, ListSortDirection.Ascending)); SD_GameVersion.Content = VersionCheck.GetGameVersionName(); BannerTools.Setup(); SD_ClanHeader.Cursor = BannerTools.GetBannerLink(null) != "" ? Cursors.Hand : null; //due to the mediaelement being set to manual control, we need to start the previewvid in the constructor this.sv_MapPreviewVid.Play(); }
private void SD_UpdateGame_Click(object sender, RoutedEventArgs e) { SetMessageboxText("Game is out of date!"); bool wasUpdated; ShowGameUpdateWindow(out wasUpdated); if (wasUpdated) { SetMessageboxText("Game was updated! " + VersionCheck.GetGameVersionName()); } }
private async Task CheckVersionsAsync() { await VersionCheck.UpdateLatestVersions(); if (!VersionCheck.IsLauncherOutOfDate()) { SetMessageboxText("Launcher is up to date!"); } else { SetMessageboxText("Launcher is out of date!"); bool updateInstallPending; ShowLauncherUpdateWindow(out updateInstallPending); if (updateInstallPending) { Close(); } else { // Get banners; consider moving this later BannerTools.Setup(); } return; } if (VersionCheck.GetGameVersionName() == "Unknown") { SetMessageboxText("Could not locate installed game version. Latest is " + VersionCheck.GetLatestGameVersionName()); } else if (!VersionCheck.IsGameOutOfDate()) { SetMessageboxText("Game is up to date! " + VersionCheck.GetGameVersionName()); } else { SetMessageboxText("Game is out of date!"); bool wasUpdated; ShowGameUpdateWindow(out wasUpdated); if (wasUpdated) { SetMessageboxText("Game was updated! " + VersionCheck.GetGameVersionName()); } SD_GameVersion.Content = VersionCheck.GetGameVersionName(); } // Get banners; consider moving this later BannerTools.Setup(); }
void ShowLauncherUpdateWindow(out bool updateInstallPending) { UpdateAvailableWindow theWindow = new UpdateAvailableWindow(); theWindow.LatestVersionText.Content = VersionCheck.GetLatestLauncherVersionName(); theWindow.GameVersionText.Content = VersionCheck.GetLauncherVersionName(); theWindow.WindowTitle.Content = "Launcher update available!"; theWindow.Owner = this; theWindow.ShowDialog(); if (theWindow.WantsToUpdate) { DownloadLauncherUpdate(out updateInstallPending); } else { updateInstallPending = false; } }
void ShowGameUpdateWindow(out bool wasUpdated) { UpdateAvailableWindow theWindow = new UpdateAvailableWindow(); theWindow.LatestVersionText.Content = VersionCheck.GetLatestGameVersionName(); theWindow.GameVersionText.Content = VersionCheck.GetGameVersionName(); theWindow.WindowTitle.Content = "Game update available!"; theWindow.Owner = this; theWindow.ShowDialog(); if (!theWindow.WantsToUpdate) { wasUpdated = false; } else { // Close any other instances of the RenX-Launcher if (InstanceHandler.IsAnotherInstanceRunning()) { InstanceHandler.KillDuplicateInstance(); } var targetDir = GameInstallation.GetRootPath(); var applicationDir = Path.Combine(GameInstallation.GetRootPath(), "patch"); var patchPath = VersionCheck.GamePatchPath; var patchUrls = VersionCheck.GamePatchUrls; var patchVersion = VersionCheck.GetLatestGameVersionName(); var progress = new Progress <DirectoryPatcherProgressReport>(); var cancellationTokenSource = new CancellationTokenSource(); var patcher = new RXPatcher(); Task task = patcher.ApplyPatchFromWeb(patchUrls.Select(url => url.ServerUri.AbsoluteUri).ToArray(), patchPath, targetDir, applicationDir, progress, cancellationTokenSource.Token, VersionCheck.InstructionsHash); var window = new ApplyUpdateWindow(task, patcher, progress, patchVersion, cancellationTokenSource, ApplyUpdateWindow.UpdateWindowType.Update); window.Owner = this; window.ShowDialog(); VersionCheck.UpdateGameVersion(); wasUpdated = true; } }
/// <summary> /// Function to control the first launch install. /// </summary> public async void FirstInstall() { VersionCheck.GetLatestGameVersionName(); await VersionCheck.UpdateLatestVersions(); //Get the current root path and prepare the installation var targetDir = GameInstallation.GetRootPath(); var applicationDir = System.IO.Path.Combine(GameInstallation.GetRootPath(), "patch"); var patchPath = VersionCheck.GamePatchPath; var patchVersion = VersionCheck.GetLatestGameVersionName(); //Create an empty var containing the progress report from the patcher var progress = new Progress <DirectoryPatcherProgressReport>(); var cancellationTokenSource = new System.Threading.CancellationTokenSource(); Task task = RxPatcher.Instance.ApplyPatchFromWeb(patchPath, targetDir, applicationDir, progress, cancellationTokenSource.Token, VersionCheck.InstructionsHash); //Create the update window var window = new ApplyUpdateWindow(task, RxPatcher.Instance, progress, patchVersion, cancellationTokenSource, ApplyUpdateWindow.UpdateWindowType.Install); window.Owner = this; //Show the dialog and wait for completion window.Show(); while (!task.IsCompleted) { await Task.Delay(1000); if (cancellationTokenSource.IsCancellationRequested) { task.Dispose(); } } RxLogger.Logger.Instance.Write($"Install complete, task state isCompleted = {task.IsCompleted}"); if (task?.IsCompleted == true && task?.Status != TaskStatus.Canceled) { VersionCheck.UpdateGameVersion(); //Create the UE3 redist dialog RxLogger.Logger.Instance.Write("Creating the UE3 Redist package dialog"); ModernDialog ueRedistDialog = new ModernDialog(); ueRedistDialog.Title = "UE3 Redistributable"; ueRedistDialog.Content = MessageRedistInstall; ueRedistDialog.Buttons = new Button[] { ueRedistDialog.OkButton, ueRedistDialog.CancelButton }; ueRedistDialog.ShowDialog(); RxLogger.Logger.Instance.Write($"Did the user want to install the UE3 Redist? - {ueRedistDialog.DialogResult.Value}"); if (ueRedistDialog.DialogResult.Value == true) { bool downloadSuccess = false; var bestPatchServer = RxPatcher.Instance.UpdateServerHandler.SelectBestPatchServer(); Uri RedistServer = bestPatchServer.Uri; //Create new URL based on the patch url (Without the patch part) String redistUrl = RedistServer + "redists/UE3Redist.exe"; string systemPath = GameInstallation.GetRootPath() + "Launcher\\Redist\\UE3Redist.exe"; //Create canceltokens to stop the downloaderthread if neccesary CancellationTokenSource downloaderTokenSource = new CancellationTokenSource(); CancellationToken downloaderToken = downloaderTokenSource.Token; //Redist downloader statuswindow GeneralDownloadWindow redistWindow = new GeneralDownloadWindow(downloaderTokenSource, "UE3Redist download"); redistWindow.Show(); //Start downloading redist RxLogger.Logger.Instance.Write($"Downloading UE3 Redist from {RedistServer.AbsoluteUri}"); downloadSuccess = await DownloadRedist(redistUrl, systemPath, downloaderToken, (received, size) => { redistWindow.UpdateProgressBar(received, size); }); RxLogger.Logger.Instance.Write("UE3 Redist Download Complete"); redistWindow.Close(); if (downloadSuccess) { //When done, execute the UE3Redist here try { using (Process ue3Redist = Process.Start(systemPath)) { ue3Redist.WaitForExit(); if (ue3Redist.ExitCode != 0)//If redist install fails, notify the user { MessageBox.Show("Error while installing the UE3 Redist."); } else//Everything done! save installed flag and restart { Properties.Settings.Default.Installed = true; Properties.Settings.Default.Save(); try { System.IO.File.Delete(systemPath); System.IO.Directory.Delete(GameInstallation.GetRootPath() + "Launcher\\Redist\\"); } catch (Exception) { MessageBox.Show("Could not cleanup the redist file. This won't hinder the game."); } } } } catch { MessageBox.Show("Error while executing the UE3 Redist."); } finally { //Restart launcher System.Diagnostics.Process.Start(Application.ResourceAssembly.Location); Application.Current.Shutdown(); } } if (downloadSuccess == false) { MessageBox.Show("Unable to download the UE3 Redist (corrupt download)"); } } else { ModernDialog notInstalledDialog = new ModernDialog(); notInstalledDialog.Title = "UE3 Redistributable"; notInstalledDialog.Content = MessageNotInstalled; notInstalledDialog.Buttons = new Button[] { notInstalledDialog.OkButton }; notInstalledDialog.ShowDialog(); //Shutdown launcher Application.Current.Shutdown(); } } else { Application.Current.Shutdown(); } }
/// <summary> /// This function will request all the server info on the RenXServers. This /// must be called to populate the server list. /// </summary> public static async Task ParseJsonServersAsync() { var newActiveServers = new List <ServerInfo>(); try { string jsonText = ""; //Grab the string from the RenX Website. RxLogger.Logger.Instance.Write($"Downloading RenxActiveServerJsonUrl {RenXWebLinks.RenxActiveServerJsonUrl}"); try { var client = new WebClient(); client.Headers.Set("User-Agent", "RenX-Launcher (" + VersionCheck.GetLauncherVersionName() + ")"); client.QueryString.Set("id", "launcher"); jsonText = await client.DownloadStringTaskAsync(RenXWebLinks.RenxActiveServerJsonUrl); } catch (Exception ex) { RxLogger.Logger.Instance.Write($"Server JSON Downloading Issue: {ex.Message}\r\nStack Trace:\r\n{ex.StackTrace}"); } RxLogger.Logger.Instance.Write($"Downloading RenxActiveServerJsonUrl {RenXWebLinks.RenxActiveServerJsonUrl} Complete"); if (jsonText == "") { return; } //Turn it into a JSon object that we can parse. var results = JsonConvert.DeserializeObject <dynamic>(jsonText); //For each object we have to try to get its components. #region -= Parse JSon Collection foreach (var data in results) { try { ServerInfo newServer = new ServerInfo(); //SET STRINGS newServer.ServerName = data["Name"] ?? "Missing"; newServer.ServerNamePrefix = data["NamePrefix"] ?? ""; if (newServer.ServerNamePrefix != "" && !newServer.ServerNamePrefix.EndsWith(" ")) { newServer.ServerNamePrefix = newServer.ServerNamePrefix + " "; } newServer.MapName = data["Current Map"] ?? "Missing"; newServer.SimplifiedMapName = GetPrettyMapName(newServer.MapName); newServer.MapMode = GetGameMode(newServer.MapName); newServer.GameVersion = data["Game Version"] ?? "Missing"; newServer.IpAddress = data["IP"] ?? "Missing"; //SET INTS newServer.BotCount = data["Bots"] ?? -1; newServer.PlayerCount = data["Players"] ?? -1; newServer.MineLimit = data.Variables["Mine Limit"] ?? -1; newServer.MaxPlayers = data.Variables["Player Limit"] ?? -1; newServer.VehicleLimit = data.Variables["Vehicle Limit"] ?? -1; newServer.CrateRespawnRate = data.Variables["CrateRespawnAfterPickup"] ?? -1; newServer.TimeLimit = data.Variables["Time Limit"] ?? -1; newServer.Port = data["Port"] ?? -1; //SET BOOLS newServer.SteamRequired = data.Variables["bSteamRequired"] ?? false; newServer.PasswordProtected = data.Variables["bPassworded"] ?? false; newServer.AutoBalance = data.Variables["bAutoBalanceTeams"] ?? false; newServer.SpawnCrates = data.Variables["bSpawnCrates"] ?? false; newServer.Ranked = data.Variables["bRanked"] ?? false; //SET COUNTRYINFO string[] countryInfo = await GrabCountry(newServer.IpAddress); newServer.CountryName = countryInfo[0]; newServer.CountryCode = countryInfo[1]; //All work done, add current serverinfo to the main list newActiveServers.Add(newServer); } catch (Exception ex) { RxLogger.Logger.Instance.Write($"Server JSON Loading Issue: {ex.Message}\r\nStack Trace:\r\n{ex.StackTrace}"); } } #endregion } catch { // If a global error occurred (e.g. connectivity/JSON parse error), clear the whole list. newActiveServers.Clear(); } ActiveServers = newActiveServers; }
public void StartupApp(object sender, StartupEventArgs e) { //Determine if the permissionChange is succesfull after launcher update bool didTryUpdate = false; bool isLogging = false; Logger.Instance.Write("Application starting up; checking command line options..."); foreach (string a in e.Args) { Logger.Instance.Write("Parsing option: " + a); if (a.Equals("--log", StringComparison.OrdinalIgnoreCase)) { Logger.Instance.StartLogConsole(); isLogging = true; } if (a.StartsWith("--patch-result=")) { didTryUpdate = true; string code = a.Substring("--patch-result=".Length); Logger.Instance.Write($"Startup Parameter 'patch-result' found - contents: {code}"); //If the code !=0 -> there is something wrong with the patching of the launcher if (code != "0" && code != "Success") { MessageBox.Show(string.Format("Failed to update the launcher (code {0}).\n\nPlease close any applications related to Renegade-X and try again.", code), "Patch failed", MessageBoxButton.OK, MessageBoxImage.Error); } else // Otherwise -> change folderpermissions and afterwards launch the launcher { try { SetFullControlPermissionsToEveryone(GameInstallation.GetRootPath()); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } else if (a.StartsWith("--firstInstall")) //Init the first install { Logger.Instance.Write("Startup parameters 'firstInstall' found - Starting RenX Installer"); Installer x = new Installer(); x.Show(); x.FirstInstall(); return; } else if (a.StartsWith("--UpdateGame=")) // Manually update the game to a given URL. { // Close any other instances of the RenX-Launcher if (InstanceHandler.IsAnotherInstanceRunning()) { InstanceHandler.KillDuplicateInstance(); } var targetDir = GameInstallation.GetRootPath(); var applicationDir = System.IO.Path.Combine(GameInstallation.GetRootPath(), "patch"); String patchUrl = a.Substring("--UpdateGame=".Length); var patchVersion = VersionCheck.GetLatestGameVersionName(); var progress = new Progress <DirectoryPatcherProgressReport>(); var cancellationTokenSource = new System.Threading.CancellationTokenSource(); RxPatcher.Instance.AddNewUpdateServer(patchUrl); System.Threading.Tasks.Task task = RxPatcher.Instance.ApplyPatchFromWebDownloadTask(RXPatchLib.RxPatcher.Instance.GetNextUpdateServerEntry(), targetDir, applicationDir, progress, cancellationTokenSource.Token, null); // no verificaiton on instructions.json, as we're bypassing standard version checking var window = new Views.ApplyUpdateWindow(task, RxPatcher.Instance, progress, patchVersion, cancellationTokenSource, Views.ApplyUpdateWindow.UpdateWindowType.Update); window.ShowDialog(); VersionCheck.UpdateGameVersion(); return; } Logger.Instance.Write("Parsed option: " + a); } Logger.Instance.Write("Done checking command line options"); if (LauncherTwo.Properties.Settings.Default.UpgradeRequired) { Logger.Instance.Write("Upgrading properties..."); LauncherTwo.Properties.Settings.Default.Upgrade(); LauncherTwo.Properties.Settings.Default.UpgradeRequired = false; LauncherTwo.Properties.Settings.Default.Save(); Logger.Instance.Write("Properties upgraded"); } //If no args are present, or a permissionChange update was executed -> normally start the launcher // didTryUpdate - If we tried an update, we have args, so we need to check this as well to make the main window load. if (e.Args.Length == 0 || didTryUpdate || isLogging) { if (InstanceHandler.IsAnotherInstanceRunning() && !didTryUpdate) { MessageBox.Show("Error:\nUnable to start Renegade-X Launcher: Another instance is already running!", "Renegade-X Launcher", MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK); Current.Shutdown(); } Logger.Instance.Write("Initial application startup complete, Creating new MainWindow"); new MainWindow().Show(); } Logger.Instance.Write("Exiting StartupApp..."); }
private void ServerInfoGrid_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (ServerInfoGrid.SelectedIndex >= OFilteredServerList.Count || ServerInfoGrid.SelectedIndex <= -1) { return; } ServerInfo selected = GetSelectedServer(); //Original mappreview code //sv_MapPreview.Source = BitmapToImageSourceConverter.Convert(MapPreviewSettings.GetMapBitmap(selected.MapName)); //Movie mappreview code if (File.Exists(GameInstallation.GetRootPath() + "\\PreviewVids\\" + selected.MapName + ".mp4")) { this.DefaultMoviePlays = false; sv_MapPreviewVid.Source = new Uri(GameInstallation.GetRootPath() + "\\PreviewVids\\" + selected.MapName + ".mp4"); sv_MapPreviewVid.Play(); } else if (!this.DefaultMoviePlays) { sv_MapPreviewVid.Source = new Uri(GameInstallation.GetRootPath() + "\\PreviewVids\\Default.mp4"); this.DefaultMoviePlays = true; sv_MapPreviewVid.Play(); } SD_ClanHeader.Source = BannerTools.GetBanner(selected.IPWithPort); SD_ClanHeader.Cursor = BannerTools.GetBannerLink(selected.IPWithPort) != "" ? Cursors.Hand : null; SD_Name.Content = selected.ServerName; SD_GameLength.Content = selected.TimeLimit.ToString(); SD_MineLimit.Content = selected.MineLimit.ToString(); SD_GameMode.Content = selected.MapMode.ToString(); SD_PlayerLimit.Content = selected.MaxPlayers.ToString(); SD_ServerVersion.Content = selected.GameVersion; SD_VehicleLimit.Content = selected.VehicleLimit; SD_CN.Content = selected.CountryName; Rect r; ServerInfo.FlagCodes.TryGetValue(selected.CountryCode, out r); this.SD_CFI.Viewbox = r; Autobalance_Checkbx.Source = GetChkBxImg(selected.AutoBalance); Steam_Checkbx.Source = GetChkBxImg(selected.SteamRequired); Crates_Checkbx.Source = GetChkBxImg(selected.SpawnCrates); InfantryOnly_Checkbx.Source = GetChkBxImg(selected.VehicleLimit <= 0); Ranked_Checkbx.Source = GetChkBxImg(selected.Ranked); // Set version mismatch message visibility and join button opacity if (VersionCheck.GetGameVersionName() == selected.GameVersion) { version_mismatch = false; SD_VersionMismatch.Visibility = Visibility.Hidden; this.Join_Server_Btn.Background.Opacity = 1.0; this.Join_Server_Btn.Content = "Join Server"; } else { version_mismatch = true; SD_VersionMismatch.Visibility = Visibility.Visible; this.Join_Server_Btn.Background.Opacity = 0.5; this.Join_Server_Btn.Content = "Server Version Mismatch"; } System.Windows.Media.Animation.Storyboard sb = this.FindResource("JoinButtonGlow") as System.Windows.Media.Animation.Storyboard; System.Windows.Media.Animation.Storyboard.SetTarget(sb, this.Join_Server_Btn); sb.Begin(); ServerInfoGrid.UpdateLayout(); }
/// <summary> /// Function to control the first launch install. /// </summary> public async void FirstInstall() { VersionCheck.GetLatestGameVersionName(); await VersionCheck.UpdateLatestVersions(); //Get the current root path and prepare the installation var targetDir = GameInstallation.GetRootPath(); var applicationDir = System.IO.Path.Combine(GameInstallation.GetRootPath(), "patch"); var patchUrls = VersionCheck.GamePatchUrls; var patchVersion = VersionCheck.GetLatestGameVersionName(); //Create an empty var containing the progress report from the patcher var progress = new Progress <DirectoryPatcherProgressReport>(); var cancellationTokenSource = new System.Threading.CancellationTokenSource(); Task task = new RXPatcher().ApplyPatchFromWeb(patchUrls, targetDir, applicationDir, progress, cancellationTokenSource.Token); //Create the update window int index = await new UpdateServerSelector().SelectHostIndex(patchUrls); var window = new ApplyUpdateWindow(task, progress, patchVersion, cancellationTokenSource, ApplyUpdateWindow.UpdateWindowType.Install, new Uri(patchUrls[index]).Host); //window.Owner = this; //Show the dialog and wait for completion window.ShowDialog(); if (task.IsCompleted == true) { VersionCheck.UpdateGameVersion(); //Create the UE3 redist dialog if (UERedistDialog.DialogResult.Value == true) { //Determine which server has best ping String[] PatchUrls = VersionCheck.GamePatchUrls; RXPatchLib.UpdateServerSelector Selector = new RXPatchLib.UpdateServerSelector(); //Need to solve a import issue regarding duplicate classes Task <int> SelectorTask = Selector.SelectHostIndex(VersionCheck.GamePatchUrls); //NEed to suppress the ui from showing here await SelectorTask; Uri Redistserver = new Uri(PatchUrls[SelectorTask.Result]); //Create new URL based on the patch url (Without the patch part) String RedistUrl = "http://" + Redistserver.Host + "/redists/UE3Redist.exe"; string SystemUrl = GameInstallation.GetRootPath() + "Launcher\\Redist\\UE3Redist.exe"; //Create canceltokens to stop the downloaderthread if neccesary CancellationTokenSource downloaderTokenSource = new CancellationTokenSource(); CancellationToken downloaderToken = downloaderTokenSource.Token; //Task for downloading the redist from patch server Task RedistDownloader = new Task(() => { System.IO.Directory.CreateDirectory(GameInstallation.GetRootPath() + "Launcher\\Redist"); System.Net.WebClient RedistRequest = new WebClient(); RedistRequest.DownloadFileAsync(new Uri(RedistUrl), SystemUrl); while (RedistRequest.IsBusy && !downloaderToken.IsCancellationRequested) { if (downloaderToken.IsCancellationRequested) { RedistRequest.CancelAsync(); } //Thread.Sleep(1000); } }, downloaderToken); //Redist downloader statuswindow GeneralDownloadWindow RedistWindow = new GeneralDownloadWindow(downloaderTokenSource, "UE3Redist download"); RedistWindow.Show(); //Task to keep the status of the UE3Redist download Task RedistDownloadStatus = new Task(() => { WebRequest req = System.Net.HttpWebRequest.Create(RedistUrl); req.Method = "HEAD"; int ContentLength; using (WebResponse resp = req.GetResponse()) { int.TryParse(resp.Headers.Get("Content-Length"), out ContentLength); } RedistWindow.initProgressBar(ContentLength); while (RedistDownloader.Status == TaskStatus.Running) { RedistWindow.Status = "Downloading UE3Redist"; FileInfo inf = new FileInfo(SystemUrl); RedistWindow.updateProgressBar(inf.Length); //Thread.Sleep(1000); } }); //Start downloading RedistDownloader.Start(); RedistDownloadStatus.Start(); await RedistDownloader; RedistWindow.Close(); //When done, execute the UE3Redist here try { using (Process UE3Redist = Process.Start(GameInstallation.GetRootPath() + "Launcher\\Redist\\UE3Redist.exe")) { UE3Redist.WaitForExit(); if (UE3Redist.ExitCode != 0)//If redist install fails, notify the user { MessageBox.Show("Error while installing the UE3 Redist."); } else//Everything done! save installed flag and restart { Properties.Settings.Default.Installed = true; Properties.Settings.Default.Save(); try { System.IO.File.Delete(GameInstallation.GetRootPath() + "Launcher\\Redist\\UE3Redist.exe"); System.IO.Directory.Delete(GameInstallation.GetRootPath() + "Launcher\\Redist\\"); } catch (Exception) { MessageBox.Show("Could not cleanup the redist file. This won't hinder the game."); } } } } catch { MessageBox.Show("Error while executing the UE3 Redist."); } finally { //Restart launcher System.Diagnostics.Process.Start(Application.ResourceAssembly.Location); Application.Current.Shutdown(); } } else { ModernDialog notInstalledDialog = new ModernDialog(); notInstalledDialog.Title = "UE3 Redistributable"; notInstalledDialog.Content = MessageNotInstalled; notInstalledDialog.Buttons = new Button[] { notInstalledDialog.OkButton }; notInstalledDialog.ShowDialog(); //Shutdown launcher Application.Current.Shutdown(); } } else { Application.Current.Shutdown(); } }
public void StartupApp(object sender, StartupEventArgs e) { //Determine if the permissionChange is succesfull after launcher update bool isGoodUpdate = false; bool isLogging = false; Logger.Instance.Write("Application starting up..."); foreach (string a in e.Args) { if (a.Equals("--log", StringComparison.OrdinalIgnoreCase)) { Logger.Instance.StartLogConsole(); isLogging = true; } if (a.StartsWith("--patch-result=")) { string code = a.Substring("--patch-result=".Length); Logger.Instance.Write($"Startup Parameter 'patch-result' found - contents: {code}"); //If the code !=0 -> there is something wrong with the patching of the launcher if (code != "0") { MessageBox.Show(string.Format("Failed to update the launcher (code {0}).\n\nPlease close any applications related to Renegade-X and try again.", code), "Patch failed", MessageBoxButton.OK, MessageBoxImage.Error); } else//Otherwise -> change folderpermissions and afterwards launch the launcher { try { SetFullControlPermissionsToEveryone(GameInstallation.GetRootPath()); isGoodUpdate = true; //Set isGoodUpdate to true to indicate correct permissionChange } catch (Exception ex) { MessageBox.Show(ex.Message); } } } else if (a.StartsWith("--firstInstall")) //Init the first install { Logger.Instance.Write("Startup parameters 'firstInstall' found - Starting RenX Installer"); Installer x = new Installer(); x.Show(); x.FirstInstall(); return; } else if (a.StartsWith("--UpdateGame="))//Manually opdate the game to a given URL. { // Close any other instances of the RenX-Launcher if (InstanceHandler.IsAnotherInstanceRunning()) { InstanceHandler.KillDuplicateInstance(); } var targetDir = GameInstallation.GetRootPath(); var applicationDir = System.IO.Path.Combine(GameInstallation.GetRootPath(), "patch"); String patchUrl = a.Substring("--UpdateGame=".Length); var patchVersion = VersionCheck.GetLatestGameVersionName(); var progress = new Progress <DirectoryPatcherProgressReport>(); var cancellationTokenSource = new System.Threading.CancellationTokenSource(); RxPatcher.Instance.AddNewUpdateServer(patchUrl, ""); System.Threading.Tasks.Task task = RxPatcher.Instance.ApplyPatchFromWebDownloadTask(RXPatchLib.RxPatcher.Instance.GetNextUpdateServerEntry(), targetDir, applicationDir, progress, cancellationTokenSource.Token, null); // no verificaiton on instructions.json, as we're bypassing standard version checking var window = new Views.ApplyUpdateWindow(task, RxPatcher.Instance, progress, patchVersion, cancellationTokenSource, Views.ApplyUpdateWindow.UpdateWindowType.Update); window.ShowDialog(); VersionCheck.UpdateGameVersion(); return; } } if (LauncherTwo.Properties.Settings.Default.UpgradeRequired) { LauncherTwo.Properties.Settings.Default.Upgrade(); LauncherTwo.Properties.Settings.Default.UpgradeRequired = false; LauncherTwo.Properties.Settings.Default.Save(); } /* Commented out untill I found a better way to intergrate it in the installation * if (!GameInstallation.IsRootPathPlausible()) * { * var result = MessageBox.Show("The game path seems to be incorrect. Please ensure that the launcher is placed in the correct location. If you proceed, files in the following location might be affected:\n\n" + GameInstallation.GetRootPath() + "\n\nAre you sure want to proceed?", "Invalid game path", MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No); * if (result != MessageBoxResult.Yes) * { * Shutdown(); * return; * } * } */ //If no args are present, or a permissionChange update was executed -> normally start the launcher if (e.Args.Length == 0 || isGoodUpdate || isLogging) { if (InstanceHandler.IsAnotherInstanceRunning() && !isGoodUpdate) { MessageBox.Show("Error:\nUnable to start Renegade-X Launcher: Another instance is already running!", "Renegade-X Launcher", MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK); Current.Shutdown(); } Logger.Instance.Write("Initial application startup complete, Creating new MainWindow"); new MainWindow().Show(); } /*else * { * Application.Current.Shutdown(); * }*/ }