/// <summary>
        /// Downloads the new update from Github Async.
        /// </summary>
        public static Task <bool> DownloadUpdateAsync(Form owner)
        {
            // Show Task Form
            TaskForm.Show(owner, "Downloading Update", "Downloading Update... Please Standby", true);

            // Return the task that will download the update
            return(Task.Run(async() =>
            {
                // Returns if there is no update
                if (!UpdateAvailable)
                {
                    return false;
                }

                // Simulate some headers, Github throws a fit otherwise
                Web = new WebClient();
                Web.Headers["User-Agent"] = "BF2GameSpyRedirector v" + Program.Version;
                Web.Headers["Accept"] = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
                Web.Headers["Accept-Language"] = "en-US,en;q=0.8";
                Web.Proxy = null; // Disable proxy because this can cause slowdown on some machines

                // Github file location
                string dlString = "https://github.com/BF2Statistics/BF2GamespyRedirector/releases/download/{0}/BF2GamespyRedirector_{0}.zip";
                Uri downloadUrl = new Uri(String.Format(dlString, NewVersion));

                // Path to the Downloaded file
                UpdateFileLocation = Path.Combine(Program.DocumentsFolder, $"BF2GamespyRedirector_{NewVersion}.zip");

                // Show Task Form
                IsDownloading = true;
                TaskForm.Cancelled += TaskForm_Cancelled;
                TaskForm.Progress.Report(new TaskProgressUpdate("Preparing the download..."));

                try
                {
                    // Download the new version Zip file
                    Web.DownloadProgressChanged += Wc_DownloadProgressChanged;
                    Web.DownloadFileCompleted += Wc_DownloadFileCompleted;
                    await Web.DownloadFileTaskAsync(downloadUrl, UpdateFileLocation);
                    return !AsyncArgs.Cancelled;
                }
                catch (WebException e) when(e.Status == WebExceptionStatus.RequestCanceled)
                {
                    // Ignore cancellation requests
                    return false;
                }
                catch (Exception)
                {
                    throw;
                }
                finally
                {
                    // Close that task form if its open!
                    if (TaskForm.IsOpen)
                    {
                        TaskForm.CloseForm();
                    }
                }
            }));
        }
Пример #2
0
        /// <summary>
        /// Open and displays the task form.
        /// </summary>
        /// <param name="Parent">The calling form, so the task form can be centered</param>
        /// <param name="WindowTitle">The task dialog window title</param>
        /// <param name="InstructionText">Instruction text displayed after the info icon. Leave null
        /// to hide the instruction text and icon.</param>
        /// <param name="SubMessage">Detail text that is displayed just above the progress bar</param>
        /// <param name="Cancelable">Specifies whether the operation can be canceled</param>
        /// <param name="Style">The progress bar style</param>
        /// <exception cref="Exception">Thrown if the Task form is already open and running. Use the IsOpen property
        /// to determine if the form is already running</exception>
        public static void Show(Form Parent,
                                string InstructionText,
                                string SubMessage,
                                bool Cancelable        = false,
                                ProgressBarStyle Style = ProgressBarStyle.Marquee,
                                int ProgressBarSteps   = 0)
        {
            // Make sure we dont have an already active form
            if (Instance != null && !Instance.IsDisposed)
            {
                throw new Exception("Task Form is already being displayed!");
            }

            // Create new instance
            Instance = new TaskForm();
            Instance.labelInstructionText.Text      = InstructionText;
            Instance.labelInstructionText.ForeColor = Color.FromArgb(0, 174, 219);
            Instance.labelContent.Text = SubMessage;
            Instance.Cancelable        = Cancelable;
            Instance.progressBar.Style = Style;

            // Setup progress bar
            if (ProgressBarSteps > 0)
            {
                Instance.progressBar.Maximum = ProgressBarSteps;
            }

            // Hide Cancel
            if (!Cancelable)
            {
                Instance.CnlButton.Hide();
                Instance.Height = 165;
                //Instance.Padding = new Padding(0, 0, 0, 15);
                //Instance.BackColor = Color.White;
            }

            // Set window position to center parent
            double H = Parent.Location.Y + (Parent.Height / 2) - (Instance.Height / 2);
            double W = Parent.Location.X + (Parent.Width / 2) - (Instance.Width / 2);

            Instance.Location = new Point((int)Math.Round(W, 0), (int)Math.Round(H, 0));

            // Display the Instanced Form
            Instance.Show(Parent);

            // Wait until the Instance form is displayed
            while (!Instance.IsHandleCreated)
            {
                Thread.Sleep(50);
            }
        }
