Ejemplo n.º 1
0
 public static void DoesRulesExist(bool removeFirewallRule, bool firstTimeRun, string nameOfApp, string localOfApp, string groupKey, string description, FirewallProtocol protocol)
 {
     if (FirewallManager.IsServiceRunning == true && !DetectLinux.LinuxDetected())
     {
         if (FirewallStatus() == true)
         {
             CheckIfRuleExists(removeFirewallRule, firstTimeRun, nameOfApp, localOfApp, groupKey, description, FirewallDirection.Inbound, protocol, FirewallDirection.Inbound.ToString());
             CheckIfRuleExists(removeFirewallRule, firstTimeRun, nameOfApp, localOfApp, groupKey, description, FirewallDirection.Outbound, protocol, FirewallDirection.Outbound.ToString());
         }
         else
         {
             Log.Warning("WINDOWS FIREWALL: Turned Off [Not by Launcher]");
         }
     }
     else if (FirewallManager.IsServiceRunning == false && !DetectLinux.LinuxDetected())
     {
         Log.Warning("WINDOWS FIREWALL: Service is Stopped [Not by Launcher]");
     }
     else if (DetectLinux.LinuxDetected())
     {
         Log.Warning("WINDOWS FIREWALL: Not Supported On Linux");
     }
     else
     {
         Log.Error("WINDOWS FIREWALL: Unknown Error Had Occured -> Check System Software");
     }
 }
Ejemplo n.º 2
0
        private void ApplyEmbeddedFonts()
        {
            /*******************************/

            /* Set Font                     /
            *  /*******************************/

            FontFamily DejaVuSans   = FontWrapper.Instance.GetFontFamily("DejaVuSans.ttf");
            var        MainFontSize = 8f * 100f / CreateGraphics().DpiY;

            if (DetectLinux.LinuxDetected())
            {
                MainFontSize = 8f;
            }
            Font = new Font(DejaVuSans, MainFontSize, FontStyle.Regular);

            /********************************/

            /* Set Theme Colors              /
            *  /********************************/

            ForeColor = Theming.WinFormSecondaryTextForeColor;
            BackColor = Theming.WinFormTBGForeColor;

            data.ForeColor = Theming.WinFormSecondaryTextForeColor;
            data.GridColor = Theming.WinFormGridForeColor;
        }
Ejemplo n.º 3
0
        private static void ShowSplashScreen(bool Status)
        {
            if (!Debugger.IsAttached && !DetectLinux.LinuxDetected())
            {
                SplashScreen f = new SplashScreen();
                f.Shown += new EventHandler((o, e) =>
                {
                    Thread ST = new Thread(() =>
                    {
                        Log.Info("SPLASH SCREEN: Closing Splash Screen");
                        Thread.Sleep(4000);
                        f.Invoke(new Action(() => { f.Close(); }));
                    })
                    {
                        IsBackground = true
                    };
                    ST.Start();
                });
                Application.Run(f);
            }

            if (Status == true)
            {
                ShowMainScreen();
            }
        }
Ejemplo n.º 4
0
        /* Checks Folder Permissions */
        public static bool CheckIfFolderPermissionIsSet(string path)
        {
            if (!DetectLinux.LinuxDetected())
            {
                var everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null);

                DirectoryInfo     Info           = new DirectoryInfo(path);
                DirectorySecurity FolderSecurity = Info.GetAccessControl();

                var acl = FolderSecurity.GetAccessRules(true, true, typeof(SecurityIdentifier));

                bool IsPermsGood = false;

                foreach (FileSystemAccessRule rule in acl)
                {
                    if (rule.IdentityReference.Value == everyone.Value && rule.AccessControlType == AccessControlType.Allow &&
                        (rule.FileSystemRights & FileSystemRights.Read) == FileSystemRights.Read)
                    {
                        IsPermsGood = true;
                    }
                }

                Log.Info("FOLDER PERMISSION: [" + path + "] Is permission set? -> " + IsPermsGood);

                return(IsPermsGood);
            }
            else
            {
                return(true);
            }
        }
Ejemplo n.º 5
0
        /* Checks if Windows Firewall is Enabled or not from a System Level */
        public static bool FirewallStatus()
        {
            bool FirewallEnabled;

            if (DetectLinux.LinuxDetected())
            {
                FirewallEnabled = false;
            }
            else
            {
                try
                {
                    Type      NetFwMgrType = Type.GetTypeFromProgID("HNetCfg.FwMgr", false);
                    INetFwMgr mgr          = (INetFwMgr)Activator.CreateInstance(NetFwMgrType);

                    FirewallEnabled = mgr.LocalPolicy.CurrentProfile.FirewallEnabled;
                }
                catch
                {
                    FirewallEnabled = false;
                }
            }

            return(FirewallEnabled);
        }
Ejemplo n.º 6
0
        /* Run The Functions to see if They need to be setup */

        public static void CheckLauncherPerms(string WhichFunction, string FileORFolderPath)
        {
            if (!DetectLinux.LinuxDetected())
            {
                if (WhichFunction == "Folder")
                {
                    if (Directory.Exists(FileORFolderPath))
                    {
                        if (CheckIfFolderPermissionIsSet(FileORFolderPath) == false)
                        {
                            GiveEveryoneReadWriteFolderAccess(FileORFolderPath);
                        }
                    }
                }
                else if (WhichFunction == "File")
                {
                    if (File.Exists(FileORFolderPath))
                    {
                        if (CheckIfFilePermissionIsSet(FileORFolderPath) == false)
                        {
                            GiveEveryoneReadWriteFileAccess(FileORFolderPath);
                        }
                    }
                }
            }
        }
