Inheritance: System.Windows.Forms.Form
        /// <summary>
        /// Method called to close the update form
        /// </summary>
        public static void CloseForm()
        {
            // No exception here
            if (Instance == null || Instance.IsDisposed)
                return;

            try
            {
                Instance.Invoke((Action)delegate
                {
                    Instance.Close();
                    Instance = null;
                });
            }
            catch { }
        }
        /// <summary>
        /// Main calling method. Opens a new instance of the form, and displays it
        /// </summary>
        /// <param name="Parent">The parent form, that will be used to center this form over</param>
        /// <param name="AllowDrag">Sets whether this window will be allowed to be moved by the user</param>
        /// <param name="WindowTitle">The text in the window title bar</param>
        public static void ShowScreen(Form Parent, bool AllowDrag = false, string WindowTitle = "Loading... Please Wait")
        {
            // Make sure it is currently not open and running.
            if (Instance != null && !Instance.IsDisposed)
                return;

            // Set window position to center parent
            Instance = new LoadingForm();
            Instance.Text = WindowTitle;
            Instance.AllowDrag = AllowDrag;
            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);
        }
        /// <summary>
        /// Main calling method. Opens a new instance of the form, and displays it
        /// </summary>
        /// <param name="WindowTitle"></param>
        public static void ShowScreen(Form Parent)
        {
            // Make sure it is currently not open and running.
            if (Instance != null && !Instance.IsDisposed)
                return;

            Instance = new LoadingForm();
            Instance.Location = new Point(Parent.Location.X + (Parent.Width / 2) - 150, Parent.Location.Y + (Parent.Height / 2) - 28);
            Thread thread = new Thread(new ThreadStart(LoadingForm.ShowForm));
            thread.IsBackground = true;
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            Thread.Sleep(100); // Wait for Run to work
        }
        private void ExportSettingsMenuItem_Click(object sender, EventArgs e)
        {
            // Warn the user about saved changes
            DialogResult res = MessageBox.Show(
                "Changes made since this window was opened will not reflect in the ScoringSettings.xml file "
                + "without reloading the saved changes. Would you like me to reload the last saved values?",
                "Reload Settings", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question
                );

            // Return if user cancels
            if (res == DialogResult.Cancel)
            {
                return;
            }

            // Show loading form
            LoadingForm.ShowScreen(this);

            // Reload settings!
            if (res == DialogResult.Yes && (!LoadConqFile() || !LoadCoopFile() || !LoadScoringCommon()))
            {
                LoadingForm.CloseForm();
                return;
            }

            try
            {
                // Define our file path and
                string file = Path.Combine(Paths.DocumentsFolder, "ScoringSettings.xml");

                // Generate our mappings
                Dictionary <string, string[]>[] types = { Scores, ConqScores, CoopScores };
                string[] names = { "general", "conquest", "coop" };

                // Create XML Settings
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Indent          = true;
                settings.IndentChars     = "\t";
                settings.NewLineChars    = Environment.NewLine;
                settings.NewLineHandling = NewLineHandling.Replace;

                // Write to file
                using (FileStream stream = File.Open(file, FileMode.Create))
                    using (XmlWriter Writer = XmlWriter.Create(stream, settings))
                    {
                        // Player Element
                        Writer.WriteStartDocument();

                        // Write editing warning
                        Writer.WriteComment(" Auto Generated :: Please DO NOT Edit Me! ");

                        // Begin
                        Writer.WriteStartElement("settings");

                        // Itterate through all setting catagories
                        for (int i = 0; i < 3; i++)
                        {
                            // Start general Element
                            Writer.WriteStartElement(names[i]);

                            // Add each scoring item to the XML
                            foreach (KeyValuePair <string, string[]> item in types[i])
                            {
                                // Open Row tag
                                Writer.WriteStartElement("item");
                                Writer.WriteAttributeString("name", item.Key);
                                Writer.WriteValue(item.Value[0]);
                                Writer.WriteEndElement();
                            }

                            // Close settings element
                            Writer.WriteEndElement();
                        }

                        // Close Tags and File
                        Writer.WriteEndElement();  // Close general Element
                        Writer.WriteEndDocument(); // End and Save file
                    }

                // Notify user
                Notify.Show("Settings Exported", "Scoring settings were exported successfully!", AlertType.Success);
            }
            finally
            {
                LoadingForm.CloseForm();
            }
        }
        /// <summary>
        /// Backs up the asp database
        /// </summary>
        private void ExportAsASPBtn_Click(object sender, EventArgs e)
        {
            // Define backup folder for this backup, and create it if it doesnt exist
            string Folder = Path.Combine(Paths.DocumentsFolder, "Database Backups", "bak_" + DateTime.Now.ToString("yyyyMMdd_HHmm"));

            if (!Directory.Exists(Folder))
            {
                Directory.CreateDirectory(Folder);
            }

            // Abortion indicator
            bool Aborted = false;

            // Open the database connection
            StatsDatabase Database;

            try
            {
                Database = new StatsDatabase();
            }
            catch (Exception Ex)
            {
                MessageBox.Show(
                    "Unable to connect to database\r\n\r\nMessage: " + Ex.Message,
                    "Database Connection Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Error
                    );

                // Stop the ASP server, and close this form
                HttpServer.Stop();
                this.Close();
                return;
            }

            // Show loading screen
            LoadingForm.ShowScreen(this);

            // Backup each table into its own bak file
            foreach (string Table in StatsDatabase.StatsTables)
            {
                // Create file path
                string BakFile = Path.Combine(Folder, Table + ".bak");

                // Backup tables
                try
                {
                    using (Stream Str = File.Open(BakFile, FileMode.OpenOrCreate))
                        using (StreamWriter Wtr = new StreamWriter(Str))
                        {
                            // Use a memory efficient way to export this stuff
                            foreach (Dictionary <string, object> Row in Database.QueryReader("SELECT * FROM " + Table))
                            {
                                Wtr.WriteLine(String.Join("\t", Row.Values));
                            }

                            Wtr.Flush();
                        }
                }
                catch (Exception Ex)
                {
                    // Close loading form
                    LoadingForm.CloseForm();

                    // Display the Exception Form
                    using (ExceptionForm Form = new ExceptionForm(Ex, false))
                    {
                        Form.Message = "An error occured while trying to backup the \"" + Table + "\" table. "
                                       + "The backup operation will now be cancelled.";
                        DialogResult Result = Form.ShowDialog();
                    }
                    Aborted = true;

                    // Try and remove backup folder
                    try
                    {
                        DirectoryInfo Dir = new DirectoryInfo(Folder);
                        Dir.Delete(true);
                    }
                    catch { }
                }

                if (Aborted)
                {
                    break;
                }
            }

            // Only display success message if we didnt abort
            if (!Aborted)
            {
                // Close loading form
                LoadingForm.CloseForm();

                string NL = Environment.NewLine;
                MessageBox.Show(
                    String.Concat("Backup has been completed successfully!", NL, NL, "Backup files have been saved to:", NL, Folder),
                    "Backup Success",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information
                    );
            }

            // Close the connection
            Database.Dispose();
        }
