Example #1
0
        static void Main()
        {
            CultureInfo.DefaultThreadCurrentCulture     = CultureInfo.GetCultureInfo(InformationCache.Lang.Name);
            CultureInfo.DefaultThreadCurrentUICulture   = CultureInfo.GetCultureInfo(Translations.UI(Translations.Application_Language = InformationCache.Lang.Name));
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            Application.ThreadException += Application_ThreadException;
            Application.EnableVisualStyles();
            /* We need to set these once and Forget about it (Unless there is a bug such as HttpWebClient) */
            AppContext.SetSwitch("Switch.System.Net.DontEnableSchUseStrongCrypto", false);
            AppContext.SetSwitch("Switch.System.Net.DontEnableSystemDefaultTlsVersions", false);
            ServicePointManager.DnsRefreshTimeout = (int)TimeSpan.FromSeconds(30).TotalMilliseconds;
            ServicePointManager.Expect100Continue = true;
            ServicePointManager.ServerCertificateValidationCallback = (Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) =>
            {
                bool isOk = true;
                if (sslPolicyErrors != SslPolicyErrors.None)
                {
                    for (int i = 0; i < chain.ChainStatus.Length; i++)
                    {
                        if (chain.ChainStatus[i].Status == X509ChainStatusFlags.RevocationStatusUnknown)
                        {
                            continue;
                        }
                        chain.ChainPolicy.RevocationFlag      = X509RevocationFlag.EntireChain;
                        chain.ChainPolicy.RevocationMode      = X509RevocationMode.Online;
                        chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 0, 15);
                        chain.ChainPolicy.VerificationFlags   = X509VerificationFlags.AllFlags;
                        bool chainIsValid = chain.Build((X509Certificate2)certificate);
                        if (!chainIsValid)
                        {
                            isOk = false;
                            break;
                        }
                    }
                }
                return(isOk);
            };

            if (Debugger.IsAttached && !NFSW.IsRunning())
            {
                Start();
            }
            else
            {
                if (NFSW.IsRunning())
                {
                    if (NFSW.DetectGameProcess())
                    {
                        MessageBox.Show(null, Translations.Database("Program_TextBox_GameIsRunning"), "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }
                    else if (NFSW.DetectGameLauncherSimplified())
                    {
                        MessageBox.Show(null, Translations.Database("Program_TextBox_SimplifiedIsRunning"), "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }
                    else
                    {
                        MessageBox.Show(null, Translations.Database("Program_TextBox_SBRWIsRunning"), "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }

                    FunctionStatus.LauncherForceClose = true;
                }

                if (FunctionStatus.LauncherForceClose)
                {
                    FunctionStatus.ErrorCloseLauncher("User Tried to Launch SBRW Launcher with one Running Already", false);
                }
                else
                {
                    /* Check if File needs to be Downloaded */
                    string LZMAPath = Strings.Encode(Path.Combine(Locations.LauncherFolder, Locations.NameLZMA));

                    if (File.Exists(LZMAPath))
                    {
                        try
                        {
                            if (new FileInfo(LZMAPath).Length == 0)
                            {
                                File.Delete(LZMAPath);
                            }
                        }
                        catch { }
                    }

                    /* INFO: this is here because this dll is necessary for downloading game files and I want to make it async.
                     * Updated RedTheKitsune Code so it downloads the file if its missing.
                     * It also restarts the launcher if the user click on yes on Prompt. - DavidCarbon */
                    if (!File.Exists("LZMA.dll"))
                    {
                        try
                        {
                            Uri URLCall = new Uri(URLs.File + "/LZMA.dll");
                            ServicePointManager.FindServicePoint(URLCall).ConnectionLeaseTimeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds;
                            WebClient Client = new WebClient
                            {
                                Encoding = Encoding.UTF8
                            };
                            Client.Headers.Add("user-agent", "SBRW Launcher " +
                                               Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)");
                            Client.DownloadFileCompleted += (object sender, AsyncCompletedEventArgs e) =>
                            {
                                if (File.Exists(LZMAPath))
                                {
                                    try
                                    {
                                        if (new FileInfo(LZMAPath).Length == 0)
                                        {
                                            File.Delete(LZMAPath);
                                        }
                                    }
                                    catch { }
                                }
                            };

                            FunctionStatus.LauncherForceClose = true;

                            try
                            {
                                Client.DownloadFile(URLCall, LZMAPath);

                                if (MessageBox.Show(null, Translations.Database("Program_TextBox_LZMA_Redownloaded"),
                                                    "GameLauncher Restart Required",
                                                    MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                                {
                                    LauncherMustRestart = true;
                                }
                            }
                            catch (Exception Error)
                            {
                                FunctionStatus.LauncherForceCloseReason = Error.Message;
                            }
                            finally
                            {
                                if (Client != null)
                                {
                                    Client.Dispose();
                                }
                            }
                        }
                        catch { }
                    }

                    if (FunctionStatus.LauncherForceClose)
                    {
                        FunctionStatus.ErrorCloseLauncher("Closing From Downloaded Missing LZMA", LauncherMustRestart);
                    }
                    else
                    {
                        Mutex No_Java = new Mutex(false, "GameLauncherNFSW-MeTonaTOR");
                        try
                        {
                            if (No_Java.WaitOne(0, false))
                            {
                                if (!UnixOS.Detected())
                                {
                                    /* MONO Hates this... */
                                    string[] File_List =
                                    {
                                        "CommandLine.dll - 2.8.0",
                                        "DiscordRPC.dll - 1.0.175.0",
                                        "Flurl.dll - 3.0.2",
                                        "Flurl.Http.dll - 3.2.0",
                                        "INIFileParser.dll - 2.5.2",
                                        "LZMA.dll - 9.10 beta",
                                        "Microsoft.WindowsAPICodePack.dll - 1.1.0.0",
                                        "Microsoft.WindowsAPICodePack.Shell.dll - 1.1.0.0",
                                        "Microsoft.WindowsAPICodePack.ShellExtensions.dll - 1.1.0.0",
                                        "Nancy.dll - 2.0.0",
                                        "Nancy.Hosting.Self.dll - 2.0.0",
                                        "Newtonsoft.Json.dll - 13.0.1",
                                        "System.Runtime.InteropServices.RuntimeInformation.dll - 4.6.24705.01. " +
                                        "Commit Hash: 4d1af962ca0fede10beb01d197367c2f90e92c97",
                                        "System.ValueTuple.dll - 4.6.26515.06 @BuiltBy: dlab-DDVSOWINAGE059 " +
                                        "@Branch: release/2.1 @SrcCode: https://github.com/dotnet/corefx/tree/30ab651fcb4354552bd4891619a0bdd81e0ebdbf",
                                        "WindowsFirewallHelper.dll - 2.1.4.81"
                                    };

                                    List <string> Missing_File_List = new List <string>();

                                    foreach (string File_String in File_List)
                                    {
                                        string[] Split_File_Version = File_String.Split(new string[] { " - " }, StringSplitOptions.None);

                                        if (!File.Exists(Path.Combine(Directory.GetCurrentDirectory(), Split_File_Version[0])))
                                        {
                                            Missing_File_List.Add(Split_File_Version[0] + " - " + Translations.Database("Program_TextBox_File_NotFound"));
                                        }
                                        else
                                        {
                                            try
                                            {
                                                FileVersionInfo Version_Info  = FileVersionInfo.GetVersionInfo(Split_File_Version[0]);
                                                string[]        Version_Split = Version_Info.ProductVersion.Split('+');
                                                string          File_Version  = Version_Split[0];

                                                if (File_Version == "")
                                                {
                                                    Missing_File_List.Add(Split_File_Version[0] + " - " + Translations.Database("Program_TextBox_File_Invalid"));
                                                }
                                                else
                                                {
                                                    if (!HardwareInfo.CheckArchitectureFile(Split_File_Version[0]))
                                                    {
                                                        Missing_File_List.Add(Split_File_Version[0] + " - " + Translations.Database("Program_TextBox_File_Invalid_CPU"));
                                                    }
                                                    else
                                                    {
                                                        if (File_Version != Split_File_Version[1])
                                                        {
                                                            Missing_File_List.Add(Split_File_Version[0] + " - " + Translations.Database("Program_TextBox_File_Invalid_Version") +
                                                                                  "(" + Split_File_Version[1] + " != " + File_Version + ")");
                                                        }
                                                    }
                                                }
                                            }
                                            catch
                                            {
                                                Missing_File_List.Add(Split_File_Version[0] + " - " + Translations.Database("Program_TextBox_File_Invalid"));
                                            }
                                        }
                                    }

                                    if (Missing_File_List.Count != 0)
                                    {
                                        string Message_Display = Translations.Database("Program_TextBox_File_Invalid_Start");

                                        foreach (string File_String in Missing_File_List)
                                        {
                                            Message_Display += "• " + File_String + "\n";
                                        }

                                        FunctionStatus.LauncherForceClose = true;
                                        MessageBox.Show(null, Message_Display, "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    }
                                }

                                if (FunctionStatus.LauncherForceClose)
                                {
                                    FunctionStatus.ErrorCloseLauncher("Closing From Missing .dll Files Check", LauncherMustRestart);
                                }
                                else
                                {
                                    Start();
                                }
                            }
                            else
                            {
                                MessageBox.Show(null, Translations.Database("Program_TextBox_SBRWIsRunning"),
                                                "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            }
                        }
                        finally
                        {
                            No_Java.Close();
                            No_Java.Dispose();
                        }
                    }
                }
            }
        }
Example #2
0
        static void Main()
        {
            bool mono  = DetectLinux.MonoDetected();
            bool wine  = DetectLinux.WineDetected();
            bool linux = DetectLinux.NativeLinuxDetected();

            Directory.SetCurrentDirectory(Path.GetDirectoryName(Application.ExecutablePath));

            if (Self.isTempFolder(Directory.GetCurrentDirectory()))
            {
                MessageBox.Show(null, "Please, extract me and my DLL files before executing...", "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                Environment.Exit(0);
            }

            if (!Directory.Exists("Languages"))
            {
                Directory.CreateDirectory("Languages");
            }

            try {
                File.Delete("Languages/Default.lng");
                File.WriteAllText("Languages/Default.lng", ExtractResource.AsString("GameLauncher.Language.Default.lng"));
            }
            catch { }

            try {
                File.Delete(Directory.GetCurrentDirectory() + "\\tempname.zip");
            } catch { }

            if (!File.Exists("LZMA.dll"))
            {
                File.WriteAllBytes("LZMA.dll", ExtractResource.AsByte("GameLauncher.LZMA.LZMA.dll"));
            }

            if (!linux && !File.Exists("discord-rpc.dll"))
            {
                File.WriteAllBytes("discord-rpc.dll", ExtractResource.AsByte("GameLauncher.Discord.discord-rpc.dll"));
            }

            if (linux && !File.Exists("libdiscord-rpc.so"))
            {
                File.WriteAllBytes("libdiscord-rpc.so", ExtractResource.AsByte("GameLauncher.Discord.libdiscord-rpc.so"));
            }

            if (File.Exists("GameLauncherUpdater.exe"))
            {
                File.Delete("GameLauncherUpdater.exe");
            }

            try {
                File.Delete("GL_Update.exe");
                File.WriteAllBytes("GL_Update.exe", ExtractResource.AsByte("GameLauncher.Updater.GL_Update.exe"));
            } catch { }

            if (!File.Exists("servers.txt"))
            {
                try {
                    File.Create("servers.txt");
                } catch { }
            }

            if (Debugger.IsAttached)
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new mainScreen());
            }
            else
            {
                if (NFSW.isNFSWRunning())
                {
                    MessageBox.Show(null, "An instance of Need for Speed: World is already running", "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    Process.GetProcessById(Process.GetCurrentProcess().Id).Kill();
                }

                Mutex mutex = new Mutex(false, "GameLauncherNFSW-MeTonaTOR");
                try {
                    if (mutex.WaitOne(0, false))
                    {
                        String[]      files        = { "Newtonsoft.Json.dll", "INIFileParser.dll", "Microsoft.WindowsAPICodePack.dll", "Microsoft.WindowsAPICodePack.Shell.dll" };
                        List <string> missingfiles = new List <string>();

                        foreach (string file in files)
                        {
                            if (!File.Exists(file))
                            {
                                missingfiles.Add(file);
                            }
                        }

                        if (missingfiles.Count != 0)
                        {
                            string message = "Cannot launch GameLauncher. The following files are missing:\n\n";

                            foreach (string file in missingfiles)
                            {
                                message += "• " + file + "\n";
                            }

                            message += "\nCurrent directory: " + Directory.GetCurrentDirectory();

                            MessageBox.Show(null, message, "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            Environment.Exit(1);
                        }

                        Application.EnableVisualStyles();
                        Application.SetCompatibleTextRenderingDefault(false);
                        Application.Run(new mainScreen());
                    }
                    else
                    {
                        MessageBox.Show(null, "An instance of the application is already running.", "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                } finally {
                    if (mutex != null)
                    {
                        mutex.Close();
                        mutex = null;
                    }
                }
            }
        }
        static void Main()
        {
            int  SysVersion = (int)Environment.OSVersion.Platform;
            bool mono       = DetectLinux.MonoDetected();
            bool wine       = DetectLinux.WineDetected();
            bool linux      = DetectLinux.NativeLinuxDetected();

            try {
            } catch {
                MessageBox.Show("This should fake antivirus :v");
            }

            /*if(Environment.OSVersion.Version.Major <= 5 && !linux) {
             *  MessageBox.Show(null, "Windows XP Support has been terminated. Please upgrade your Operating System to 'Vista' or newer.", "GameLauncher.exe", MessageBoxButtons.OK, MessageBoxIcon.Warning);
             *  Environment.Exit(Environment.ExitCode);
             * }*/

            Directory.SetCurrentDirectory(Path.GetDirectoryName(Application.ExecutablePath));

            if (!Directory.Exists("Languages"))
            {
                Directory.CreateDirectory("Languages");
            }

            try {
                File.Delete("Languages/Default.lng");
                File.WriteAllText("Languages/Default.lng", ExtractResource.AsString("GameLauncher.Language.Default.lng"));
            }
            catch { }

            try {
                File.Delete(Directory.GetCurrentDirectory() + "\\tempname.zip");
            } catch { }

            if (linux)
            {
                MessageBox.Show(null, "Native Linux support is still under alpha stage. Therefore, launcher or game could crash.", "GameLauncher.exe", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else if (mono == true)
            {
                MessageBox.Show(null, "Mono support is still under alpha stage. Therefore, launcher could not launch.", "GameLauncher.exe", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

            if (!File.Exists("LZMA.dll"))
            {
                File.WriteAllBytes("LZMA.dll", ExtractResource.AsByte("GameLauncher.LZMA.LZMA.dll"));
            }

            if (!linux && !File.Exists("discord-rpc.dll"))
            {
                File.WriteAllBytes("discord-rpc.dll", ExtractResource.AsByte("GameLauncher.Discord.discord-rpc.dll"));
            }

            if (linux && !File.Exists("libdiscord-rpc.so"))
            {
                File.WriteAllBytes("libdiscord-rpc.so", ExtractResource.AsByte("GameLauncher.Discord.libdiscord-rpc.so"));
            }

            if (File.Exists("GameLauncherUpdater.exe"))
            {
                File.Delete("GameLauncherUpdater.exe");
            }

            try {
                File.Delete("GL_Update.exe");
                File.WriteAllBytes("GL_Update.exe", ExtractResource.AsByte("GameLauncher.Updater.GL_Update.exe"));
            } catch { }

            if (!File.Exists("servers.txt"))
            {
                try {
                    File.Create("servers.txt");
                } catch { }
            }

            if (Debugger.IsAttached)
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new mainScreen());
            }
            else
            {
                if (NFSW.isNFSWRunning())
                {
                    MessageBox.Show(null, "An instance of Need for Speed: World is already running", "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    Process.GetProcessById(Process.GetCurrentProcess().Id).Kill();
                }

                Mutex mutex = new Mutex(false, "GameLauncherNFSW-MeTonaTOR");
                try {
                    if (mutex.WaitOne(0, false))
                    {
                        String[]      files        = { "Newtonsoft.Json.dll", "LZMA.dll" };
                        List <string> missingfiles = new List <string>();

                        foreach (string file in files)
                        {
                            if (!File.Exists(file))
                            {
                                missingfiles.Add(file);
                            }
                        }

                        if (missingfiles.Count != 0)
                        {
                            string message = "Cannot launch GameLauncher. The following files are missing:\n\n";

                            foreach (string file in missingfiles)
                            {
                                message += "• " + file + "\n";
                            }

                            message += "\nCurrent directory: " + Directory.GetCurrentDirectory();
                            message += "\nYou will be moved to the project page for re-download.";

                            MessageBox.Show(null, message, "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            Process.Start(@"https://github.com/SoapboxRaceWorld/GameLauncher_NFSW/releases");
                            Environment.Exit(1);
                        }

                        Application.EnableVisualStyles();
                        Application.SetCompatibleTextRenderingDefault(false);
                        Application.Run(new mainScreen());
                    }
                    else
                    {
                        MessageBox.Show(null, "An instance of the application is already running.", "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                } finally {
                    if (mutex != null)
                    {
                        mutex.Close();
                        mutex = null;
                    }
                }
            }
        }
Example #4
0
        internal static void Main()
        {
            Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.Idle;

            Console.WriteLine("Application path: " + Path.GetDirectoryName(Application.ExecutablePath));

            /*GPU getinfo = null;
             *
             * switch(GPUHelper.getManufacturer()) {
             *  case GPUHelper.GPUManufacturer.NVIDIA:
             *      getinfo = new NVIDIA();
             *      break;
             *  case GPUHelper.GPUManufacturer.AMD:
             *      getinfo = new AMD();
             *      break;
             *  case GPUHelper.GPUManufacturer.INTEL:
             *      getinfo = new INTEL();
             *      break;
             *  default:
             *      getinfo = null;
             *      break;
             * }
             *
             * MeTonaTOR.MessageBox.Show(getinfo.DriverVersion());*/

            if (!Self.hasWriteAccessToFolder(Path.GetDirectoryName(Application.ExecutablePath)))
            {
                MessageBox.Show("This application requires admin priviledge. Restarting...");
                Self.runAsAdmin();
            }

            IniFile _settingFile = new IniFile("Settings.ini");

            if (!string.IsNullOrEmpty(_settingFile.Read("DisableVerifyHash")))
            {
                _settingFile.Write("DisableVerifyHash", "1");
            }

            if (!string.IsNullOrEmpty(_settingFile.Read("InstallationDirectory")))
            {
                Console.WriteLine("Game path: " + _settingFile.Read("InstallationDirectory"));

                if (!Self.hasWriteAccessToFolder(_settingFile.Read("InstallationDirectory")))
                {
                    MessageBox.Show("This application requires admin priviledge. Restarting...");
                    Self.runAsAdmin();
                }
            }

            File.Delete("log.txt");

            Log.StartLogging();

            //StaticConfiguration.DisableErrorTraces = false;

            Log.Debug("Setting up current directory: " + Path.GetDirectoryName(Application.ExecutablePath));
            Directory.SetCurrentDirectory(Path.GetDirectoryName(Application.ExecutablePath));

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(true);

            Log.Debug("Checking current directory");

            if (Self.isTempFolder(Directory.GetCurrentDirectory()))
            {
                MessageBox.Show(null, "Please, extract me and my DLL files before executing...", "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                Environment.Exit(0);
            }

            if (!File.Exists("GameLauncherUpdater.exe"))
            {
                Log.Debug("Starting GameLauncherUpdater downloader");
                try {
                    using (WebClientWithTimeout wc = new WebClientWithTimeout()) {
                        wc.DownloadFileCompleted += (object sender, AsyncCompletedEventArgs e) => {
                            if (new FileInfo("GameLauncherUpdater.exe").Length == 0)
                            {
                                File.Delete("GameLauncherUpdater.exe");
                            }
                        };
                        wc.DownloadFileAsync(new Uri(Self.mainserver + "/files/GameLauncherUpdater.exe"), "GameLauncherUpdater.exe");
                    }
                } catch (Exception ex) {
                    Log.Debug("Failed to download updater. " + ex.Message);
                }
            }

            if (!File.Exists("servers.json"))
            {
                try {
                    File.WriteAllText("servers.json", "[]");
                } catch { /* ignored */ }
            }

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            if (Debugger.IsAttached)
            {
                Log.Debug("Checking Proxy");
                ServerProxy.Instance.Start();
                Log.Debug("Starting MainScreen");
                Application.Run(new MainScreen());
            }
            else
            {
                if (NFSW.isNFSWRunning())
                {
                    MessageBox.Show(null, "An instance of Need for Speed: World is already running", "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    Process.GetProcessById(Process.GetCurrentProcess().Id).Kill();
                }

                var mutex = new Mutex(false, "GameLauncherNFSW-MeTonaTOR");
                try {
                    if (mutex.WaitOne(0, false))
                    {
                        string[] files =
                        {
                            "DiscordRPC.dll - 1.0.0.0",
                            "Flurl.dll - 2.8.2",
                            "Flurl.Http.dll - 2.4.2",
                            "INIFileParser.dll - 2.5.2",
                            "LZMA.dll - 9.10 beta",
                            "Microsoft.WindowsAPICodePack.dll - 1.1.0.0",
                            "Microsoft.WindowsAPICodePack.Shell.dll - 1.1.0.0",
                            "Microsoft.WindowsAPICodePack.ShellExtensions.dll - 1.1.0.0",
                            "Nancy.dll - 2.0.0",
                            "Nancy.Hosting.Self.dll - 2.0.0",
                            "Newtonsoft.Json.dll - 12.0.3",
                            "SharpRaven.dll - 2.4.0",
                            "System.Runtime.InteropServices.RuntimeInformation.dll - 4.6.24705.01. Commit Hash: 4d1af962ca0fede10beb01d197367c2f90e92c97"
                        };

                        var missingfiles = new List <string>();

                        if (!DetectLinux.LinuxDetected())  //MONO Hates that...
                        {
                            foreach (var file in files)
                            {
                                var splitFileVersion = file.Split(new string[] { " - " }, StringSplitOptions.None);

                                if (!File.Exists(Directory.GetCurrentDirectory() + "\\" + splitFileVersion[0]))
                                {
                                    missingfiles.Add(splitFileVersion[0] + " - Not Found");
                                }
                                else
                                {
                                    try {
                                        var      versionInfo  = FileVersionInfo.GetVersionInfo(splitFileVersion[0]);
                                        string[] versionsplit = versionInfo.ProductVersion.Split('+');
                                        string   version      = versionsplit[0];

                                        if (version == "")
                                        {
                                            missingfiles.Add(splitFileVersion[0] + " - Invalid File");
                                        }
                                        else
                                        {
                                            if (Self.CheckArchitectureFile(splitFileVersion[0]) == false)
                                            {
                                                missingfiles.Add(splitFileVersion[0] + " - Wrong Architecture");
                                            }
                                            else
                                            {
                                                if (version != splitFileVersion[1])
                                                {
                                                    missingfiles.Add(splitFileVersion[0] + " - Invalid Version (" + splitFileVersion[1] + " != " + version + ")");
                                                }
                                            }
                                        }
                                    } catch {
                                        missingfiles.Add(splitFileVersion[0] + " - Invalid File");
                                    }
                                }
                            }
                        }
                        if (missingfiles.Count != 0)
                        {
                            var message = "Cannot launch GameLauncher. The following files are invalid:\n\n";

                            foreach (var file in missingfiles)
                            {
                                message += "• " + file + "\n";
                            }

                            MessageBox.Show(null, message, "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        else
                        {
                            Log.Debug("Checking Proxy");
                            ServerProxy.Instance.Start();

                            Application.ThreadException += new ThreadExceptionEventHandler(ThreadExceptionEventHandler);
                            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionEventHandler);

                            Log.Debug("Starting MainScreen");
                            Application.Run(new MainScreen());
                        }
                    }
                    else
                    {
                        MessageBox.Show(null, "An instance of Launcher is already running.", "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                } finally {
                    mutex.Close();
                    mutex = null;
                }
            }
        }
Example #5
0
        private static void Main2(Arguments args)
        {
            Thread.CurrentThread.CurrentCulture   = CultureInfo.CreateSpecificCulture("en-US");
            Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture("en-US");

            if (UriScheme.IsCommandLineArgumentsInstalled())
            {
                UriScheme.InstallCommandLineArguments(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), AppDomain.CurrentDomain.FriendlyName));
                if (args.Parse != null)
                {
                    new UriScheme(args.Parse);
                }
            }

            try {
                new WebClient().DownloadData("http://l.mtntr.pl/generate_204.php");
            } catch (Exception) {
                MessageBox.Show("There's no internet connection, launcher might crash");
            }

            IniFile _settingFile = new IniFile("Settings.ini");

            if (!(_settingFile.KeyExists("PatchesApplied")))
            {
                String _OS = (string)Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Windows NT\\CurrentVersion").GetValue("productName");
                if (_OS.Contains("Windows 7"))
                {
                    if (Self.getInstalledHotFix("KB3020369") == false || Self.getInstalledHotFix("KB3125574") == false)
                    {
                        String messageBoxPopupKB = String.Empty;
                        messageBoxPopupKB  = "Hey Windows 7 User, in order to play on this server, we need to make additional tweaks to your system.\n";
                        messageBoxPopupKB += "We must make sure you have those Windows Update packages installed:\n\n";

                        if (Self.getInstalledHotFix("KB3020369") == false)
                        {
                            messageBoxPopupKB += "- Update KB3020369\n";
                        }
                        if (Self.getInstalledHotFix("KB3125574") == false)
                        {
                            messageBoxPopupKB += "- Update KB3125574\n";
                        }

                        messageBoxPopupKB += "\nAditionally, we must add a value to the registry:\n";

                        messageBoxPopupKB += "- HKLM/SYSTEM/CurrentControlSet/Control/SecurityProviders\n/SCHANNEL/Protocols/TLS 1.2/Client\n";
                        messageBoxPopupKB += "- Value: DisabledByDefault -> 0\n\n";

                        messageBoxPopupKB += "Would you like to add those values?";
                        DialogResult replyPatchWin7 = MessageBox.Show(null, messageBoxPopupKB, "GameLauncherReborn", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

                        if (replyPatchWin7 == DialogResult.Yes)
                        {
                            RegistryKey key = Registry.LocalMachine.CreateSubKey(@"SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client");
                            key.SetValue("DisabledByDefault", 0x0);

                            MessageBox.Show(null, "Registry option set, Remember that the following patch might work after a system reboot", "GameLauncherReborn", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        else
                        {
                            MessageBox.Show(null, "Roger that, There will be some issues connecting to the servers.", "GameLauncherReborn", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }

                        _settingFile.Write("PatchesApplied", "1");
                    }
                }
            }

            Console.WriteLine("Application path: " + Path.GetDirectoryName(Application.ExecutablePath));

            if (!Self.hasWriteAccessToFolder(Path.GetDirectoryName(Application.ExecutablePath)))
            {
                MessageBox.Show("This application requires admin priviledge");
            }

            if (DetectLinux.LinuxDetected())
            {
                if (!_settingFile.KeyExists("InstallationDirectory"))
                {
                    _settingFile.Write("InstallationDirectory", "GameFiles");
                }

                if (!_settingFile.KeyExists("CDN"))
                {
                    try {
                        List <CDNObject>     CDNList = new List <CDNObject>();
                        WebClientWithTimeout wc3     = new WebClientWithTimeout();
                        String _slresponse           = wc3.DownloadString(Self.CDNUrlList);
                        CDNList = JsonConvert.DeserializeObject <List <CDNObject> >(_slresponse);
                        _settingFile.Write("CDN", CDNList.First().url);
                    } catch {
                        _settingFile.Write("CDN", "http://cdn.worldunited.gg/gamefiles/packed/");
                    }
                }
            }

            if (!string.IsNullOrEmpty(_settingFile.Read("InstallationDirectory")))
            {
                Console.WriteLine("Game path: " + _settingFile.Read("InstallationDirectory"));

                if (!Self.hasWriteAccessToFolder(_settingFile.Read("InstallationDirectory")))
                {
                    MessageBox.Show("This application requires admin priviledge. Restarting...");
                }
            }

            File.Delete("communication.log");
            File.Delete("launcher.log");

            Log.StartLogging();
            Log.Debug("GameLauncher " + Application.ProductVersion);

            if (_settingFile.KeyExists("InstallationDirectory"))
            {
                if (!File.Exists(_settingFile.Read("InstallationDirectory")))
                {
                    Directory.CreateDirectory(_settingFile.Read("InstallationDirectory"));
                }
            }

            //StaticConfiguration.DisableErrorTraces = false;

            Log.Debug("Setting up current directory: " + Path.GetDirectoryName(Application.ExecutablePath));
            Directory.SetCurrentDirectory(Path.GetDirectoryName(Application.ExecutablePath));

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(true);

            Log.Debug("Checking current directory");

            if (Self.isTempFolder(Directory.GetCurrentDirectory()))
            {
                MessageBox.Show(null, "Please, extract me and my DLL files before executing...", "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                Environment.Exit(0);
            }

            String[] removeFiles = new String[] { "GameLauncherUpdater.exe", "Update.exe", "update.sbrw" };

            foreach (string file in removeFiles)
            {
                if (File.Exists(file))
                {
                    File.Delete(file);
                }
            }

            //Also remove new one on next launch.
            if (File.Exists("Update.exe"))
            {
                File.Delete("GameLauncherUpdater.exe");
            }

            if (!File.Exists("servers.json"))
            {
                try {
                    File.WriteAllText("servers.json", "[]");
                } catch { /* ignored */ }
            }

            if (Properties.Settings.Default.IsRestarting)
            {
                Properties.Settings.Default.IsRestarting = false;
                Properties.Settings.Default.Save();
                Thread.Sleep(3000);
            }

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            if (Debugger.IsAttached)
            {
                Log.Debug("Checking Proxy");
                ServerProxy.Instance.Start();
                Log.Debug("Starting MainScreen");
                Application.Run(new MainScreen());
            }
            else
            {
                if (NFSW.isNFSWRunning())
                {
                    MessageBox.Show(null, "An instance of Need for Speed: World is already running", "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    Process.GetProcessById(Process.GetCurrentProcess().Id).Kill();
                }

                var mutex = new Mutex(false, "GameLauncherNFSW-MeTonaTOR");
                try {
                    if (mutex.WaitOne(0, false))
                    {
                        string[] files =
                        {
                            "CommandLine.dll - 2.8.0",
                            "DiscordRPC.dll - 1.0.150.0",
                            "Flurl.dll - 2.8.2",
                            "Flurl.Http.dll - 2.4.2",
                            "INIFileParser.dll - 2.5.2",
                            "Microsoft.WindowsAPICodePack.dll - 1.1.0.0",
                            "Microsoft.WindowsAPICodePack.Shell.dll - 1.1.0.0",
                            "Microsoft.WindowsAPICodePack.ShellExtensions.dll - 1.1.0.0",
                            "Nancy.dll - 2.0.0",
                            "Nancy.Hosting.Self.dll - 2.0.0",
                            "Newtonsoft.Json.dll - 12.0.3",
                            "System.Runtime.InteropServices.RuntimeInformation.dll - 4.6.24705.01. Commit Hash: 4d1af962ca0fede10beb01d197367c2f90e92c97"
                        };

                        var missingfiles = new List <string>();

                        if (!DetectLinux.LinuxDetected())  //MONO Hates that...
                        {
                            foreach (var file in files)
                            {
                                var splitFileVersion = file.Split(new string[] { " - " }, StringSplitOptions.None);

                                if (!File.Exists(Directory.GetCurrentDirectory() + "\\" + splitFileVersion[0]))
                                {
                                    missingfiles.Add(splitFileVersion[0] + " - Not Found");
                                }
                                else
                                {
                                    try {
                                        var      versionInfo  = FileVersionInfo.GetVersionInfo(splitFileVersion[0]);
                                        string[] versionsplit = versionInfo.ProductVersion.Split('+');
                                        string   version      = versionsplit[0];

                                        if (version == "")
                                        {
                                            missingfiles.Add(splitFileVersion[0] + " - Invalid File");
                                        }
                                        else
                                        {
                                            if (Self.CheckArchitectureFile(splitFileVersion[0]) == false)
                                            {
                                                missingfiles.Add(splitFileVersion[0] + " - Wrong Architecture");
                                            }
                                            else
                                            {
                                                if (version != splitFileVersion[1])
                                                {
                                                    missingfiles.Add(splitFileVersion[0] + " - Invalid Version (" + splitFileVersion[1] + " != " + version + ")");
                                                }
                                            }
                                        }
                                    } catch {
                                        missingfiles.Add(splitFileVersion[0] + " - Invalid File");
                                    }
                                }
                            }
                        }
                        if (missingfiles.Count != 0)
                        {
                            var message = "Cannot launch GameLauncher. The following files are invalid:\n\n";

                            foreach (var file in missingfiles)
                            {
                                message += "• " + file + "\n";
                            }

                            MessageBox.Show(null, message, "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        else
                        {
                            Log.Debug("Checking Proxy");
                            ServerProxy.Instance.Start();

                            Log.Debug("Starting MainScreen");
                            Application.Run(new MainScreen());
                        }
                    }
                    else
                    {
                        MessageBox.Show(null, "An instance of Launcher is already running.", "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                } finally {
                    mutex.Close();
                    mutex = null;
                }
            }
        }
Example #6
0
        internal static void Main()
        {
            File.Delete("log.txt");

            Log.StartLogging();

            Log.Debug("Setting up current directory: " + Path.GetDirectoryName(Application.ExecutablePath));
            Directory.SetCurrentDirectory(Path.GetDirectoryName(Application.ExecutablePath));

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(true);

            Form SplashScreen2 = null;

            Log.Debug("Checking current directory");

            if (Self.isTempFolder(Directory.GetCurrentDirectory()))
            {
                MessageBox.Show(null, "Please, extract me and my DLL files before executing...", "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                Environment.Exit(0);
            }

            if (!File.Exists("GameLauncherUpdater.exe"))
            {
                Log.Debug("Starting GameLauncherUpdater downloader");
                try {
                    using (WebClientWithTimeout wc = new WebClientWithTimeout()) {
                        wc.DownloadFileCompleted += (object sender, AsyncCompletedEventArgs e) => {
                            if (new FileInfo("GameLauncherUpdater.exe").Length == 0)
                            {
                                File.Delete("GameLauncherUpdater.exe");
                            }
                        };
                        wc.DownloadFileAsync(new Uri(Self.mainserver + "/files/GameLauncherUpdater.exe"), "GameLauncherUpdater.exe");
                    }
                } catch (Exception ex) {
                    Log.Debug("Failed to download updater. " + ex.Message);
                }
            }

            if (!File.Exists("servers.json"))
            {
                try {
                    File.WriteAllText("servers.json", "[]");
                } catch { /* ignored */ }
            }

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            if (Debugger.IsAttached)
            {
                Log.Debug("Checking Proxy");
                ServerProxy.Instance.Start();
                Log.Debug("Starting MainScreen");
                Application.Run(new MainScreen(SplashScreen2));
            }
            else
            {
                if (NFSW.isNFSWRunning())
                {
                    MessageBox.Show(null, "An instance of Need for Speed: World is already running", "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    Process.GetProcessById(Process.GetCurrentProcess().Id).Kill();
                }

                var mutex = new Mutex(false, "GameLauncherNFSW-MeTonaTOR");
                try {
                    if (mutex.WaitOne(0, false))
                    {
                        string[] files =
                        {
                            "SharpRaven.dll - 2.4.0",
                            "Flurl.dll - 2.8.0",
                            "Flurl.Http.dll - 2.3.2",
                            "INIFileParser.dll - 2.5.2",
                            "Microsoft.WindowsAPICodePack.dll - 1.1.0.0",
                            "Microsoft.WindowsAPICodePack.Shell.dll - 1.1.0.0",
                            "Nancy.dll - 1.4.4",
                            "Nancy.Hosting.Self.dll - 1.4.1",
                            "Newtonsoft.Json.dll - 11.0.2",
                        };

                        var missingfiles = new List <string>();

                        if (!DetectLinux.LinuxDetected())  //MONO Hates that...
                        {
                            foreach (var file in files)
                            {
                                var splitFileVersion = file.Split(new string[] { " - " }, StringSplitOptions.None);

                                if (!File.Exists(Directory.GetCurrentDirectory() + "\\" + splitFileVersion[0]))
                                {
                                    missingfiles.Add(splitFileVersion[0] + " - Not Found");
                                }
                                else
                                {
                                    try {
                                        var      versionInfo  = FileVersionInfo.GetVersionInfo(splitFileVersion[0]);
                                        string[] versionsplit = versionInfo.ProductVersion.Split('+');
                                        string   version      = versionsplit[0];

                                        if (version == "")
                                        {
                                            missingfiles.Add(splitFileVersion[0] + " - Invalid File");
                                        }
                                        else
                                        {
                                            if (Self.CheckArchitectureFile(splitFileVersion[0]) == false)
                                            {
                                                missingfiles.Add(splitFileVersion[0] + " - Wrong Architecture");
                                            }
                                            else
                                            {
                                                if (version != splitFileVersion[1])
                                                {
                                                    missingfiles.Add(splitFileVersion[0] + " - Invalid Version (" + splitFileVersion[1] + " != " + version + ")");
                                                }
                                            }
                                        }
                                    } catch {
                                        missingfiles.Add(splitFileVersion[0] + " - Invalid File");
                                    }
                                }
                            }
                        }
                        if (missingfiles.Count != 0)
                        {
                            var message = "Cannot launch GameLauncher. The following files are invalid:\n\n";

                            foreach (var file in missingfiles)
                            {
                                message += "• " + file + "\n";
                            }

                            MessageBox.Show(null, message, "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        else
                        {
                            Log.Debug("Checking Proxy");
                            ServerProxy.Instance.Start();

                            Application.ThreadException += new ThreadExceptionEventHandler(ThreadExceptionEventHandler);
                            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionEventHandler);

                            Log.Debug("Starting MainScreen");
                            Application.Run(new MainScreen(SplashScreen2));
                        }
                    }
                    else
                    {
                        MessageBox.Show(null, "An instance of the application is already running.", "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                } finally {
                    mutex.Close();
                    mutex = null;
                }
            }
        }
        internal static void Main()
        {
            var linux = DetectLinux.NativeLinuxDetected();

            Directory.SetCurrentDirectory(Path.GetDirectoryName(Application.ExecutablePath) ?? throw new InvalidOperationException());

            if (Self.isTempFolder(Directory.GetCurrentDirectory()))
            {
                MessageBox.Show(null, "Please, extract me and my DLL files before executing...", "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                Environment.Exit(0);
            }

            if (!Directory.Exists("Languages"))
            {
                Directory.CreateDirectory("Languages");
            }

            try
            {
                File.Delete("Languages/Default.lng");
                File.WriteAllText("Languages/Default.lng", ExtractResource.AsString("GameLauncher.Language.Default.lng"));
            }
            catch
            {
                // ignored
            }

            try
            {
                File.Delete(Directory.GetCurrentDirectory() + "\\tempname.zip");
            }
            catch
            {
                // ignored
            }

            if (!File.Exists("LZMA.dll"))
            {
                File.WriteAllBytes("LZMA.dll", ExtractResource.AsByte("GameLauncher.LZMA.LZMA.dll"));
            }

            if (!linux && !File.Exists("discord-rpc.dll"))
            {
                File.WriteAllBytes("discord-rpc.dll", ExtractResource.AsByte("GameLauncher.Discord.discord-rpc.dll"));
            }

            if (linux && !File.Exists("libdiscord-rpc.so"))
            {
                File.WriteAllBytes("libdiscord-rpc.so", ExtractResource.AsByte("GameLauncher.Discord.libdiscord-rpc.so"));
            }

            if (File.Exists("GL_Update.exe"))
            {
                File.Delete("GL_Update.exe");
            }

            if (!File.Exists("GameLauncherUpdater.exe"))
            {
                try
                {
                    File.WriteAllBytes("GameLauncherUpdater.exe", new WebClientWithTimeout().DownloadData("http://launcher.soapboxrace.world/GameLauncherUpdater.exe"));
                }
                catch
                {
                    // ignored
                }
            }
            if (!File.Exists("servers.json"))
            {
                try
                {
                    File.WriteAllText("servers.json", "[]");
                }
                catch
                {
                    // ignored
                }
            }

            if (Debugger.IsAttached)
            {
                ServerProxy.Instance.Start();
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new MainScreen());
            }
            else
            {
                if (NFSW.isNFSWRunning())
                {
                    MessageBox.Show(null, "An instance of Need for Speed: World is already running", "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    Process.GetProcessById(Process.GetCurrentProcess().Id).Kill();
                }

                var mutex = new Mutex(false, "GameLauncherNFSW-MeTonaTOR");
                try
                {
                    if (mutex.WaitOne(0, false))
                    {
                        string[] files =
                        {
                            "Newtonsoft.Json.dll",
                            "INIFileParser.dll",
                            "Microsoft.WindowsAPICodePack.dll",
                            "Microsoft.WindowsAPICodePack.Shell.dll",
                            "Flurl.dll",
                            "Flurl.Http.dll",
                            "BlackListedServers.dat"
                        };
                        var missingfiles = new List <string>();

                        foreach (var file in files)
                        {
                            if (!File.Exists(file))
                            {
                                missingfiles.Add(file);
                            }
                        }

                        if (missingfiles.Count != 0)
                        {
                            var message = "Cannot launch GameLauncher. The following files are missing:\n\n";

                            foreach (var file in missingfiles)
                            {
                                message += "• " + file + "\n";
                            }

                            message += "\nCurrent directory: " + Directory.GetCurrentDirectory();

                            MessageBox.Show(null, message, "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            Environment.Exit(1);
                        }

                        ServerProxy.Instance.Start();

                        Application.EnableVisualStyles();
                        Application.SetCompatibleTextRenderingDefault(false);
                        Application.Run(new MainScreen());
                    }
                    else
                    {
                        MessageBox.Show(null, "An instance of the application is already running.", "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                finally
                {
                    mutex.Close();
                    mutex = null;
                }
            }
        }
Example #8
0
        private static void Main2(Arguments args)
        {
            if (!DetectLinux.LinuxDetected())
            {
                //Check if User has .NETFramework 4.6.2 or later Installed
                const string subkey = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\";

                using (var ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(subkey))
                {
                    if (ndpKey != null && ndpKey.GetValue("Release") != null && (int)ndpKey.GetValue("Release") >= 394802)
                    {
                        /* Check Up to Date Certificate Status */
                        try
                        {
                            WebClient update_data = new WebClient();
                            update_data.CancelAsync();
                            update_data.Headers.Add("user-agent", "GameLauncher " + Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)");
                            update_data.DownloadStringAsync(new Uri("http://crl.carboncrew.org/RCA-Info.json"));
                            update_data.DownloadStringCompleted += (sender, e) => {
                                JSONRootCA API = JsonConvert.DeserializeObject <JSONRootCA>(e.Result);

                                if (API.CN != null)
                                {
                                    Log.Info("CERTIFICATE STORE: Setting Common Name -> " + API.CN);
                                    CertificateStore.RootCACommonName = API.CN;
                                }

                                if (API.Subject != null)
                                {
                                    Log.Info("CERTIFICATE STORE: Setting Subject Name -> " + API.Subject);
                                    CertificateStore.RootCASubjectName = API.Subject;
                                }

                                if (API.Ids != null)
                                {
                                    foreach (IdsModel entries in API.Ids)
                                    {
                                        if (entries.Serial != null)
                                        {
                                            Log.Info("CERTIFICATE STORE: Setting Serial Number -> " + entries.Serial);
                                            CertificateStore.RootCASerial = entries.Serial;
                                        }
                                    }
                                }

                                if (API.File != null)
                                {
                                    foreach (FileModel entries in API.File)
                                    {
                                        if (entries.Name != null)
                                        {
                                            Log.Info("CERTIFICATE STORE: Setting Root CA File Name -> " + entries.Name);
                                            CertificateStore.RootCAFileName = entries.Name;
                                        }

                                        if (entries.Cer != null)
                                        {
                                            Log.Info("CERTIFICATE STORE: Setting Root CA File URL -> " + entries.Cer);
                                            CertificateStore.RootCAFileURL = entries.Cer;
                                        }
                                    }
                                }
                            };
                        }
                        catch
                        {
                            Log.Error("CERTIFICATE STORE: Unable to Retrive Latest Certificate Information");
                        }
                    }
                    else
                    {
                        DialogResult frameworkError = MessageBox.Show(null, "This application requires one of the following versions of the .NET Framework:\n" +
                                                                      " .NETFramework, Version=v4.6.2 \n\nDo you want to install this .NET Framework version now?", "GameLauncher.exe - This application could not be started.", MessageBoxButtons.YesNo, MessageBoxIcon.Error);

                        if (frameworkError == DialogResult.Yes)
                        {
                            Process.Start("https://dotnet.microsoft.com/download/dotnet-framework");
                        }
                        Process.GetProcessById(Process.GetCurrentProcess().Id).Kill();
                    }
                }
            }

            File.Delete("communication.log");
            File.Delete("launcher.log");

            Log.StartLogging();

            FileSettingsSave.NullSafeSettings();
            FileAccountSave.NullSafeAccount();

            Self.currentLanguage = CultureInfo.CurrentCulture.Name.Split('-')[0].ToUpper();
            Thread.CurrentThread.CurrentCulture   = CultureInfo.CreateSpecificCulture("en-US");
            Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture("en-US");

            if (UriScheme.IsCommandLineArgumentsInstalled())
            {
                UriScheme.InstallCommandLineArguments(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), AppDomain.CurrentDomain.FriendlyName));
                if (args.Parse != null)
                {
                    new UriScheme(args.Parse);
                }
            }

            if (EnableInsider.ShouldIBeAnInsider() == true)
            {
                Log.Build("INSIDER: GameLauncher " + Application.ProductVersion + "_" + EnableInsider.BuildNumber());
            }
            else
            {
                Log.Build("BUILD: GameLauncher " + Application.ProductVersion);
            }

            if (Properties.Settings.Default.IsRestarting)
            {
                Properties.Settings.Default.IsRestarting = false;
                Properties.Settings.Default.Save();
                Thread.Sleep(3000);
            }

            if (!DetectLinux.LinuxDetected())
            {
                //Windows Firewall Runner
                if (!string.IsNullOrEmpty(FileSettingsSave.FirewallStatus))
                {
                    string nameOfLauncher  = "SBRW - Game Launcher";
                    string localOfLauncher = Assembly.GetEntryAssembly().Location;

                    string nameOfUpdater  = "SBRW - Game Launcher Updater";
                    string localOfUpdater = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "GameLauncherUpdater.exe");

                    string groupKeyLauncher    = "Game Launcher for Windows";
                    string descriptionLauncher = "Soapbox Race World";

                    bool removeFirewallRule = false;
                    bool firstTimeRun       = false;

                    if (FileSettingsSave.FirewallStatus == "Not Excluded")
                    {
                        firstTimeRun = true;
                        FileSettingsSave.FirewallStatus = "Excluded";
                    }
                    else if (FileSettingsSave.FirewallStatus == "Reset")
                    {
                        removeFirewallRule = true;
                        FileSettingsSave.FirewallStatus = "Not Excluded";
                    }

                    FileSettingsSave.SaveSettings();

                    //Inbound & Outbound
                    FirewallHelper.DoesRulesExist(removeFirewallRule, firstTimeRun, nameOfLauncher, localOfLauncher, groupKeyLauncher, descriptionLauncher, FirewallProtocol.Any);
                    FirewallHelper.DoesRulesExist(removeFirewallRule, firstTimeRun, nameOfUpdater, localOfUpdater, groupKeyLauncher, descriptionLauncher, FirewallProtocol.Any);

                    //This Removes the Game File Exe From Firewall
                    //To Find the one that Adds the Exe To Firewall -> Search for `OnDownloadFinished()`
                    string CurrentGameFilesExePath = Path.Combine(FileSettingsSave.GameInstallation + "\\nfsw.exe");

                    if (File.Exists(CurrentGameFilesExePath) && removeFirewallRule == true)
                    {
                        string nameOfGame  = "SBRW - Game";
                        string localOfGame = CurrentGameFilesExePath;

                        string groupKeyGame    = "Need for Speed: World";
                        string descriptionGame = groupKeyGame;

                        //Inbound & Outbound
                        FirewallHelper.DoesRulesExist(removeFirewallRule, firstTimeRun, nameOfGame, localOfGame, groupKeyGame, descriptionGame, FirewallProtocol.Any);
                    }
                }
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(true);

            VisualsAPIChecker.PingAPIStatus();

            /* Set Launcher Directory */
            Log.Info("CORE: Setting up current directory: " + Path.GetDirectoryName(Application.ExecutablePath));
            Directory.SetCurrentDirectory(Path.GetDirectoryName(Application.ExecutablePath));

            if (!DetectLinux.LinuxDetected())
            {
                Log.Info("CORE: Checking current directory");

                switch (Self.CheckFolder(Directory.GetCurrentDirectory()))
                {
                case FolderType.IsTempFolder:
                    MessageBox.Show(null, "Please, extract me and my DLL files before executing...", "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    Environment.Exit(0);
                    break;

                case FolderType.IsUsersFolders:
                    MessageBox.Show(null, "Please, choose a different directory for the game launcher.\n\nSpecial Folders such as:" +
                                    "\n\nDownloads, Documents, Desktop, Videos, Music, OneDrive, or Any Type of User Folders" +
                                    "\n\nAre Disadvised", "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    Environment.Exit(0);
                    break;

                case FolderType.IsProgramFilesFolder:
                    MessageBox.Show(null, "Please, choose a different directory for the game launcher." +
                                    "\n\nSpecial Folders such as:\n\nProgram Files or Program Files (x86)\n\nAre Disadvised", "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    Environment.Exit(0);
                    break;

                case FolderType.IsWindowsFolder:
                    MessageBox.Show(null, "Please, choose a different directory for the game launcher." +
                                    "\n\nSpecial Folder such as:\n\nWindows\n\nAre Disadvised", "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    Environment.Exit(0);
                    break;
                }

                if (!Self.HasWriteAccessToFolder(Path.GetDirectoryName(Application.ExecutablePath)))
                {
                    MessageBox.Show("This application requires admin priviledge");
                }

                //Update this text file if a new GameLauncherUpdater.exe has been delployed - DavidCarbon
                try
                {
                    try
                    {
                        switch (APIStatusChecker.CheckStatus("http://api.github.com/repos/SoapboxRaceWorld/GameLauncherUpdater/releases/latest"))
                        {
                        case API.Online:
                            WebClient update_data = new WebClient();
                            update_data.CancelAsync();
                            update_data.Headers.Add("user-agent", "GameLauncher " + Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)");
                            update_data.DownloadStringAsync(new Uri("http://api.github.com/repos/SoapboxRaceWorld/GameLauncherUpdater/releases/latest"));
                            update_data.DownloadStringCompleted += (sender, e) => {
                                GitHubRelease GHAPI = JsonConvert.DeserializeObject <GitHubRelease>(e.Result);

                                if (GHAPI.TagName != null)
                                {
                                    Log.Info("LAUNCHER UPDATER: Setting Latest Version -> " + GHAPI.TagName);
                                    LatestUpdaterBuildVersion = GHAPI.TagName;
                                }
                                Log.Info("LAUNCHER UPDATER: Latest Version -> " + LatestUpdaterBuildVersion);
                            };
                            break;

                        default:
                            Log.Error("LAUNCHER UPDATER: Failed to Retrive Latest Updater Information from GitHub");
                            break;
                        }
                    }
                    catch
                    {
                        var GetLatestUpdaterBuildVersion = new WebClient().DownloadString(Self.secondstaticapiserver + "/Version.txt");
                        if (!string.IsNullOrEmpty(GetLatestUpdaterBuildVersion))
                        {
                            Log.Info("LAUNCHER UPDATER: Setting Latest Version -> " + GetLatestUpdaterBuildVersion);
                            LatestUpdaterBuildVersion = GetLatestUpdaterBuildVersion;
                        }
                    }
                    Log.Info("LAUNCHER UPDATER: Fail Safe Latest Version -> " + LatestUpdaterBuildVersion);
                }
                catch (Exception ex)
                {
                    Log.Error("LAUNCHER UPDATER: Failed to get new version file: " + ex.Message);
                }
            }

            if (!DetectLinux.LinuxDetected())
            {
                //Windows 7 Fix
                if ((string.IsNullOrEmpty(FileSettingsSave.Win7UpdatePatches) && WindowsProductVersion.GetWindowsNumber() == 6.1) || FileSettingsSave.Win7UpdatePatches == "0")
                {
                    if (Self.GetInstalledHotFix("KB3020369") == false || Self.GetInstalledHotFix("KB3125574") == false)
                    {
                        String messageBoxPopupKB = String.Empty;
                        messageBoxPopupKB  = "Hey Windows 7 User, we've detected a potential issue of some missing Updates that are required.\n";
                        messageBoxPopupKB += "We found that these Windows Update packages are showing as not installed:\n\n";

                        if (Self.GetInstalledHotFix("KB3020369") == false)
                        {
                            messageBoxPopupKB += "- Update KB3020369\n";
                        }
                        if (Self.GetInstalledHotFix("KB3125574") == false)
                        {
                            messageBoxPopupKB += "- Update KB3125574\n";
                        }

                        messageBoxPopupKB += "\nAditionally, we must add a value to the registry:\n";

                        messageBoxPopupKB += "- HKLM/SYSTEM/CurrentControlSet/Control/SecurityProviders\n/SCHANNEL/Protocols/TLS 1.2/Client\n";
                        messageBoxPopupKB += "- Value: DisabledByDefault -> 0\n\n";

                        messageBoxPopupKB += "Would you like to add those values?";
                        DialogResult replyPatchWin7 = MessageBox.Show(null, messageBoxPopupKB, "SBRW Launcher", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

                        if (replyPatchWin7 == DialogResult.Yes)
                        {
                            RegistryKey key = Registry.LocalMachine.CreateSubKey(@"SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client");
                            key.SetValue("DisabledByDefault", 0x0);

                            MessageBox.Show(null, "Registry option set, Remember that the changes may require a system reboot to take effect", "SBRW Launcher", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        else
                        {
                            MessageBox.Show(null, "Roger that, There may be some issues connecting to the servers.", "SBRW Launcher", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }

                        FileSettingsSave.Win7UpdatePatches = "1";
                        FileSettingsSave.SaveSettings();
                    }
                }

                if (!RedistributablePackage.IsInstalled(RedistributablePackageVersion.VC2015to2019x86))
                {
                    var result = MessageBox.Show(
                        "You do not have the 32-bit 2015-2019 VC++ Redistributable Package installed.\n \nThis will install in the Background\n \nThis may restart your computer. \n \nClick OK to install it.",
                        "Compatibility",
                        MessageBoxButtons.OKCancel,
                        MessageBoxIcon.Warning);

                    if (result != DialogResult.OK)
                    {
                        MessageBox.Show("The game will not be started.", "Compatibility", MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                        return;
                    }

                    var wc = new WebClient();
                    wc.DownloadFile("https://aka.ms/vs/16/release/VC_redist.x86.exe", "VC_redist.x86.exe");
                    var proc = Process.Start(new ProcessStartInfo
                    {
                        Verb      = "runas",
                        Arguments = "/quiet",
                        FileName  = "VC_redist.x86.exe"
                    });

                    if (proc == null)
                    {
                        MessageBox.Show("Failed to run package installer. The game will not be started.", "Compatibility", MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                        return;
                    }
                }

                if (Environment.Is64BitOperatingSystem == true)
                {
                    if (!RedistributablePackage.IsInstalled(RedistributablePackageVersion.VC2015to2019x64))
                    {
                        var result = MessageBox.Show(
                            "You do not have the 64-bit 2015-2019 VC++ Redistributable Package installed.\n \nThis will install in the Background\n \nThis may restart your computer. \n \nClick OK to install it.",
                            "Compatibility",
                            MessageBoxButtons.OKCancel,
                            MessageBoxIcon.Warning);

                        if (result != DialogResult.OK)
                        {
                            MessageBox.Show("The game will not be started.", "Compatibility", MessageBoxButtons.OK,
                                            MessageBoxIcon.Error);
                            return;
                        }

                        var wc = new WebClient();
                        wc.DownloadFile("https://aka.ms/vs/16/release/VC_redist.x64.exe", "VC_redist.x64.exe");
                        var proc = Process.Start(new ProcessStartInfo
                        {
                            Verb      = "runas",
                            Arguments = "/quiet",
                            FileName  = "VC_redist.x64.exe"
                        });

                        if (proc == null)
                        {
                            MessageBox.Show("Failed to run package installer. The game will not be started.", "Compatibility", MessageBoxButtons.OK,
                                            MessageBoxIcon.Error);
                            return;
                        }
                    }
                }
            }

            Console.WriteLine("Application path: " + Path.GetDirectoryName(Application.ExecutablePath));

            if (!string.IsNullOrEmpty(FileSettingsSave.GameInstallation))
            {
                if (!Self.HasWriteAccessToFolder(FileSettingsSave.GameInstallation))
                {
                    MessageBox.Show("This application requires admin priviledge. Restarting...");
                }
            }

            //INFO: this is here because this dll is necessary for downloading game files and I want to make it async.
            //Updated RedTheKitsune Code so it downloads the file if its missing. It also restarts the launcher if the user click on yes on Prompt. - DavidCarbon
            if (!File.Exists("LZMA.dll"))
            {
                try
                {
                    Log.Warning("CORE: Starting LZMA downloader");
                    using (WebClient wc = new WebClient())
                    {
                        wc.DownloadFileAsync(new Uri(Self.fileserver + "/LZMA.dll"), "LZMA.dll");
                    }

                    DialogResult restartApp = MessageBox.Show(null, "Downloaded Missing LZMA.dll File. \nPlease Restart Launcher, Thanks!", "GameLauncher Restart Required", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

                    if (restartApp == DialogResult.Yes)
                    {
                        Properties.Settings.Default.IsRestarting = true;
                        Properties.Settings.Default.Save();
                        Application.Restart();
                    }

                    Process.GetProcessById(Process.GetCurrentProcess().Id).Kill();
                }
                catch (Exception ex)
                {
                    Log.Error("CORE: Failed to download LZMA. " + ex.Message);
                }
            }

            //StaticConfiguration.DisableErrorTraces = false;

            if (!File.Exists("servers.json"))
            {
                try
                {
                    File.WriteAllText("servers.json", "[]");
                } catch { /* ignored */ }
            }

            if (Properties.Settings.Default.IsRestarting)
            {
                Properties.Settings.Default.IsRestarting = false;
                Properties.Settings.Default.Save();
                Thread.Sleep(3000);
            }

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            if (Debugger.IsAttached)
            {
                ShowMainScreen();
            }
            else
            {
                if (NFSW.IsNFSWRunning())
                {
                    MessageBox.Show(null, "An instance of Need for Speed: World is already running", "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    Process.GetProcessById(Process.GetCurrentProcess().Id).Kill();
                }

                var mutex = new Mutex(false, "GameLauncherNFSW-MeTonaTOR");
                try
                {
                    if (mutex.WaitOne(0, false))
                    {
                        string[] files =
                        {
                            "CommandLine.dll - 2.8.0",
                            "DiscordRPC.dll - 1.0.169.0",
                            "Flurl.dll - 3.0.1",
                            "Flurl.Http.dll - 3.0.1",
                            "INIFileParser.dll - 2.5.2",
                            "LZMA.dll - 9.10 beta",
                            "Microsoft.WindowsAPICodePack.dll - 1.1.0.0",
                            "Microsoft.WindowsAPICodePack.Shell.dll - 1.1.0.0",
                            "Microsoft.WindowsAPICodePack.ShellExtensions.dll - 1.1.0.0",
                            "Nancy.dll - 2.0.0",
                            "Nancy.Hosting.Self.dll - 2.0.0",
                            "Newtonsoft.Json.dll - 12.0.3",
                            "System.Runtime.InteropServices.RuntimeInformation.dll - 4.6.24705.01. Commit Hash: 4d1af962ca0fede10beb01d197367c2f90e92c97",
                            "System.ValueTuple.dll - 4.6.26515.06 @BuiltBy: dlab-DDVSOWINAGE059 @Branch: release/2.1 @SrcCode: https://github.com/dotnet/corefx/tree/30ab651fcb4354552bd4891619a0bdd81e0ebdbf",
                            "WindowsFirewallHelper.dll - 1.6.3.40"
                        };

                        var missingfiles = new List <string>();

                        if (!DetectLinux.LinuxDetected())
                        { //MONO Hates that...
                            foreach (var file in files)
                            {
                                var splitFileVersion = file.Split(new string[] { " - " }, StringSplitOptions.None);

                                if (!File.Exists(Directory.GetCurrentDirectory() + "\\" + splitFileVersion[0]))
                                {
                                    missingfiles.Add(splitFileVersion[0] + " - Not Found");
                                }
                                else
                                {
                                    try
                                    {
                                        var      versionInfo  = FileVersionInfo.GetVersionInfo(splitFileVersion[0]);
                                        string[] versionsplit = versionInfo.ProductVersion.Split('+');
                                        string   version      = versionsplit[0];

                                        if (version == "")
                                        {
                                            missingfiles.Add(splitFileVersion[0] + " - Invalid File");
                                        }
                                        else
                                        {
                                            if (Self.CheckArchitectureFile(splitFileVersion[0]) == false)
                                            {
                                                missingfiles.Add(splitFileVersion[0] + " - Wrong Architecture");
                                            }
                                            else
                                            {
                                                if (version != splitFileVersion[1])
                                                {
                                                    missingfiles.Add(splitFileVersion[0] + " - Invalid Version (" + splitFileVersion[1] + " != " + version + ")");
                                                }
                                            }
                                        }
                                    }
                                    catch
                                    {
                                        missingfiles.Add(splitFileVersion[0] + " - Invalid File");
                                    }
                                }
                            }
                        }
                        if (missingfiles.Count != 0)
                        {
                            ShowSplashScreen(false);

                            var message = "Cannot launch GameLauncher. The following files are invalid:\n\n";

                            foreach (var file in missingfiles)
                            {
                                message += "• " + file + "\n";
                            }

                            MessageBox.Show(null, message, "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        else
                        {
                            Theming.CheckIfThemeExists();
                            ShowSplashScreen(true);
                        }
                    }
                    else
                    {
                        ShowSplashScreen(false);
                        MessageBox.Show(null, "An instance of Launcher is already running.", "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                finally
                {
                    mutex.Close();
                    mutex = null;
                }
            }
        }
Example #9
0
        static void Main()
        {
            int  SysVersion = (int)Environment.OSVersion.Platform;
            bool mono       = DetectLinux.MonoDetected();
            bool wine       = DetectLinux.WineDetected();
            bool linux      = DetectLinux.LinuxDetected();

            //Discord fix
            Directory.SetCurrentDirectory(Path.GetDirectoryName(Application.ExecutablePath));

            //Languages
            if (!File.Exists("Languages"))
            {
                Directory.CreateDirectory("Languages");
                File.WriteAllText("Languages/Dutch.lng", ExtractResource.AsString("GameLauncher.Languages.Dutch.lng"));
                File.WriteAllText("Languages/English.lng", ExtractResource.AsString("GameLauncher.Languages.English.lng"));
                File.WriteAllText("Languages/French.lng", ExtractResource.AsString("GameLauncher.Languages.French.lng"));
                File.WriteAllText("Languages/German_Formal.lng", ExtractResource.AsString("GameLauncher.Languages.German_Formal.lng"));
                File.WriteAllText("Languages/German_Informal.lng", ExtractResource.AsString("GameLauncher.Languages.German_Informal.lng"));
                File.WriteAllText("Languages/Polish.lng", ExtractResource.AsString("GameLauncher.Languages.Polish.lng"));
                File.WriteAllText("Languages/Portuguese.lng", ExtractResource.AsString("GameLauncher.Languages.Portuguese.lng"));
                File.WriteAllText("Languages/Spanish.lng", ExtractResource.AsString("GameLauncher.Languages.Spanish.lng"));
                File.WriteAllText("Languages/Swedish.lng", ExtractResource.AsString("GameLauncher.Languages.Swedish.lng"));
            }

            //Remove zip file
            try {
                File.Delete(Directory.GetCurrentDirectory() + "\\tempname.zip");
            } catch { }

            //Console log with warning
            if (mono == true)
            {
                MessageBox.Show(null, "Mono support is still under alpha stage. Therefore, launcher could not launch.", "GameLauncher.exe", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

            //Add LZMA.dll on the fly (used for decompression of section{int}.dll files)
            if (!File.Exists("LZMA.dll"))
            {
                File.WriteAllBytes("LZMA.dll", ExtractResource.AsByte("GameLauncher.LZMA.LZMA.dll"));
            }

            //Add GameLauncherUpdater.exe on the fly
            if (!File.Exists("GameLauncherUpdater.exe"))
            {
                File.WriteAllBytes("GameLauncherUpdater.exe", ExtractResource.AsByte("GameLauncher.Updater.GameLauncherUpdater.exe"));
            }

            //Detect if NFSW is launched
            if (NFSW.isNFSWRunning())
            {
                MessageBox.Show(null, "An instance of Need for Speed: World is already running", "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                Process.GetProcessById(Process.GetCurrentProcess().Id).Kill();
            }

            Mutex mutex = new Mutex(false, "GameLauncherNFSW-MeTonaTOR"); //Forgot about other launchers...

            try {
                if (mutex.WaitOne(0, false))
                {
                    //First of all, we need to check if files exists
                    String[]      files        = { "Newtonsoft.Json.dll", "LZMA.dll", "ICSharpCode.SharpZipLib.dll" };
                    List <string> missingfiles = new List <string>();

                    foreach (string file in files)
                    {
                        if (!File.Exists(file))
                        {
                            missingfiles.Add(file);
                        }
                    }

                    if (missingfiles.Count != 0)
                    {
                        string message = "Cannot launch GameLauncher. The following files are missing:\n\n";

                        foreach (string file in missingfiles)
                        {
                            message += "• " + file + "\n";
                        }

                        message += "\nCurrent directory: " + Directory.GetCurrentDirectory();
                        message += "\nYou will be moved to the project page for re-download.";

                        MessageBox.Show(null, message, "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        Process.Start(@"https://github.com/SoapboxRaceWorld/GameLauncher_NFSW/releases");
                        Environment.Exit(1);
                    }

                    if (Environment.OSVersion.Version.Major >= 6)
                    {
                        User32.SetProcessDPIAware();
                    }

                    //try {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new mainScreen());
                    //} catch(Exception) {
                    //Temporarely we gonna kill it.
                    //  Process.GetProcessById(Process.GetCurrentProcess().Id).Kill();
                    //}
                }
                else
                {
                    MessageBox.Show(null, "An instance of the application is already running.", "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            } finally {
                if (mutex != null)
                {
                    mutex.Close();
                    mutex = null;
                }
            }
        }
Example #10
0
        private static void Main2(Arguments args)
        {
            if (Debugger.IsAttached && !NFSW.IsNFSWRunning())
            {
                NetCodeDefaults();
                DoRunChecks(args);
            }
            else
            {
                if (NFSW.IsNFSWRunning())
                {
                    MessageBox.Show(null, "An instance of Need for Speed: World is already running", "NFSTR.Com Başlatıcı", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    Process.GetProcessById(Process.GetCurrentProcess().Id).Kill();
                }

                NetCodeDefaults();

                //INFO: this is here because this dll is necessary for downloading game files and I want to make it async.
                //Updated RedTheKitsune Code so it downloads the file if its missing. It also restarts the launcher if the user click on yes on Prompt. - DavidCarbon
                if (!File.Exists("LZMA.dll"))
                {
                    try
                    {
                        using (WebClient wc = new WebClient())
                        {
                            wc.DownloadFile(new Uri(URLs.fileserver + "/LZMA.dll"), "LZMA.dll");
                        }

                        DialogResult restartApp = MessageBox.Show(null, "Downloaded Missing LZMA.dll File. \nPlease Restart Launcher, Thanks!", "GameLauncher Restart Required", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

                        if (restartApp == DialogResult.Yes)
                        {
                            Properties.Settings.Default.IsRestarting = true;
                            Properties.Settings.Default.Save();
                            Application.Restart();
                        }

                        Process.GetProcessById(Process.GetCurrentProcess().Id).Kill();
                    }
                    catch (Exception)
                    {
                    }
                }

                var mutex = new Mutex(false, "GameLauncherNFSW-MeTonaTOR");
                try
                {
                    if (mutex.WaitOne(0, false))
                    {
                        string[] files =
                        {
                            "CommandLine.dll - 2.8.0",
                            "DiscordRPC.dll - 1.0.175.0",
                            "Flurl.dll - 3.0.1",
                            "Flurl.Http.dll - 3.0.1",
                            "INIFileParser.dll - 2.5.2",
                            "LZMA.dll - 9.10 beta",
                            "Microsoft.WindowsAPICodePack.dll - 1.1.0.0",
                            "Microsoft.WindowsAPICodePack.Shell.dll - 1.1.0.0",
                            "Microsoft.WindowsAPICodePack.ShellExtensions.dll - 1.1.0.0",
                            "Nancy.dll - 2.0.0",
                            "Nancy.Hosting.Self.dll - 2.0.0",
                            "Newtonsoft.Json.dll - 12.0.3",
                            "System.Runtime.InteropServices.RuntimeInformation.dll - 4.6.24705.01. Commit Hash: 4d1af962ca0fede10beb01d197367c2f90e92c97",
                            "System.ValueTuple.dll - 4.6.26515.06 @BuiltBy: dlab-DDVSOWINAGE059 @Branch: release/2.1 @SrcCode: https://github.com/dotnet/corefx/tree/30ab651fcb4354552bd4891619a0bdd81e0ebdbf",
                            "WindowsFirewallHelper.dll - 2.0.4.70-beta2"
                        };

                        var missingfiles = new List <string>();

                        if (!DetectLinux.LinuxDetected())
                        { //MONO Hates that...
                            foreach (var file in files)
                            {
                                var splitFileVersion = file.Split(new string[] { " - " }, StringSplitOptions.None);

                                if (!File.Exists(Directory.GetCurrentDirectory() + "\\" + splitFileVersion[0]))
                                {
                                    missingfiles.Add(splitFileVersion[0] + " - Not Found");
                                }
                                else
                                {
                                    try
                                    {
                                        var      versionInfo  = FileVersionInfo.GetVersionInfo(splitFileVersion[0]);
                                        string[] versionsplit = versionInfo.ProductVersion.Split('+');
                                        string   version      = versionsplit[0];

                                        if (version == "")
                                        {
                                            missingfiles.Add(splitFileVersion[0] + " - Invalid File");
                                        }
                                        else
                                        {
                                            if (HardwareInfo.CheckArchitectureFile(splitFileVersion[0]) == false)
                                            {
                                                missingfiles.Add(splitFileVersion[0] + " - Wrong Architecture");
                                            }
                                            else
                                            {
                                                if (version != splitFileVersion[1])
                                                {
                                                    missingfiles.Add(splitFileVersion[0] + " - Invalid Version (" + splitFileVersion[1] + " != " + version + ")");
                                                }
                                            }
                                        }
                                    }
                                    catch
                                    {
                                        missingfiles.Add(splitFileVersion[0] + " - Invalid File");
                                    }
                                }
                            }
                        }
                        if (missingfiles.Count != 0)
                        {
                            var message = "Cannot launch GameLauncher. The following files are invalid:\n\n";

                            foreach (var file in missingfiles)
                            {
                                message += "• " + file + "\n";
                            }

                            MessageBox.Show(null, message, "NFSTR.Com Başlatıcı", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        else
                        {
                            DoRunChecks(args);
                        }
                    }
                    else
                    {
                        MessageBox.Show(null, "An instance of Launcher is already running.", "NFSTR.Com Başlatıcı", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                finally
                {
                    mutex.Close();
                }
            }
        }
Example #11
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            if (NFSW.IsNFSWRunning())
            {
                if (NFSW.DetectGameProcess())
                {
                    MessageBox.Show(null, "An instance of Need for Speed: World is already running", UserAgent.AgentAltName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                else
                {
                    MessageBox.Show(null, "An instance of SBRW Launcher is already running.", UserAgent.AgentAltName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                Process.GetProcessById(Process.GetCurrentProcess().Id).Kill();
            }
            else
            {
                var mutex = new Mutex(false, UserAgent.AgentName);
                try
                {
                    if (mutex.WaitOne(0, false))
                    {
                        if (!File.Exists("nfsw.exe"))
                        {
                            MessageBox.Show("nfsw.exe not found! Please put this launcher in the game directory. " +
                                            "If you don't have the game installed, Use the Vanilla Launcher to install it (visit https://soapboxrace.world/)",
                                            UserAgent.AgentAltName, MessageBoxButtons.OK, MessageBoxIcon.Error);

                            Process.GetProcessById(Process.GetCurrentProcess().Id).Kill();
                        }
                        else
                        {
                            if (!canAccesGameData())
                            {
                                MessageBox.Show("This application requires admin priviledge. Restarting...");
                                runAsAdmin();
                                return;
                            }

                            if (SHA.HashFile("nfsw.exe") != "7C0D6EE08EB1EDA67D5E5087DDA3762182CDE4AC")
                            {
                                MessageBox.Show("Invalid file was detected, please restore original nfsw.exe", UserAgent.AgentAltName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                            else
                            {
                                if (File.Exists(".links"))
                                {
                                    var linksPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "\\.links");
                                    ModNetLinksCleanup.CleanLinks(linksPath);
                                }

                                ServicePointManager.Expect100Continue = true;
                                ServicePointManager.SecurityProtocol |= SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

                                ServerListUpdater.GetList();

                                Application.Run(new Form1());
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show(null, "An instance of Launcher is already running.", UserAgent.AgentAltName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                finally
                {
                    mutex.Close();
                }
            }
        }