Ejemplo n.º 7
0
        private void CheckGameFilesDirectoryPrevention()
        {
            if (!DetectLinux.LinuxDetected())
            {
                switch (Self.CheckFolder(_newGameFilesPath))
                {
                case FolderType.IsSameAsLauncherFolder:
                    Directory.CreateDirectory("Game Files");
                    Log.Error("LAUNCHER: Installing NFSW in same directory where the launcher resides is disadvised.");
                    MessageBox.Show(null, string.Format("Installing NFSW in same directory where the launcher resides is disadvised. Instead, we will install it at {0}.", AppDomain.CurrentDomain.BaseDirectory + "Game Files"), "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    FileSettingsSave.GameInstallation = AppDomain.CurrentDomain.BaseDirectory + "\\Game Files";
                    break;

                case FolderType.IsTempFolder:
                    Directory.CreateDirectory("Game Files");
                    Log.Error("LAUNCHER: (╯°□°)╯︵ ┻━┻ Installing NFSW in the Temp Folder is disadvised!");
                    MessageBox.Show(null, string.Format("(╯°□°)╯︵ ┻━┻\n\nInstalling NFSW in the Temp Folder is disadvised! Instead, we will install it at {0}.", AppDomain.CurrentDomain.BaseDirectory + "\\Game Files" + "\n\n┬─┬ ノ( ゜-゜ノ)"), "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    FileSettingsSave.GameInstallation = AppDomain.CurrentDomain.BaseDirectory + "\\Game Files";
                    break;

                case FolderType.IsProgramFilesFolder:
                case FolderType.IsUsersFolders:
                case FolderType.IsWindowsFolder:
                    Directory.CreateDirectory("Game Files");
                    Log.Error("LAUNCHER: Installing NFSW in a Special Directory is disadvised.");
                    MessageBox.Show(null, string.Format("Installing NFSW in a Special Directory is disadvised. Instead, we will install it at {0}.", AppDomain.CurrentDomain.BaseDirectory + "\\Game Files"), "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    FileSettingsSave.GameInstallation = AppDomain.CurrentDomain.BaseDirectory + "\\Game Files";
                    break;
                }
                FileSettingsSave.SaveSettings();
            }
        }
Ejemplo n.º 8
0
        private void SetVisuals()
        {
            /*******************************/

            /* Set Font                     /
            *  /*******************************/

            FontFamily DejaVuSans     = FontWrapper.Instance.GetFontFamily("DejaVuSans.ttf");
            FontFamily DejaVuSansBold = FontWrapper.Instance.GetFontFamily("DejaVuSans-Bold.ttf");

            var MainFontSize = 9f * 100f / CreateGraphics().DpiY;

            //var SecondaryFontSize = 8f * 100f / CreateGraphics().DpiY;
            //var ThirdFontSize = 10f * 100f / CreateGraphics().DpiY;
            //var FourthFontSize = 14f * 100f / CreateGraphics().DpiY;

            if (DetectLinux.LinuxDetected())
            {
                MainFontSize = 9f;
                //SecondaryFontSize = 8f;
                //ThirdFontSize = 10f;
                //FourthFontSize = 14f;
            }
            Font = new Font(DejaVuSans, MainFontSize, FontStyle.Regular);
            ChangelogBox.Font  = new Font(DejaVuSans, MainFontSize, FontStyle.Regular);
            ChangelogText.Font = new Font(DejaVuSans, MainFontSize, FontStyle.Regular);
            UpdateButton.Font  = new Font(DejaVuSansBold, MainFontSize, FontStyle.Bold);
            UpdateText.Font    = new Font(DejaVuSans, MainFontSize, FontStyle.Regular);
            SkipButton.Font    = new Font(DejaVuSansBold, MainFontSize, FontStyle.Bold);
            IgnoreButton.Font  = new Font(DejaVuSansBold, MainFontSize, FontStyle.Bold);

            /********************************/

            /* Set Theme Colors              /
            *  /********************************/

            ForeColor = Theming.WinFormTextForeColor;
            BackColor = Theming.WinFormTBGForeColor;

            ChangelogText.ForeColor = Theming.WinFormSecondaryTextForeColor;
            ChangelogBox.ForeColor  = Theming.WinFormTextForeColor;

            UpdateText.ForeColor = Theming.WinFormTextForeColor;

            UpdateButton.ForeColor = Theming.BlueForeColorButton;
            UpdateButton.BackColor = Theming.BlueBackColorButton;
            UpdateButton.FlatAppearance.BorderColor        = Theming.BlueBorderColorButton;
            UpdateButton.FlatAppearance.MouseOverBackColor = Theming.BlueMouseOverBackColorButton;

            IgnoreButton.ForeColor = Theming.BlueForeColorButton;
            IgnoreButton.BackColor = Theming.BlueBackColorButton;
            IgnoreButton.FlatAppearance.BorderColor        = Theming.BlueBorderColorButton;
            IgnoreButton.FlatAppearance.MouseOverBackColor = Theming.BlueMouseOverBackColorButton;

            SkipButton.ForeColor = Theming.BlueForeColorButton;
            SkipButton.BackColor = Theming.BlueBackColorButton;
            SkipButton.FlatAppearance.BorderColor        = Theming.BlueBorderColorButton;
            SkipButton.FlatAppearance.MouseOverBackColor = Theming.BlueMouseOverBackColorButton;
        }
Ejemplo n.º 9
0
        private void SetVisuals()
        {
            /*******************************/

            /* Set Font                     /
            *  /*******************************/

            FontFamily DejaVuSans     = FontWrapper.Instance.GetFontFamily("DejaVuSans.ttf");
            FontFamily DejaVuSansBold = FontWrapper.Instance.GetFontFamily("DejaVuSans-Bold.ttf");

            var MainFontSize = 9f * 100f / CreateGraphics().DpiY;

            //var SecondaryFontSize = 8f * 100f / CreateGraphics().DpiY;
            //var ThirdFontSize = 10f * 100f / CreateGraphics().DpiY;
            //var FourthFontSize = 14f * 100f / CreateGraphics().DpiY;

            if (DetectLinux.LinuxDetected())
            {
                MainFontSize = 9f;
                //SecondaryFontSize = 8f;
                //ThirdFontSize = 10f;
                //FourthFontSize = 14f;
            }
            Font = new Font(DejaVuSans, MainFontSize, FontStyle.Regular);
            ServerListRenderer.Font = new Font(DejaVuSans, MainFontSize, FontStyle.Regular);
            Loading.Font            = new Font(DejaVuSans, MainFontSize, FontStyle.Regular);
            BtnAddServer.Font       = new Font(DejaVuSansBold, MainFontSize, FontStyle.Bold);
            BtnSelectServer.Font    = new Font(DejaVuSansBold, MainFontSize, FontStyle.Bold);
            BtnClose.Font           = new Font(DejaVuSansBold, MainFontSize, FontStyle.Bold);
            Version.Font            = new Font(DejaVuSans, MainFontSize, FontStyle.Regular);

            /********************************/

            /* Set Theme Colors & Images     /
            *  /********************************/

            ForeColor = Theming.WinFormTextForeColor;
            BackColor = Theming.WinFormTBGForeColor;

            Loading.ForeColor = Theming.WinFormWarningTextForeColor;
            Version.ForeColor = Theming.WinFormTextForeColor;

            ServerListRenderer.ForeColor = Theming.WinFormSecondaryTextForeColor;

            BtnAddServer.ForeColor = Theming.BlueForeColorButton;
            BtnAddServer.BackColor = Theming.BlueBackColorButton;
            BtnAddServer.FlatAppearance.BorderColor        = Theming.BlueBorderColorButton;
            BtnAddServer.FlatAppearance.MouseOverBackColor = Theming.BlueMouseOverBackColorButton;

            BtnSelectServer.ForeColor = Theming.BlueForeColorButton;
            BtnSelectServer.BackColor = Theming.BlueBackColorButton;
            BtnSelectServer.FlatAppearance.BorderColor        = Theming.BlueBorderColorButton;
            BtnSelectServer.FlatAppearance.MouseOverBackColor = Theming.BlueMouseOverBackColorButton;

            BtnClose.ForeColor = Theming.BlueForeColorButton;
            BtnClose.BackColor = Theming.BlueBackColorButton;
            BtnClose.FlatAppearance.BorderColor        = Theming.BlueBorderColorButton;
            BtnClose.FlatAppearance.MouseOverBackColor = Theming.BlueMouseOverBackColorButton;
        }
Ejemplo n.º 10
0
        private void SetVisuals()
        {
            /*******************************/

            /* Set Font                     /
            *  /*******************************/

            FontFamily DejaVuSans     = FontWrapper.Instance.GetFontFamily("DejaVuSans.ttf");
            FontFamily DejaVuSansBold = FontWrapper.Instance.GetFontFamily("DejaVuSans-Bold.ttf");

            var MainFontSize = 9f * 100f / CreateGraphics().DpiY;

            //var SecondaryFontSize = 8f * 100f / CreateGraphics().DpiY;
            //var ThirdFontSize = 10f * 100f / CreateGraphics().DpiY;
            //var FourthFontSize = 14f * 100f / CreateGraphics().DpiY;

            if (DetectLinux.LinuxDetected())
            {
                MainFontSize = 9f;
                //SecondaryFontSize = 8f;
                //ThirdFontSize = 10f;
                //FourthFontSize = 14f;
            }
            Font = new Font(DejaVuSans, MainFontSize, FontStyle.Regular);
            VerifyHashWelcome.Font    = new Font(DejaVuSansBold, MainFontSize, FontStyle.Bold);
            ScanProgressText.Font     = new Font(DejaVuSansBold, MainFontSize, FontStyle.Bold);
            DownloadProgressText.Font = new Font(DejaVuSansBold, MainFontSize, FontStyle.Bold);
            StartScanner.Font         = new Font(DejaVuSansBold, MainFontSize, FontStyle.Bold);
            StopScanner.Font          = new Font(DejaVuSansBold, MainFontSize, FontStyle.Bold);
            VerifyHashText.Font       = new Font(DejaVuSansBold, MainFontSize, FontStyle.Bold);
            VersionLabel.Font         = new Font(DejaVuSans, MainFontSize, FontStyle.Regular);

            /********************************/

            /* Set Theme Colors              /
            *  /********************************/

            ForeColor = Theming.WinFormTextForeColor;
            BackColor = Theming.WinFormTBGForeColor;

            DownloadProgressText.ForeColor = Theming.WinFormTextForeColor;
            ScanProgressText.ForeColor     = Theming.WinFormTextForeColor;

            VerifyHashWelcome.ForeColor = Theming.WinFormSecondaryTextForeColor;
            VerifyHashText.ForeColor    = Theming.WinFormSuccessTextForeColor;

            VersionLabel.ForeColor = Theming.WinFormTextForeColor;

            StartScanner.ForeColor = Theming.WinFormSuccessTextForeColor;
            StartScanner.BackColor = Theming.BlueBackColorButton;
            StartScanner.FlatAppearance.BorderColor        = Theming.BlueBorderColorButton;
            StartScanner.FlatAppearance.MouseOverBackColor = Theming.BlueMouseOverBackColorButton;

            StopScanner.ForeColor = Theming.WinFormWarningTextForeColor;
            StopScanner.BackColor = Theming.BlueBackColorButton;
            StopScanner.FlatAppearance.BorderColor        = Theming.BlueBorderColorButton;
            StopScanner.FlatAppearance.MouseOverBackColor = Theming.BlueMouseOverBackColorButton;
        }
Ejemplo n.º 11
0
        protected override WebRequest GetWebRequest(Uri address)
        {
            if (DetectLinux.LinuxDetected())
            {
                address = new UriBuilder(address)
                {
                    Scheme = Uri.UriSchemeHttp,
                    Port   = address.IsDefaultPort ? -1 : address.Port // -1 => default port for scheme
                }.Uri;
            }

            ServicePointManager.SecurityProtocol  = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
            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, 1, 0);
                        chain.ChainPolicy.VerificationFlags   = X509VerificationFlags.AllFlags;
                        bool chainIsValid = chain.Build((X509Certificate2)certificate);
                        if (!chainIsValid)
                        {
                            isOk = false;
                            break;
                        }
                    }
                }
                return(isOk);
            };

            Log.UrlCall("Calling URL: " + address);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);

            request.UserAgent                     = "GameLauncher (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)";
            request.Headers["X-HWID"]             = Security.FingerPrint.Value();
            request.Headers["X-UserAgent"]        = "GameLauncherReborn " + Application.ProductVersion + " WinForms (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)";
            request.Headers["X-GameLauncherHash"] = Value();
            request.Headers["X-DiscordID"]        = Self.discordid;

            if (addrange != 0)
            {
                request.AddRange(addrange);
            }

            request.Proxy   = null;
            request.Timeout = timeout;

            return(request);
        }
 public static void SetState(IntPtr windowHandle, TaskbarStates taskbarState)
 {
     try {
         if (taskbarSupported && !DetectLinux.LinuxDetected())
         {
             taskbarInstance.SetProgressState(windowHandle, taskbarState);
         }
     } catch { }
 }
 public static void SetValue(IntPtr windowHandle, double progressValue, double progressMax)
 {
     try {
         if (taskbarSupported && !DetectLinux.LinuxDetected())
         {
             taskbarInstance.SetProgressValue(windowHandle, (ulong)progressValue, (ulong)progressMax);
         }
     } catch { }
 }
 public static async Task SubmitError(Exception exception)
 {
     var mainsrv = DetectLinux.LinuxDetected() ? mainserver.Replace("https", "http") : mainserver;
     Url url     = new Url(mainsrv + "/error-report");
     await url.PostJsonAsync(new
     {
         message    = exception.Message ?? "no message",
         stackTrace = exception.StackTrace ?? "no stack trace"
     });
 }