Beispiel #6
0
        /// <summary>
        /// Event fired when the Generate Button is clicked
        /// Does the random Generating
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void GenerateBtn_Click(object sender, EventArgs e)
        {
            // Initialize lists
            List <string> Modes = new List <string>();
            List <string> Sizes = new List <string>();

            // Get list of supported Game Modes the user wants
            if (ConquestBox.Checked)
            {
                Modes.Add("gpm_cq");
            }
            if (CoopBox.Checked)
            {
                Modes.Add("gpm_coop");
            }

            // Get list of sizes the user wants
            if (s16Box.Checked)
            {
                Sizes.Add("16");
            }
            if (s32Box.Checked)
            {
                Sizes.Add("32");
            }
            if (s64Box.Checked)
            {
                Sizes.Add("64");
            }

            // Make sure we have at least 1 mode and size
            if (Modes.Count == 0 || Sizes.Count == 0)
            {
                // Handle Message
                MessageBox.Show("You must select at least 1 GameMode and Map Size!", "User Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            // Initialize internal variables
            BF2Mod Mod            = MainForm.SelectedMod;
            Random Rnd            = new Random();
            int    NumOfMapsToAdd = (int)NumMaps.Value;
            int    MapCount       = Mod.Levels.Count;

            string[]      gModes = Modes.ToArray();
            StringBuilder Sb     = new StringBuilder();

            // Shuffle the maplist
            Mod.Levels.Shuffle();

            // Show loading form
            LoadingForm.ShowScreen(this);
            SetNativeEnabled(false);

            // Don't lockup GUI, run in a new task
            await Task.Run(() =>
            {
                // Loop through, the number of times the user specified, adding a map
                for (int i = 0; i < NumOfMapsToAdd; i++)
                {
                    // Prevent infinite looping and/or quit if we have reached the map count
                    if (i > 255 || (noDupesBox.Checked && i == MapCount))
                    {
                        break;
                    }

                    // Grab a random map from the levels array
                    try
                    {
                        // Try and load the map... if an exception is thrown, this loop doesnt count
                        BF2Map Map = Mod.LoadMap((noDupesBox.Checked) ? Mod.Levels[i] : Mod.Levels[Rnd.Next(0, MapCount)]);

                        // Get the common intersected gamemodes that the map has in common with what the user wants
                        string[] Common = Map.GameModes.Keys.ToArray();
                        Common          = gModes.Intersect(Common).ToArray();

                        // No common game modes
                        if (Common.Length == 0)
                        {
                            NumOfMapsToAdd++;
                            continue;
                        }

                        // Get a random gamemode key
                        string Mode = Common[Rnd.Next(0, Common.Length)];

                        // Get the common map sizes between what the user wants, and what the map supports
                        Common = Map.GameModes[Mode].Intersect(Sizes).ToArray();
                        if (Common.Length == 0)
                        {
                            // No common sizes, try another map
                            NumOfMapsToAdd++;
                            continue;
                        }

                        // Get a random size, and add the map
                        string Size = Common[Rnd.Next(0, Common.Length)];
                        Sb.AppendLine(Map.Name + " " + Mode + " " + Size);
                    }
                    catch (InvalidMapException)
                    {
                        NumOfMapsToAdd++;
                    }
                }
            });

            // Add new maplist to the maplist box
            MapListBox.Text = Sb.ToString();
            SetNativeEnabled(true);
            LoadingForm.CloseForm();
        }