コード例 #1
0
        public static void Load()
        {
            TraceLog.Write("Loading client settings... ");
            if (Container == null)
            {
                try
                {
                    using (FileStream file = File.Open(FilePath, FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read))
                        using (StreamReader reader = new StreamReader(file))
                        {
                            string contents = reader.ReadToEnd();
                            if (String.IsNullOrWhiteSpace(contents))
                            {
                                Container = new SettingsContainer();
                            }
                            else
                            {
                                Container = JsonConvert.DeserializeObject <SettingsContainer>(contents);
                            }

                            TraceLog.WriteLine("Success!");
                        }
                }
                catch (Exception e)
                {
                    TraceLog.WriteLine("Failed!");
                    TraceLog.Indent();
                    TraceLog.TraceError(e.Message);
                    TraceLog.Unindent();
                    Container = new SettingsContainer();
                }

                // Ensure we have the default provider if none others
                if (Container.ServiceProviders.Count == 0)
                {
                    Container.AddDefaultProvider();

                    // Save changes
                    Save();
                }
            }
        }
コード例 #2
0
        /// <summary>
        /// Loads a battlefield 2 server into this object for use.
        /// </summary>
        /// <param name="Bf2Path">The full root path to the server's executable file</param>
        public static void SetInstallPath(string Bf2Path)
        {
            // Write trace
            TraceLog.WriteLine($"Loading Battlefield 2 directory: \"{Bf2Path}\"");
            TraceLog.Indent();

            // Make sure we have a valid server path
            if (!File.Exists(Path.Combine(Bf2Path, "bf2.exe")))
            {
                // Write trace
                TraceLog.TraceError("Invalid BF2 installation path. bf2.exe does not exist!");
                TraceLog.Unindent();
                throw new ArgumentException("Invalid BF2 installation path");
            }

            // Make sure we actually changed server paths before processing
            if (!String.IsNullOrEmpty(RootPath) && (new Uri(Bf2Path)) == (new Uri(RootPath)))
            {
                // Write trace
                TraceLog.WriteLine("Installation directory was not changed, aborting.");
                TraceLog.Unindent();

                // Same path is selected, just return
                return;
            }

            // Temporary variables
            string        Modpath  = Path.Combine(Bf2Path, "mods");
            List <BF2Mod> TempMods = new List <BF2Mod>();

            // Make sure the server has the required folders
            if (!Directory.Exists(Modpath))
            {
                // Write trace
                TraceLog.TraceError("Unable to locate the 'mods' folder.");
                TraceLog.Unindent();
                throw new Exception("Unable to locate the 'mods' folder. Please make sure you have selected a valid "
                                    + "battlefield 2 installation path before proceeding.");
            }

            // Load all found mods, discarding invalid mods
            ModLoadErrors = new List <string>();
            IEnumerable <string> ModList = from dir in Directory.GetDirectories(Modpath) select dir.Substring(Modpath.Length + 1);

            foreach (string Name in ModList)
            {
                try
                {
                    // Create a new instance of the mod, and store it for later
                    BF2Mod Mod = new BF2Mod(Modpath, Name);
                    TempMods.Add(Mod);
                    TraceLog.WriteLine("Loaded mod: " + Mod.Name);
                }
                catch (InvalidModException E)
                {
                    ModLoadErrors.Add(E.Message);
                    TraceLog.WriteLine($"Failed to Load mod: \"{Name}\" Error: {E.Message}");
                    continue;
                }
                catch (Exception E)
                {
                    ModLoadErrors.Add(E.Message);
                    TraceLog.TraceError($"Caught Exception loading mod: \"{Name}");
                    TraceLog.Indent();
                    TraceLog.WriteLine(E.Message);
                    TraceLog.Unindent();
                }
            }

            // We need mods bro...
            if (TempMods.Count == 0)
            {
                TraceLog.TraceError($"No valid mods could be found!");
                throw new Exception("No valid battlefield 2 mods could be found in the Bf2 Server mods folder!");
            }

            // Define var values after we now know this server apears valid
            RootPath = Bf2Path;
            Mods     = TempMods;
            TraceLog.Unindent();

            // Fire change event
            if (PathChanged != null)
            {
                PathChanged();
            }

            // Recheck server process
            CheckServerProcess();
        }