Пример #3
0
        /// <summary>
        /// Event fired when the Launch Battlefield 2 button is pushed on the Launcher Tab
        /// </summary>
        private async void LaunchButton_Click(object sender, EventArgs args)
        {
            // Lock button to prevent spam
            LaunchButton.Enabled = false;

            // Close the app
            if (BF2Client.IsRunning)
            {
                BF2Client.Stop();
                return;
            }

            // Show overlay first, which provides the smokey (Modal) background
            using (ModalOverlay overlay = new ModalOverlay(this, 0.3))
            {
                // Show overlay
                overlay.Show(this);

                // Make sure a mod is selected
                if (ModComboBox.SelectedIndex < 1)
                {
                    MetroMessageBox.Show(overlay,
                                         "Please select a Bf2 Mod before attempting to start the game!",
                                         "No Mod Selected", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, 150
                                         );
                    overlay.Close();

                    // Reset button
                    BF2Client_Exited();

                    // Focus the mod select
                    ModComboBox.Focus();
                    return;
                }

                // Grab our mod and provider
                BF2Mod          Mod      = ModComboBox.SelectedItem as BF2Mod;
                ServiceProvider Provider = ProviderComboBox.SelectedItem as ServiceProvider;
                Server          Server   = ServerComboBox.SelectedItem as Server;

                // Remove old redirects
                Redirector.RemoveRedirects();

                // If we arent using a provider, skip to just launching the game
                if (Provider == null)
                {
                    goto StartClient;
                }

                // Apply redirects in a new thread
                SyncProgress <TaskStep> MyProgress = new SyncProgress <TaskStep>(RedirectStatusUpdate);
                bool Success = await Redirector.ApplyRedirectsAsync(Provider, MyProgress);

                if (!Success)
                {
                    // Show error
                    MetroMessageBox.Show(overlay, ErrorStep.Description, "Redirect Error", MessageBoxButtons.OK, MessageBoxIcon.Error, 180);
                    overlay.Close();

                    // Reset button
                    BF2Client_Exited();
                    return;
                }

                // Show the Task Form
                TaskForm.Show(this, "Launching Battlefield 2", $"Starting Battlefield 2 with mod \"{Mod.Title}\"", false, ProgressBarStyle.Marquee, 0);

                // Our goto to start the game
StartClient:
                {
                    try
                    {
                        // ===
                        // ALWAYS Remove all temporary keys before this next point
                        // ===
                        Params.Reload(LaunchParamsTextBox.Text);
                        Params.ClearTempParams();

                        // If we are auto joining a server, we must login!
                        if (Provider != null && (Server != null || CredentialsCheckBox.Checked))
                        {
                            // Prompt user to login!
                            using (LoginForm f = new LoginForm(Provider))
                            {
                                DialogResult Res = f.ShowDialog(overlay);
                                if (Res == DialogResult.Cancel)
                                {
                                    // Reset button
                                    TaskForm.CloseForm();
                                    BF2Client_Exited();
                                    return;
                                }

                                // Set server params
                                if (Server != null)
                                {
                                    Params.AddOrSet("joinServer", Server.Address);
                                    Params.AddOrSet("port", Server.Port.ToString());
                                }

                                // Set login params
                                Params.AddOrSet("playerName", f.UsernameTextBox.Text);
                                Params.AddOrSet("playerPassword", f.PasswordTextBox.Text);
                            }
                        }

                        // Start the client executable
                        BF2Client.Start(Mod, Params.BuildString(true));
                    }
                    catch (Exception e)
                    {
                        // Show error
                        MetroMessageBox.Show(overlay, e.Message, "Failure to Launch", MessageBoxButtons.OK, MessageBoxIcon.Error, 180);
                        BF2Client_Exited();
                    }
                }

                // Close the task form
                TaskForm.CloseForm();

                // Close Task form and overlay
                using (RunningOverlay = new GameRunningForm(this))
                {
                    RunningOverlay.ShowDialog(overlay);
                }

                // Close Overlay
                overlay.Close();
                LaunchButton.Focus();
            }
        }