Ejemplo n.º 15
0
 public static bool RuleExist(string nameOfApp)
 {
     if (DetectLinux.LinuxDetected())
     {
         return(true);
     }
     else
     {
         return(FindRules(nameOfApp).Any());
     }
 }
Ejemplo n.º 16
0
        public static string Value()
        {
            if (string.IsNullOrEmpty(fingerPrint))
            {
                if (!DetectLinux.LinuxDetected())
                {
                    fingerPrint = WindowsValue();
                }
                else if (DetectLinux.LinuxDetected())
                {
                    fingerPrint = LinuxValue();
                }
            }

            return(fingerPrint);
        }
Ejemplo n.º 17
0
        public static void CheckAvailability()
        {
            if (!DetectLinux.LinuxDetected())
            {
                switch (APIStatusChecker.CheckStatus(URLs.mainserver + "/update.php?version=" + Application.ProductVersion))
                {
                case APIStatus.Online:
                    MainAPI();
                    break;

                default:
                    GitHubAPI();
                    break;
                }
            }
        }
Ejemplo n.º 18
0
        protected override WebRequest GetWebRequest(Uri address)
        {
            if (DetectLinux.LinuxDetected())
            {
                address = new UriBuilder(address)
                {
                    Scheme = Uri.UriSchemeHttp,
                    Port   = address.IsDefaultPort ? -1 : address.Port // -1 => default port for scheme
                }.Uri;
            }

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);

            request.UserAgent                     = (Self.userAgent == null) ? "GameLauncher (+https://github.com/SoapboxRaceWorld/GameLauncher_NFSW)" : Self.userAgent;
            request.Headers["X-HWID"]             = Security.FingerPrint.Value();
            request.Headers["X-UserAgent"]        = "GameLauncherReborn " + Application.ProductVersion + " WinForms (+https://github.com/worldunitedgg/GameLauncher_NFSW)";
            request.Headers["X-GameLauncherHash"] = Value();
            request.Headers["X-DiscordID"]        = Self.discordid;
            //request.Timeout = 30000;

            return(request);
        }