コード例 #3
0
        /// <summary>
        /// Entry point... this will check if we are at the initial setup
        /// phase, and show the installation forms
        /// </summary>
        /// <returns>Returns false if the user cancels the setup before the basic settings are setup, true otherwise</returns>
        public static bool Run()
        {
            // Load the program config
            Settings Config = Settings.Default;

            // If this is the first time running a new update, we need to update the config file
            if (!Config.SettingsUpdated)
            {
                Config.Upgrade();
                Config.SettingsUpdated = true;
                Config.Save();
            }

            // If this is the first run, Get client and server install paths
            if (String.IsNullOrWhiteSpace(Config.Bf2InstallDir) || !File.Exists(Path.Combine(Config.Bf2InstallDir, "bf2.exe")))
            {
                TraceLog.WriteLine("Empty or Invalid BF2 directory detected, running Install Form.");
                if (!ShowInstallForm())
                {
                    return(false);
                }
            }

            // Create the "My Documents/BF2Statistics" folder
            try
            {
                // Make sure documents folder exists
                if (!Directory.Exists(Program.DocumentsFolder))
                {
                    Directory.CreateDirectory(Program.DocumentsFolder);
                }
            }
            catch (Exception E)
            {
                // Alert the user that there was an error
                MessageBox.Show("We encountered an error trying to create the required \"My Documents/BF2Statistics\" folder!"
                                + Environment.NewLine.Repeat(1) + E.Message,
                                "Setup Error",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error
                                );
                return(false);
            }

            // Load server go.. If we fail to load a valid server, we will come back to here
LoadClient:
            {
                // Load the BF2 Server
                try
                {
                    BF2Client.SetInstallPath(Config.Bf2InstallDir);
                }
                catch (Exception E)
                {
                    MetroMessageBox.Show(Form.ActiveForm, E.Message, "Battlefield 2 Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                    // Re-prompt
                    if (!ShowInstallForm())
                    {
                        return(false);
                    }

                    goto LoadClient;
                }
            }

            return(true);
        }
コード例 #4
0
        /// <summary>
        /// The main entry point for the redirector
        /// </summary>
        /// <returns>Returns wether the DNS cache results match the selected IPAddresses</returns>
        public static bool Initialize()
        {
            // Only initialize once
            if (!IsInitialized)
            {
                IsInitialized = true;
                TraceLog.WriteLine("Initializing Redirector");
                TraceLog.Indent();

                // Set the System.Net DNS Cache refresh timeout to 1 millisecond
                ServicePointManager.DnsRefreshTimeout = 1;

                // Get config options
                RedirectMethod = Program.Config.RedirectMode;
                TraceLog.WriteLine("Chosen Redirect mode: " + RedirectMethod.ToString());

                // Create new Instances
                HostsFileSys = new SysHostsFile();
                HostsFileIcs = new HostsFileIcs();

                // Detect redirects
                bool IcsHasRedirects   = HostsFileIcs.HasAnyEntry(GamespyHosts) || HostsFileIcs.HasEntry(Bf2StatsHost);
                bool HostsHasRedirects = HostsFileSys.HasAnyEntry(GamespyHosts) || HostsFileSys.HasEntry(Bf2StatsHost);

                // Write tracelogs
                TraceLog.WriteLine("System Hosts has redirects: " + ((HostsHasRedirects) ? "True" : "False"));
                TraceLog.WriteLine("Hosts.ics has redirects: " + ((IcsHasRedirects) ? "True" : "False"));

                // Both files cannot have redirects!
                if (IcsHasRedirects && HostsHasRedirects)
                {
                    // Get the Non-Selected mode, and remove those redirects
                    HostsFile toRemove = (RedirectMethod == RedirectMode.HostsFile)
                        ? HostsFileIcs as HostsFile
                        : HostsFileSys as HostsFile;

                    try
                    {
                        // Remove all redirects
                        TraceLog.Write("Removing redirects from unchosen hostsfile... ");
                        RemoveRedirects(toRemove);
                        TraceLog.WriteLine("Success");
                    }
                    catch (Exception e)
                    {
                        TraceLog.WriteLine("Failed!");
                        TraceLog.Indent();
                        TraceLog.TraceError(e.Message);
                    }
                }

                // Set old redirect data if we have it
                if (RedirectsEnabled)
                {
                    // Grab our service provider
                    ServiceProvider provider = ClientSettings.ServiceProviders
                                               .Where(x => x.Name == Program.Config.LastUsedProvider)
                                               .FirstOrDefault();

                    // Make sure we have an object before settings
                    if (provider != null)
                    {
                        SetProviderIPAddress(provider);
                    }
                }

                // Remove all indents
                TraceLog.Unindent(true);
            }

            // Verify cache
            return((RedirectsEnabled) ? VerifyDNSCache() : true);
        }