Ejemplo n.º 19
0
        /* Sets Folder Permissions */
        public static void GiveEveryoneReadWriteFolderAccess(string path)
        {
            if (!DetectLinux.LinuxDetected())
            {
                try
                {
                    DirectoryInfo     Info           = new DirectoryInfo(path);
                    DirectorySecurity FolderSecurity = Info.GetAccessControl();

                    SecurityIdentifier everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null);

                    FolderSecurity.AddAccessRule(new FileSystemAccessRule(everyone, FileSystemRights.FullControl,
                                                                          InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.NoPropagateInherit,
                                                                          AccessControlType.Allow));

                    Directory.SetAccessControl(path, FolderSecurity);
                }
                catch (Exception ex)
                {
                    Log.Error("FOLDER PERMISSION: " + ex.Message);
                }
            }
        }
Ejemplo n.º 20
0
        /* Sets File Permissions */
        public static void GiveEveryoneReadWriteFileAccess(string path)
        {
            if (!DetectLinux.LinuxDetected())
            {
                try
                {
                    var everyone = new SecurityIdentifier(WellKnownSidType.WorldSid,
                                                          null);

                    var accessRule = new FileSystemAccessRule(everyone,
                                                              FileSystemRights.FullControl,
                                                              InheritanceFlags.None, PropagationFlags.NoPropagateInherit,
                                                              AccessControlType.Allow);

                    var fileSecurity = File.GetAccessControl(path);
                    fileSecurity.AddAccessRule(accessRule);
                    File.SetAccessControl(path, fileSecurity);
                }
                catch (Exception ex)
                {
                    Log.Error("FILE PERMISSION: " + ex.Message);
                }
            }
        }
Ejemplo n.º 21
0
        private static void ShowMainScreen()
        {
            if (VisualsAPIChecker.WOPLAPI == false)
            {
                DialogResult restartAppNoApis = MessageBox.Show(null, "There's no internet connection, Launcher might crash \n \nClick Yes to Close Launcher \nor \nClick No Continue", "GameLauncher has Stopped, Failed To Connect To API", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

                if (restartAppNoApis == DialogResult.No)
                {
                    MessageBox.Show("Good Luck... \n No Really \n ...Good Luck", "GameLauncher Will Continue, When It Failed To Connect To API");
                    Log.Warning("PRE-CHECK: User has Bypassed 'No Internet Connection' Check and Will Continue");
                }

                if (restartAppNoApis == DialogResult.Yes)
                {
                    Process.GetProcessById(Process.GetCurrentProcess().Id).Kill();
                }
            }

            ServerListUpdater.GetList();
            CDNListUpdater.GetList();
            LauncherUpdateCheck.CheckAvailability();

            if (!DetectLinux.LinuxDetected())
            {
                //Install Custom Root Certificate
                CertificateStore.Check();

                if (!File.Exists("GameLauncherUpdater.exe"))
                {
                    Log.Info("LAUNCHER UPDATER: Starting GameLauncherUpdater downloader");
                    try
                    {
                        using (WebClient wc = new WebClient())
                        {
                            wc.DownloadFileCompleted += (object sender, AsyncCompletedEventArgs e) =>
                            {
                                if (new FileInfo("GameLauncherUpdater.exe").Length == 0)
                                {
                                    File.Delete("GameLauncherUpdater.exe");
                                }
                            };
                            wc.DownloadFile(new Uri("https://github.com/SoapboxRaceWorld/GameLauncherUpdater/releases/latest/download/GameLauncherUpdater.exe"), "GameLauncherUpdater.exe");
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Error("LAUCHER UPDATER: Failed to download updater. " + ex.Message);
                    }
                }
                else if (File.Exists("GameLauncherUpdater.exe"))
                {
                    String GameLauncherUpdaterLocation = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "GameLauncherUpdater.exe");
                    var    LauncherUpdaterBuild        = FileVersionInfo.GetVersionInfo(GameLauncherUpdaterLocation);
                    var    LauncherUpdaterBuildNumber  = LauncherUpdaterBuild.FileVersion;
                    var    UpdaterBuildNumberResult    = LauncherUpdaterBuildNumber.CompareTo(LatestUpdaterBuildVersion);

                    Log.Build("LAUNCHER UPDATER BUILD: GameLauncherUpdater " + LauncherUpdaterBuildNumber);
                    if (UpdaterBuildNumberResult < 0)
                    {
                        Log.Info("LAUNCHER UPDATER: " + UpdaterBuildNumberResult + " Builds behind latest Updater!");
                    }
                    else
                    {
                        Log.Info("LAUNCHER UPDATER: Latest GameLauncherUpdater!");
                    }

                    if (UpdaterBuildNumberResult < 0)
                    {
                        Log.Info("LAUNCHER UPDATER: Downloading New GameLauncherUpdater.exe");
                        File.Delete("GameLauncherUpdater.exe");

                        try
                        {
                            using (WebClient wc = new WebClient())
                            {
                                wc.DownloadFile(new Uri("https://github.com/SoapboxRaceWorld/GameLauncherUpdater/releases/latest/download/GameLauncherUpdater.exe"), "GameLauncherUpdater.exe");
                            }
                        }
                        catch (Exception ex)
                        {
                            Log.Error("LAUNCHER UPDATER: Failed to download new updater. " + ex.Message);
                        }
                    }
                }
            }

            if (!string.IsNullOrEmpty(FileSettingsSave.GameInstallation))
            {
                var linksPath = Path.Combine(FileSettingsSave.GameInstallation + "\\.links");
                ModNetLinksCleanup.CleanLinks(linksPath);
            }

            Log.Info("PROXY: Starting Proxy");
            ServerProxy.Instance.Start();

            Log.Visuals("CORE: Starting MainScreen");
            Application.Run(new MainScreen());
        }
        public static void NullSafeSettings()
        {
            if (settingFile.KeyExists("Server"))
            {
                FileAccountSave.ChoosenGameServer = settingFile.Read("Server");
                settingFile.DeleteKey("Server");
                FileAccountSave.SaveAccount();
            }

            if (settingFile.KeyExists("AccountEmail"))
            {
                FileAccountSave.UserRawEmail = settingFile.Read("AccountEmail");
                settingFile.DeleteKey("AccountEmail");
                FileAccountSave.SaveAccount();
            }

            if (settingFile.KeyExists("Password"))
            {
                FileAccountSave.UserHashedPassword = settingFile.Read("Password");
                settingFile.DeleteKey("Password");
                FileAccountSave.SaveAccount();
            }

            if (DetectLinux.LinuxDetected() && !settingFile.KeyExists("InstallationDirectory"))
            {
                settingFile.Write("InstallationDirectory", "GameFiles");
            }
            else if (!settingFile.KeyExists("InstallationDirectory"))
            {
                settingFile.Write("InstallationDirectory", GameInstallation);
            }
            else if (!File.Exists(GameInstallation) && !string.IsNullOrEmpty(GameInstallation))
            {
                Directory.CreateDirectory(GameInstallation);
            }

            if (!settingFile.KeyExists("CDN"))
            {
                settingFile.Write("CDN", CDN);
            }
            else if (settingFile.KeyExists("CDN"))
            {
                if (CDN.EndsWith("/"))
                {
                    char[] charsToTrim = { '/' };
                    string FinalCDNURL = CDN.TrimEnd(charsToTrim);

                    settingFile.Write("CDN", FinalCDNURL);
                }
            }

            if (!settingFile.KeyExists("Language"))
            {
                settingFile.Write("Language", Lang);
            }

            if (!settingFile.KeyExists("DisableProxy"))
            {
                settingFile.Write("DisableProxy", Proxy);
            }

            if (!settingFile.KeyExists("DisableRPC"))
            {
                settingFile.Write("DisableRPC", RPC);
            }

            if (!settingFile.KeyExists("IgnoreUpdateVersion"))
            {
                settingFile.Write("IgnoreUpdateVersion", IgnoreVersion);
            }

            if (!DetectLinux.LinuxDetected())
            {
                if (!settingFile.KeyExists("Firewall"))
                {
                    settingFile.Write("Firewall", FirewallStatus);
                }

                if (WindowsProductVersion.GetWindowsNumber() >= 10.0)
                {
                    if (!settingFile.KeyExists("WindowsDefender"))
                    {
                        settingFile.Write("WindowsDefender", WindowsDefenderStatus);
                    }
                }
                else if (WindowsProductVersion.GetWindowsNumber() < 10.0)
                {
                    if (settingFile.KeyExists("WindowsDefender") || !string.IsNullOrEmpty(settingFile.Read("WindowsDefender")))
                    {
                        settingFile.DeleteKey("WindowsDefender");
                    }
                }

                if (WindowsProductVersion.GetWindowsNumber() == 6.1 && !settingFile.KeyExists("PatchesApplied"))
                {
                    settingFile.Write("PatchesApplied", Win7UpdatePatches);
                }
                else if (WindowsProductVersion.GetWindowsNumber() != 6.1 && settingFile.KeyExists("PatchesApplied"))
                {
                    settingFile.DeleteKey("PatchesApplied");
                }
            }

            /* Key Entries to Remove (No Longer Needed) */

            if (settingFile.KeyExists("LauncherPosX"))
            {
                settingFile.DeleteKey("LauncherPosX");
            }

            if (settingFile.KeyExists("LauncherPosY"))
            {
                settingFile.DeleteKey("LauncherPosY");
            }

            if (settingFile.KeyExists("DisableVerifyHash"))
            {
                settingFile.DeleteKey("DisableVerifyHash");
            }

            if (settingFile.KeyExists("TracksHigh"))
            {
                settingFile.DeleteKey("TracksHigh");
            }

            if (settingFile.KeyExists("ModNetDisabled"))
            {
                settingFile.DeleteKey("ModNetDisabled");
            }

            settingFile = new IniFile("Settings.ini");
        }
        public static void SaveSettings()
        {
            if (settingFile.Read("CDN") != CDN)
            {
                if (CDN.EndsWith("/"))
                {
                    char[] charsToTrim = { '/' };
                    string FinalCDNURL = CDN.TrimEnd(charsToTrim);

                    settingFile.Write("CDN", FinalCDNURL);
                }
                else
                {
                    settingFile.Write("CDN", CDN);
                }
            }

            if (settingFile.Read("Language") != Lang)
            {
                settingFile.Write("Language", Lang);
            }

            if (settingFile.Read("DisableProxy") != Proxy)
            {
                settingFile.Write("DisableProxy", Proxy);
            }

            if (settingFile.Read("DisableRPC") != RPC)
            {
                settingFile.Write("DisableRPC", RPC);
            }

            if (settingFile.Read("InstallationDirectory") != GameInstallation)
            {
                settingFile.Write("InstallationDirectory", GameInstallation);
            }

            if (settingFile.Read("IgnoreUpdateVersion") != IgnoreVersion)
            {
                settingFile.Write("IgnoreUpdateVersion", IgnoreVersion);
            }

            if (!DetectLinux.LinuxDetected())
            {
                if (settingFile.Read("Firewall") != FirewallStatus)
                {
                    settingFile.Write("Firewall", FirewallStatus);
                }

                if (WindowsProductVersion.GetWindowsNumber() >= 10.0)
                {
                    if (settingFile.Read("WindowsDefender") != WindowsDefenderStatus)
                    {
                        settingFile.Write("WindowsDefender", WindowsDefenderStatus);
                    }
                }

                if ((settingFile.Read("PatchesApplied") != Win7UpdatePatches) && WindowsProductVersion.GetWindowsNumber() == 6.1)
                {
                    settingFile.Write("PatchesApplied", Win7UpdatePatches);
                }
            }

            settingFile = new IniFile("Settings.ini");
        }
Ejemplo n.º 24
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;
                }
            }
        }
Ejemplo n.º 25
0
        public SelectServer()
        {
            InitializeComponent();
            SetVisuals();

            Version.Text = "Version: v" + Application.ProductVersion;

            //And one for keeping data about server, IP tbh
            ServerListRenderer.View          = View.Details;
            ServerListRenderer.FullRowSelect = true;

            ServerListRenderer.Columns.Add("");
            ServerListRenderer.Columns[0].Width = 1;

            ServerListRenderer.Columns.Add("Name");
            ServerListRenderer.Columns[1].Width = 210;

            ServerListRenderer.Columns.Add("Country");
            ServerListRenderer.Columns[2].Width     = 100;
            ServerListRenderer.Columns[2].TextAlign = HorizontalAlignment.Center;

            ServerListRenderer.Columns.Add("Online");
            ServerListRenderer.Columns[3].Width     = 75;
            ServerListRenderer.Columns[3].TextAlign = HorizontalAlignment.Center;

            ServerListRenderer.Columns.Add("Registered");
            ServerListRenderer.Columns[4].Width     = 85;
            ServerListRenderer.Columns[4].TextAlign = HorizontalAlignment.Center;

            ServerListRenderer.Columns.Add("Ping");
            ServerListRenderer.Columns[5].Width     = 60;
            ServerListRenderer.Columns[5].TextAlign = HorizontalAlignment.Center;

            foreach (var substring in ServerListUpdater.NoCategoryList)
            {
                try
                {
                    servers.Enqueue(ID + "_|||_" + substring.IpAddress + "_|||_" + substring.Name);

                    ServerListRenderer.Items.Add(new ListViewItem(
                                                     new[]
                    {
                        ID.ToString(), substring.Name, "", "", "", "", ""
                    }
                                                     ));

                    data.Add(ID, substring);
                    ID++;
                }
                catch
                {
                }
            }

            Thread newList = new Thread(() =>
            {
                Thread.Sleep(200);
                this.BeginInvoke((MethodInvoker) delegate
                {
                    while (servers.Count != 0)
                    {
                        string QueueContent    = servers.Dequeue();
                        string[] QueueContent2 = QueueContent.Split(new string[] { "_|||_" }, StringSplitOptions.None);

                        int serverid      = Convert.ToInt32(QueueContent2[0]) - 1;
                        string serverurl  = QueueContent2[1] + "/GetServerInformation";
                        string servername = QueueContent2[2];

                        try
                        {
                            WebClient getdata            = new WebClient();
                            GetServerInformation content = JsonConvert.DeserializeObject <GetServerInformation>(getdata.DownloadString(serverurl));

                            if (content == null)
                            {
                                ServerListRenderer.Items[serverid].SubItems[1].Text = servername;
                                ServerListRenderer.Items[serverid].SubItems[2].Text = "---";
                                ServerListRenderer.Items[serverid].SubItems[3].Text = "---";
                                ServerListRenderer.Items[serverid].SubItems[4].Text = "---";
                            }
                            else
                            {
                                ServerListRenderer.Items[serverid].SubItems[1].Text = servername;
                                ServerListRenderer.Items[serverid].SubItems[2].Text = ServerListUpdater.CountryName(content.country.ToString());
                                ServerListRenderer.Items[serverid].SubItems[3].Text = content.onlineNumber.ToString();
                                ServerListRenderer.Items[serverid].SubItems[4].Text = content.numberOfRegistered.ToString();

                                //PING
                                if (!DetectLinux.LinuxDetected())
                                {
                                    Ping pingSender = new Ping();
                                    Uri StringToUri = new Uri(serverurl);
                                    pingSender.SendAsync(StringToUri.Host, 1000, new byte[1], new PingOptions(64, true), new AutoResetEvent(false));
                                    pingSender.PingCompleted += (sender3, e3) => {
                                        PingReply reply = e3.Reply;

                                        if (reply.Status == IPStatus.Success && servername != "Offline Built-In Server")
                                        {
                                            ServerListRenderer.Items[serverid].SubItems[5].Text = reply.RoundtripTime + "ms";
                                        }
                                        else
                                        {
                                            ServerListRenderer.Items[serverid].SubItems[5].Text = "---";
                                        }
                                    };
                                }
                                else
                                {
                                    ServerListRenderer.Items[serverid].SubItems[5].Text = "N/A";
                                }
                            }
                        }
                        catch
                        {
                            ServerListRenderer.Items[serverid].SubItems[1].Text = servername;
                            ServerListRenderer.Items[serverid].SubItems[2].Text = "---";
                            ServerListRenderer.Items[serverid].SubItems[3].Text = "---";
                            ServerListRenderer.Items[serverid].SubItems[4].Text = "---";
                            ServerListRenderer.Items[serverid].SubItems[5].Text = "---";
                        }

                        if (servers.Count == 0)
                        {
                            Loading.Text = "";
                        }

                        Application.DoEvents();
                    }
                });
            })
            {
                IsBackground = true
            };

            newList.Start();

            ServerListRenderer.AllowColumnReorder   = false;
            ServerListRenderer.ColumnWidthChanging += (handler, args) =>
            {
                args.Cancel   = true;
                args.NewWidth = ServerListRenderer.Columns[args.ColumnIndex].Width;
            };

            ServerListRenderer.DoubleClick += new EventHandler((handler, args) =>
            {
                SelectedGameServerToRemember();
            });
        }
Ejemplo n.º 26
0
        private void SetVisuals()
        {
            /*******************************/

            /* Set Font                     /
            *  /*******************************/

            FontFamily DejaVuSans     = FontWrapper.Instance.GetFontFamily("DejaVuSans.ttf");
            FontFamily DejaVuSansBold = FontWrapper.Instance.GetFontFamily("DejaVuSans-Bold.ttf");

            var MainFontSize      = 10f * 100f / CreateGraphics().DpiY;
            var SecondaryFontSize = 15f * 100f / CreateGraphics().DpiY;
            var ThirdFontSize     = 26f * 100f / CreateGraphics().DpiY;

            //var FourthFontSize = 14f * 100f / CreateGraphics().DpiY;

            if (DetectLinux.LinuxDetected())
            {
                MainFontSize      = 10f;
                SecondaryFontSize = 15f;
                ThirdFontSize     = 26f;
                //FourthFontSize = 14f;
            }
            Font              = new Font(DejaVuSans, MainFontSize, FontStyle.Regular);
            AboutText.Font    = new Font(DejaVuSansBold, ThirdFontSize, FontStyle.Bold);
            PatchTitle1.Font  = new Font(DejaVuSans, SecondaryFontSize, FontStyle.Regular);
            PatchText1.Font   = new Font(DejaVuSans, MainFontSize, FontStyle.Regular);
            PatchButton1.Font = new Font(DejaVuSans, SecondaryFontSize, FontStyle.Regular);
            PatchTitle2.Font  = new Font(DejaVuSans, SecondaryFontSize, FontStyle.Regular);
            PatchText2.Font   = new Font(DejaVuSans, MainFontSize, FontStyle.Regular);
            PatchButton2.Font = new Font(DejaVuSans, SecondaryFontSize, FontStyle.Regular);
            PatchTitle3.Font  = new Font(DejaVuSans, SecondaryFontSize, FontStyle.Regular);
            PatchText3.Font   = new Font(DejaVuSans, MainFontSize, FontStyle.Regular);
            PatchButton3.Font = new Font(DejaVuSans, SecondaryFontSize, FontStyle.Regular);

            /********************************/

            /* Set Theme Colors              /
            *  /********************************/

            AboutText.ForeColor = Theming.WinFormTextForeColor;

            BackColor = Theming.WinFormTBGForeColor;
            ForeColor = Theming.WinFormTextForeColor;

            PatchContainerPanel.BackColor = Theming.WinFormTBGForeColor;
            PatchContainerPanel.ForeColor = Theming.WinFormTextForeColor;

            PatchText1.BackColor = Theming.AboutBGForeColor;
            PatchText1.ForeColor = Theming.AboutTextForeColor;

            PatchText2.BackColor = Theming.AboutBGForeColor;
            PatchText2.ForeColor = Theming.AboutTextForeColor;

            PatchText3.BackColor = Theming.AboutBGForeColor;
            PatchText3.ForeColor = Theming.AboutTextForeColor;

            PatchButton1.ForeColor = Theming.BlueForeColorButton;
            PatchButton1.BackColor = Theming.BlueBackColorButton;
            PatchButton1.FlatAppearance.BorderColor        = Theming.BlueBorderColorButton;
            PatchButton1.FlatAppearance.MouseOverBackColor = Theming.BlueMouseOverBackColorButton;

            PatchButton2.ForeColor = Theming.BlueForeColorButton;
            PatchButton2.BackColor = Theming.BlueBackColorButton;
            PatchButton2.FlatAppearance.BorderColor        = Theming.BlueBorderColorButton;
            PatchButton2.FlatAppearance.MouseOverBackColor = Theming.BlueMouseOverBackColorButton;

            PatchButton3.ForeColor = Theming.BlueForeColorButton;
            PatchButton3.BackColor = Theming.BlueBackColorButton;
            PatchButton3.FlatAppearance.BorderColor        = Theming.BlueBorderColorButton;
            PatchButton3.FlatAppearance.MouseOverBackColor = Theming.BlueMouseOverBackColorButton;
        }
Ejemplo n.º 27
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;
                }
            }
        }
Ejemplo n.º 28
0
        /*******************************/

        /* On Button/Dropdown Functions /
        *  /*******************************/

        /* Settings Save */
        private void SettingsSave_Click(object sender, EventArgs e)
        {
            //TODO null check
            FileSettingsSave.Lang = SettingsLanguage.SelectedValue.ToString();

            if (WindowsProductVersion.GetWindowsNumber() >= 10.0 && (FileSettingsSave.GameInstallation != _newGameFilesPath) && !DetectLinux.LinuxDetected())
            {
                WindowsDefenderGameFilesDirctoryChange();
            }
            else if (FileSettingsSave.GameInstallation != _newGameFilesPath)
            {
                CheckGameFilesDirectoryPrevention();

                if (!DetectLinux.LinuxDetected())
                {
                    //Remove current Firewall for the Game Files
                    string CurrentGameFilesExePath = Path.Combine(FileSettingsSave.GameInstallation + "\\nfsw.exe");

                    if (File.Exists(CurrentGameFilesExePath) && FirewallHelper.RuleExist("SBRW - Game") == true)
                    {
                        bool removeFirewallRule = true;
                        bool firstTimeRun       = 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);
                    }
                }

                FileSettingsSave.GameInstallation = _newGameFilesPath;

                //Clean Mods Files from New Dirctory (If it has .links in directory)
                var linksPath = Path.Combine(_newGameFilesPath, "\\.links");
                ModNetLinksCleanup.CleanLinks(linksPath);

                _restartRequired = true;
            }

            if (FileSettingsSave.CDN != ((CDNObject)SettingsCDNPick.SelectedItem).Url)
            {
                SettingsCDNCurrentText.Text = "CHANGED CDN";
                SettingsCDNCurrent.Text     = ((CDNObject)SettingsCDNPick.SelectedItem).Url;
                FileSettingsSave.CDN        = ((CDNObject)SettingsCDNPick.SelectedItem).Url;
                _restartRequired            = true;
            }

            String disableProxy = (SettingsProxyCheckbox.Checked == true) ? "1" : "0";

            if (FileSettingsSave.Proxy != disableProxy)
            {
                FileSettingsSave.Proxy = (SettingsProxyCheckbox.Checked == true) ? "1" : "0";
                _restartRequired       = true;
            }

            String disableRPC = (SettingsDiscordRPCCheckbox.Checked == true) ? "1" : "0";

            if (FileSettingsSave.RPC != disableRPC)
            {
                FileSettingsSave.RPC = (SettingsDiscordRPCCheckbox.Checked == true) ? "1" : "0";
                _restartRequired     = true;
            }

            if (_restartRequired)
            {
                MessageBox.Show(null, "In order to see settings changes, you need to restart launcher manually.", "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

            //Actually lets check those 2 files
            if (File.Exists(FileSettingsSave.GameInstallation + "/profwords") && File.Exists(FileSettingsSave.GameInstallation + "/profwords_dis"))
            {
                File.Delete(FileSettingsSave.GameInstallation + "/profwords_dis");
            }

            //Delete/Enable profwords filter here
            if (SettingsWordFilterCheck.Checked)
            {
                if (File.Exists(FileSettingsSave.GameInstallation + "/profwords"))
                {
                    File.Move(FileSettingsSave.GameInstallation + "/profwords", FileSettingsSave.GameInstallation + "/profwords_dis");
                }
            }
            else
            {
                if (File.Exists(FileSettingsSave.GameInstallation + "/profwords_dis"))
                {
                    File.Move(FileSettingsSave.GameInstallation + "/profwords_dis", FileSettingsSave.GameInstallation + "/profwords");
                }
            }

            /* Save Settings */
            FileSettingsSave.SaveSettings();

            var userSettingsXml = new XmlDocument();

            try
            {
                if (File.Exists(_userSettings))
                {
                    try
                    {
                        userSettingsXml.Load(_userSettings);
                        var language = userSettingsXml.SelectSingleNode("Settings/UI/Language");
                        language.InnerText = SettingsLanguage.SelectedValue.ToString();
                    }
                    catch
                    {
                        File.Delete(_userSettings);

                        var setting = userSettingsXml.AppendChild(userSettingsXml.CreateElement("Settings"));
                        var ui      = setting.AppendChild(userSettingsXml.CreateElement("UI"));

                        var persistentValue = setting.AppendChild(userSettingsXml.CreateElement("PersistentValue"));
                        var chat            = persistentValue.AppendChild(userSettingsXml.CreateElement("Chat"));
                        chat.InnerXml = "<DefaultChatGroup Type=\"string\">" + Self.currentLanguage + "</DefaultChatGroup>";
                        ui.InnerXml   = "<Language Type=\"string\">" + SettingsLanguage.SelectedValue + "</Language>";

                        var directoryInfo = Directory.CreateDirectory(Path.GetDirectoryName(_userSettings));
                    }
                }
                else
                {
                    try
                    {
                        var setting = userSettingsXml.AppendChild(userSettingsXml.CreateElement("Settings"));
                        var ui      = setting.AppendChild(userSettingsXml.CreateElement("UI"));

                        var persistentValue = setting.AppendChild(userSettingsXml.CreateElement("PersistentValue"));
                        var chat            = persistentValue.AppendChild(userSettingsXml.CreateElement("Chat"));
                        chat.InnerXml = "<DefaultChatGroup Type=\"string\">" + Self.currentLanguage + "</DefaultChatGroup>";
                        ui.InnerXml   = "<Language Type=\"string\">" + SettingsLanguage.SelectedValue + "</Language>";

                        var directoryInfo = Directory.CreateDirectory(Path.GetDirectoryName(_userSettings));
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(null, "There was an error saving your settings to actual file. Restoring default.\n" + ex.Message, "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        File.Delete(_userSettings);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(null, "There was an error saving your settings to actual file. Restoring default.\n" + ex.Message, "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Error);
                File.Delete(_userSettings);
            }

            /* Save XML Settings */
            userSettingsXml.Save(_userSettings);

            //DialogResult = DialogResult.OK;
            Close();
        }
Ejemplo n.º 29
0
        private void DebugWindow_Load(object sender, EventArgs e)
        {
            data.AutoGenerateColumns = true;

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

            string TracksHigh = (SettingFile.Read("TracksHigh") == "1") ? "True" : "False";
            string Password   = (!String.IsNullOrEmpty(SettingFile.Read("Password"))) ? "True" : "False";
            string SkipUpdate = (SettingFile.Read("SkipUpdate") == "1") ? "True" : "False";

            string Antivirus   = String.Empty;
            string Firewall    = String.Empty;
            string AntiSpyware = String.Empty;

            if (!DetectLinux.UnixDetected())
            {
                try
                {
                    Antivirus   = (String.IsNullOrEmpty(AntivirusInstalled())) ? "---" : AntivirusInstalled();
                    Firewall    = (String.IsNullOrEmpty(AntivirusInstalled("FirewallProduct"))) ? "---" : AntivirusInstalled("FirewallProduct");
                    AntiSpyware = (String.IsNullOrEmpty(AntivirusInstalled("AntiSpywareProduct"))) ? "---" : AntivirusInstalled("AntiSpywareProduct");
                }
                catch
                {
                    Antivirus   = "Unknown";
                    Firewall    = "Unknown";
                    AntiSpyware = "Unknown";
                }
            }

            string LauncherPosition = "";
            string OS = "";

            if (DetectLinux.WineDetected())
            {
                OS = "Wine";
            }
            else if (DetectLinux.LinuxDetected())
            {
                OS = "Linux";
            }
            else if (DetectLinux.MacOSDetected())
            {
                OS = "MacOS";
            }
            else
            {
                OS = (from x in new ManagementObjectSearcher("SELECT Caption FROM Win32_OperatingSystem").Get().Cast <ManagementObject>()
                      select x.GetPropertyValue("Caption")).FirstOrDefault().ToString();
            }

            if (SettingFile.Read("LauncherPosX") + "x" + SettingFile.Read("LauncherPosY") == "x")
            {
                LauncherPosition = "Windows Default Position";
            }
            else
            {
                LauncherPosition = SettingFile.Read("LauncherPosX") + "x" + SettingFile.Read("LauncherPosY");
            }

            long          memKb = 0;
            ulong         lpFreeBytesAvailable = 0;
            List <string> GPUs            = new List <string>();
            string        Win32_Processor = "";

            if (!DetectLinux.UnixDetected())
            {
                Kernel32.GetPhysicallyInstalledSystemMemory(out memKb);

                ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT Name FROM Win32_VideoController");
                string graphicsCard = string.Empty;
                foreach (ManagementObject mo in searcher.Get())
                {
                    foreach (PropertyData property in mo.Properties)
                    {
                        GPUs.Add(property.Value.ToString());
                    }
                }

                Win32_Processor = (from x in new ManagementObjectSearcher("SELECT Name FROM Win32_Processor").Get().Cast <ManagementObject>()
                                   select x.GetPropertyValue("Name")).FirstOrDefault().ToString();

                Kernel32.GetDiskFreeSpaceEx(SettingFile.Read("InstallationDirectory"), out lpFreeBytesAvailable, out ulong lpTotalNumberOfBytes, out ulong lpTotalNumberOfFreeBytes);
            }

            var Win32_VideoController = string.Join(" | ", GPUs);

            var settings = new List <ListType> {
                new ListType {
                    Name = "InstallationDirectory", Value = SettingFile.Read("InstallationDirectory")
                },
                new ListType {
                    Name = "HWID", Value = Security.FingerPrint.Value()
                },
                new ListType {
                    Name = "Server Address", Value = ServerIP
                },
                new ListType {
                    Name = "Server Name", Value = ServerName
                },
                new ListType {
                    Name = "Credentials Saved", Value = Password
                },
                new ListType {
                    Name = "Language", Value = SettingFile.Read("Language")
                },
                new ListType {
                    Name = "TracksHigh", Value = TracksHigh
                },
                new ListType {
                    Name = "SkipUpdate", Value = SkipUpdate
                },
                new ListType {
                    Name = "LauncherPos", Value = LauncherPosition
                },
                new ListType {
                    Name = "ProxyPort", Value = Self.ProxyPort.ToString()
                },

                new ListType {
                    Name = "", Value = ""
                },
            };

            if (DetectLinux.UnixDetected())
            {
                var embedded = Directory.Exists("wine");
                settings.Add(new ListType {
                    Name = "Embedded Wine", Value = embedded.ToString()
                });
                if (!embedded)
                {
                    settings.Add(new ListType {
                        Name = "Wine version", Value = WineManager.GetWineVersion()
                    });
                }
                settings.Add(new ListType {
                    Name = "", Value = ""
                });
            }

            if (!DetectLinux.UnixDetected())
            {
                settings.AddRange(new[] {
                    new ListType {
                        Name = "Antivirus", Value = Antivirus
                    },
                    new ListType {
                        Name = "Firewall", Value = Firewall
                    },
                    new ListType {
                        Name = "AntiSpyware", Value = AntiSpyware
                    },
                    new ListType {
                        Name = "", Value = ""
                    },
                    new ListType {
                        Name = "CPU", Value = Win32_Processor
                    },
                    new ListType {
                        Name = "GPU", Value = Win32_VideoController
                    },
                    new ListType {
                        Name = "RAM", Value = (memKb / 1024).ToString() + "MB"
                    },
                    new ListType {
                        Name = "Disk Space Left", Value = FormatFileSize(lpFreeBytesAvailable)
                    },
                    new ListType {
                        Name = "", Value = ""
                    }
                });
            }
            settings.AddRange(new[] {
                new ListType {
                    Name = "Operating System", Value = OS
                },
                new ListType {
                    Name = "Environment Version", Value = Environment.OSVersion.Version.ToString()
                },
                new ListType {
                    Name = "Screen Resolution", Value = Screen.PrimaryScreen.Bounds.Width + "x" + Screen.PrimaryScreen.Bounds.Height
                }
            });

            data.DataSource = settings;

            DataGridViewCellStyle style = new DataGridViewCellStyle();

            style.Font = new Font(data.Font, FontStyle.Bold);
            data.Columns[0].DefaultCellStyle = style;

            data.Columns[0].Width += 50;

            int size_x = 1024;
            int size_y = 450;

            data.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.Size = new Size(size_x, size_y);
        }
Ejemplo n.º 30
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;
                }
            }
        }