/// <summary> /// Evaluates a function and returns its value. It is assumed the current /// position is at the opening parenthesis of the argument list. /// </summary> /// <param name="parser">TextParser object</param> /// <param name="name">Name of function</param> /// <param name="pos">Position at start of function</param> /// <returns></returns> protected double EvaluateFunction(TextParser parser, string name, int pos) { double result = default(double); // Parse function parameters List <double> parameters = ParseParameters(parser); // We found a function reference FunctionStatus status = FunctionStatus.UndefinedFunction; if (ProcessFunction != null) { FunctionEventArgs args = new FunctionEventArgs(); args.Name = name; args.Parameters = parameters; args.Result = result; args.Status = FunctionStatus.OK; ProcessFunction(this, args); result = args.Result; status = args.Status; } if (status == FunctionStatus.UndefinedFunction) { throw new EvalException(String.Format(ErrUndefinedFunction, name), pos); } if (status == FunctionStatus.WrongParameterCount) { throw new EvalException(ErrWrongParamCount, pos); } return(result); }
private void CheckGameFilesDirectoryPrevention() { if (!DetectLinux.LinuxDetected()) { switch (FunctionStatus.CheckFolder(_newGameFilesPath)) { case FolderType.IsSameAsLauncherFolder: Directory.CreateDirectory("Game Files"); Log.Error("LAUNCHER: Installing NFSW in same directory where the launcher resides is NOT recommended."); MessageBox.Show(null, string.Format("Installing NFSW in same directory where the launcher resides is not allowed.\nInstead, 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 NOT allowed!"); MessageBox.Show(null, string.Format("(╯°□°)╯︵ ┻━┻\n\nInstalling NFSW in the Temp Folder is NOT allowed!\nInstead, 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 not recommended or allowed.\nInstead, 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(); } }
public async Task <IActionResult> GetFunctionStatus(string name, [FromServices] IScriptJobHost scriptHost = null) { FunctionStatus status = new FunctionStatus(); // first see if the function has any errors // if the host is not running or is offline // there will be no error info if (scriptHost != null && scriptHost.FunctionErrors.TryGetValue(name, out ICollection <string> functionErrors)) { status.Errors = functionErrors; } else { // if we don't have any errors registered, make sure the function exists // before returning empty errors var result = await _functionsManager.GetFunctionsMetadata(includeProxies : true); var function = result.FirstOrDefault(p => p.Name.ToLowerInvariant() == name.ToLowerInvariant()); if (function == null) { return(NotFound()); } } return(Ok(status)); }
/// <summary> /// Constructs a new <see cref="FunctionEventArgs"/> instance. /// </summary> /// <param name="name">Name of the function.</param> /// <param name="parameters">Parameters being passed to the function.</param> /// <param name="result">Returns the function result.</param> /// <param name="status">Returns the function status.</param> public FunctionEventArgs(string name, Variable[] parameters, Variable result, FunctionStatus status = FunctionStatus.OK) { Name = name; Parameters = parameters; Result = result; Status = status; }
public object Invoke(IBindingEnvironment environment, object[] arguments) { int argcount = 0; if (arguments != null) { argcount = arguments.Length; } if (this.arity != argcount) { if (!this.hasvariableparameters || this.arity - 1 > argcount) { throw new InvalidOperationException("Invalid number of arguments"); } } BindingEnvironment newenv = new BindingEnvironment(environment); if (this.hasvariableparameters) { for (int k = 0; k < this.arity - 1; k++) { newenv.SetLocalValue(this.parameterNames[k], arguments[k]); } if (argcount == 0) { newenv.SetLocalValue(this.parameterNames[0], new object[] { }); } else { object[] pars = new object[argcount - this.arity + 1]; Array.Copy(arguments, argcount - pars.Length, pars, 0, pars.Length); newenv.SetLocalValue(this.parameterNames[this.arity - 1], pars); } } else { for (int k = 0; k < argcount; k++) { newenv.SetLocalValue(this.parameterNames[k], arguments[k]); } } FunctionStatus fstatus = Machine.CurrentFunctionStatus; Machine.CurrentFunctionStatus = new FunctionStatus(); try { this.body.Execute(newenv); return(Machine.CurrentFunctionStatus.ReturnValue); } finally { Machine.CurrentFunctionStatus = fstatus; } }
public async Task FunctionWithIndexingError_ReturnsError() { FunctionStatus status = await Fixture.Host.GetFunctionStatusAsync("FunctionIndexingError"); string error = status.Errors.Single(); Assert.Equal("Microsoft.Azure.WebJobs.Host: Error indexing method 'Functions.FunctionIndexingError'. Microsoft.Azure.WebJobs.Extensions.Storage: Storage account connection string 'setting_does_not_exist' does not exist. Make sure that it is a defined App Setting.", error); }
public Function(Guid id, string name, string img1, string intro, string content, FunctionStatus status) { this.Id = id; this.Functionname = name; this.Firstimg = img1; this.Introduction = intro; this.Content = content; this.Status = status; }
public async Task ErrorFunction_DoesNotBringDownHost() { // verify the cached error for the invalid function FunctionStatus status = await Fixture.Host.GetFunctionStatusAsync("Invalid"); string error = status.Errors.Single(); Assert.Equal("'invalid' is not a valid binding direction.", error); }
public async Task <FunctionStatus> AddFunctionStatus(FunctionStatus functionStatus) { try { return(functionStatus = await maintRepo.AddFunctionStatus(functionStatus)); } catch (Exception) { throw; } }
public async Task <FunctionStatus> AddFunctionStatus(FunctionStatus functionStatus) { try { using (var unitOfWork = unitOfWorkFactory.Create()) { var entity = (FunctionStatusEntity)functionStatus; var addedStatus = unitOfWork.Repository().Add <FunctionStatusEntity>(entity); var response = await unitOfWork.CommitAsync(); return((FunctionStatus)addedStatus); } } catch (Exception) { throw; } }
public async Task <IHttpActionResult> AddFunctionStatus([FromBody] FunctionStatus functionStatus) { try { var addedStatus = await maintEngine.AddFunctionStatus(functionStatus); if (addedStatus != null) { return(Ok(addedStatus)); } else { return(Content(HttpStatusCode.InternalServerError, "An error has occured and no resource was created")); } } catch (Exception ex) { return(Content(HttpStatusCode.InternalServerError, ex)); } }
public IActionResult GetFunctionStatus(string name, [FromServices] IScriptJobHost scriptHost) { FunctionStatus status = new FunctionStatus(); // first see if the function has any errors if (scriptHost.FunctionErrors.TryGetValue(name, out ICollection <string> functionErrors)) { status.Errors = functionErrors; } else { // if we don't have any errors registered, make sure the function exists // before returning empty errors FunctionDescriptor function = scriptHost.Functions.FirstOrDefault(p => p.Name.ToLowerInvariant() == name.ToLowerInvariant()); if (function == null) { return(NotFound()); } } return(Ok(status)); }
public FunctionStatus GetFunctionStatus(string name) { FunctionStatus status = new FunctionStatus(); Collection <string> functionErrors = null; // first see if the function has any errors if (_scriptHostManager.Instance.FunctionErrors.TryGetValue(name, out functionErrors)) { status.Errors = functionErrors; } else { // if we don't have any errors registered, make sure the function exists // before returning empty errors FunctionDescriptor function = _scriptHostManager.Instance.Functions.FirstOrDefault(p => p.Name.ToLowerInvariant() == name.ToLowerInvariant()); if (function == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } } return(status); }
public static FunctionLogDetails UpdateFunctionLogRequest(FunctionLogDetails functionLogDetails, FunctionStatus status, string message = null) { if (functionLogDetails != null) { functionLogDetails.Status = status; functionLogDetails.EndDate = DateTime.UtcNow; functionLogDetails.Message = message; } return(functionLogDetails); }
private static void DoRunChecks(Arguments args) { /* Splash Screen */ if (!Debugger.IsAttached && !DetectLinux.LinuxDetected()) { _SplashScreen = new Thread(new ThreadStart(SplashScreen)); _SplashScreen.Start(); } File.Delete("communication.log"); File.Delete("launcher.log"); Log.StartLogging(); if (!DetectLinux.LinuxDetected()) { //Check if User has .NETFramework 4.6.2 or later Installed const string subkey = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\"; using (var ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(subkey)) { if (ndpKey != null && ndpKey.GetValue("Release") != null && (int)ndpKey.GetValue("Release") >= 394802) { /* Check Up to Date Certificate Status */ try { WebClient update_data = new WebClient(); update_data.CancelAsync(); update_data.Headers.Add("user-agent", "GameLauncher " + Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)"); update_data.DownloadStringAsync(new Uri("http://crl.carboncrew.org/RCA-Info.json")); update_data.DownloadStringCompleted += (sender, e) => { JsonRootCA API = JsonConvert.DeserializeObject <JsonRootCA>(e.Result); if (API.CN != null) { Log.Info("CERTIFICATE STORE: Setting Common Name -> " + API.CN); CertificateStore.RootCACommonName = API.CN; } if (API.Subject != null) { Log.Info("CERTIFICATE STORE: Setting Subject Name -> " + API.Subject); CertificateStore.RootCASubjectName = API.Subject; } if (API.Ids != null) { foreach (IdsModel entries in API.Ids) { if (entries.Serial != null) { Log.Info("CERTIFICATE STORE: Setting Serial Number -> " + entries.Serial); CertificateStore.RootCASerial = entries.Serial; } } } if (API.File != null) { foreach (FileModel entries in API.File) { if (entries.Name != null) { Log.Info("CERTIFICATE STORE: Setting Root CA File Name -> " + entries.Name); CertificateStore.RootCAFileName = entries.Name; } if (entries.Cer != null) { Log.Info("CERTIFICATE STORE: Setting Root CA File URL -> " + entries.Cer); CertificateStore.RootCAFileURL = entries.Cer; } } } }; } catch { Log.Error("CERTIFICATE STORE: Unable to Retrive Latest Certificate Information"); } } else { DialogResult frameworkError = MessageBox.Show(null, "This application requires one of the following versions of the .NET Framework:\n" + " .NETFramework, Version=v4.6.2 \n\nDo you want to install this .NET Framework version now?", "GameLauncher.exe - This application could not be started.", MessageBoxButtons.YesNo, MessageBoxIcon.Error); if (frameworkError == DialogResult.Yes) { Process.Start("https://dotnet.microsoft.com/download/dotnet-framework"); } /* Close Splash Screen (Just in Case) */ if (IsSplashScreenLive == true) { _SplashScreen.Abort(); } Process.GetProcessById(Process.GetCurrentProcess().Id).Kill(); } } } FileSettingsSave.NullSafeSettings(); FileAccountSave.NullSafeAccount(); FunctionStatus.CurrentLanguage = CultureInfo.CurrentCulture.Name.Split('-')[0].ToUpper(); Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US"); Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture("en-US"); if (UriScheme.IsCommandLineArgumentsInstalled()) { UriScheme.InstallCommandLineArguments(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), AppDomain.CurrentDomain.FriendlyName)); if (args.Parse != null) { new UriScheme(args.Parse); } } if (EnableInsider.ShouldIBeAnInsider() == true) { Log.Build("INSIDER: GameLauncher " + Application.ProductVersion + "_" + EnableInsider.BuildNumber()); } else { Log.Build("BUILD: GameLauncher " + Application.ProductVersion); } if (Properties.Settings.Default.IsRestarting) { Properties.Settings.Default.IsRestarting = false; Properties.Settings.Default.Save(); Thread.Sleep(3000); } if (!DetectLinux.LinuxDetected()) { //Windows Firewall Runner if (!string.IsNullOrEmpty(FileSettingsSave.FirewallStatus)) { if (FirewallManager.IsServiceRunning == true && FirewallHelper.FirewallStatus() == true) { string nameOfLauncher = "SBRW - Game Launcher"; string localOfLauncher = Assembly.GetEntryAssembly().Location; string nameOfUpdater = "SBRW - Game Launcher Updater"; string localOfUpdater = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "GameLauncherUpdater.exe"); string groupKeyLauncher = "Game Launcher for Windows"; string descriptionLauncher = "Soapbox Race World"; bool removeFirewallRule = false; bool firstTimeRun = false; if (FileSettingsSave.FirewallStatus == "Not Excluded" || FileSettingsSave.FirewallStatus == "Turned Off" || FileSettingsSave.FirewallStatus == "Service Stopped" || FileSettingsSave.FirewallStatus == "Unknown") { firstTimeRun = true; FileSettingsSave.FirewallStatus = "Excluded"; } else if (FileSettingsSave.FirewallStatus == "Reset") { removeFirewallRule = true; FileSettingsSave.FirewallStatus = "Not Excluded"; } //Inbound & Outbound FirewallHelper.DoesRulesExist(removeFirewallRule, firstTimeRun, nameOfLauncher, localOfLauncher, groupKeyLauncher, descriptionLauncher, FirewallProtocol.Any); FirewallHelper.DoesRulesExist(removeFirewallRule, firstTimeRun, nameOfUpdater, localOfUpdater, groupKeyLauncher, descriptionLauncher, FirewallProtocol.Any); //This Removes the Game File Exe From Firewall //To Find the one that Adds the Exe To Firewall -> Search for `OnDownloadFinished()` string CurrentGameFilesExePath = Path.Combine(FileSettingsSave.GameInstallation + "\\nfsw.exe"); if (File.Exists(CurrentGameFilesExePath) && removeFirewallRule == true) { string nameOfGame = "SBRW - Game"; string localOfGame = CurrentGameFilesExePath; string groupKeyGame = "Need for Speed: World"; string descriptionGame = groupKeyGame; //Inbound & Outbound FirewallHelper.DoesRulesExist(removeFirewallRule, firstTimeRun, nameOfGame, localOfGame, groupKeyGame, descriptionGame, FirewallProtocol.Any); } } else if (FirewallManager.IsServiceRunning == true && FirewallHelper.FirewallStatus() == false) { FileSettingsSave.FirewallStatus = "Turned Off"; } else { FileSettingsSave.FirewallStatus = "Service Stopped"; } FileSettingsSave.SaveSettings(); } } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(true); /* Set Launcher Directory */ Log.Info("CORE: Setting up current directory: " + Path.GetDirectoryName(Application.ExecutablePath)); Directory.SetCurrentDirectory(Path.GetDirectoryName(Application.ExecutablePath)); if (!DetectLinux.LinuxDetected()) { Log.Info("CORE: Checking current directory"); switch (FunctionStatus.CheckFolder(Directory.GetCurrentDirectory())) { case FolderType.IsTempFolder: case FolderType.IsUsersFolders: case FolderType.IsProgramFilesFolder: case FolderType.IsWindowsFolder: case FolderType.IsRootFolder: String constructMsg = String.Empty; constructMsg += "Bu Dizinde NFS World Dosyaları Yok.\nLütfen Bu Başlatıcı Dosyalarını oyunun Dosyalarının Olduğu dizine atın NOT:\n\n"; constructMsg += "• X:\\ (Anadizin, veya C:\\ ve D:\\)\n"; constructMsg += "• C:\\Program Files\n"; constructMsg += "• C:\\Program Files (x86)\n"; constructMsg += "• C:\\Kullanıcı ('Masaüstü' veya 'Belgeler')\n"; constructMsg += "• C:\\Windows\n\n"; constructMsg += "Dizinlerine Kurmayınız!"; MessageBox.Show(null, constructMsg, "NFSTR.Com Başlatıcı", MessageBoxButtons.OK, MessageBoxIcon.Error); Environment.Exit(0); break; } if (!FunctionStatus.HasWriteAccessToFolder(Path.GetDirectoryName(Application.ExecutablePath))) { MessageBox.Show("Bu Uygulama Admin Yetkileri Gerektirir"); } //Update this text file if a new GameLauncherUpdater.exe has been delployed - DavidCarbon try { try { switch (APIStatusChecker.CheckStatus("http://api.github.com/repos/SoapboxRaceWorld/GameLauncherUpdater/releases/latest")) { case APIStatus.Online: WebClient update_data = new WebClient(); update_data.CancelAsync(); update_data.Headers.Add("user-agent", "GameLauncher " + Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)"); update_data.DownloadStringAsync(new Uri("http://api.github.com/repos/SoapboxRaceWorld/GameLauncherUpdater/releases/latest")); update_data.DownloadStringCompleted += (sender, e) => { GitHubRelease GHAPI = JsonConvert.DeserializeObject <GitHubRelease>(e.Result); if (GHAPI.TagName != null) { Log.Info("LAUNCHER UPDATER: Setting Latest Version -> " + GHAPI.TagName); LatestUpdaterBuildVersion = GHAPI.TagName; } Log.Info("LAUNCHER UPDATER: Latest Version -> " + LatestUpdaterBuildVersion); }; break; default: Log.Error("LAUNCHER UPDATER: Failed to Retrive Latest Updater Information from GitHub"); break; } } catch { var GetLatestUpdaterBuildVersion = new WebClient().DownloadString(URLs.secondstaticapiserver + "/Version.txt"); if (!string.IsNullOrEmpty(GetLatestUpdaterBuildVersion)) { Log.Info("LAUNCHER UPDATER: Setting Latest Version -> " + GetLatestUpdaterBuildVersion); LatestUpdaterBuildVersion = GetLatestUpdaterBuildVersion; } } Log.Info("LAUNCHER UPDATER: Fail Safe Latest Version -> " + LatestUpdaterBuildVersion); } catch (Exception ex) { Log.Error("LAUNCHER UPDATER: Failed to get new version file: " + ex.Message); } } if (!DetectLinux.LinuxDetected()) { //Windows 7 Fix if (WindowsProductVersion.GetWindowsNumber() == 6.1 && (string.IsNullOrEmpty(FileSettingsSave.Win7UpdatePatches))) { if (ManagementSearcher.GetInstalledHotFix("KB3020369") == false || ManagementSearcher.GetInstalledHotFix("KB3125574") == false) { String messageBoxPopupKB = String.Empty; messageBoxPopupKB = "Hey Windows 7 User, we've detected a potential issue of some missing Updates that are required.\n"; messageBoxPopupKB += "We found that these Windows Update packages are showing as not installed:\n\n"; if (ManagementSearcher.GetInstalledHotFix("KB3020369") == false) { messageBoxPopupKB += "- Update KB3020369\n"; } if (ManagementSearcher.GetInstalledHotFix("KB3125574") == false) { messageBoxPopupKB += "- Update KB3125574\n"; } messageBoxPopupKB += "\nAditionally, we must add a value to the registry:\n"; messageBoxPopupKB += "- HKLM/SYSTEM/CurrentControlSet/Control/SecurityProviders\n/SCHANNEL/Protocols/TLS 1.2/Client\n"; messageBoxPopupKB += "- Value: DisabledByDefault -> 0\n\n"; messageBoxPopupKB += "Would you like to add those values?"; DialogResult replyPatchWin7 = MessageBox.Show(null, messageBoxPopupKB, "SBRW Launcher", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); if (replyPatchWin7 == DialogResult.Yes) { RegistryKey key = Registry.LocalMachine.CreateSubKey(@"SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client"); key.SetValue("DisabledByDefault", 0x0); MessageBox.Show(null, "Registry option set, Remember that the changes may require a system reboot to take effect", "SBRW Launcher", MessageBoxButtons.OK, MessageBoxIcon.Warning); FileSettingsSave.Win7UpdatePatches = "1"; } else { MessageBox.Show(null, "Roger that, There may be some issues connecting to the servers.", "SBRW Launcher", MessageBoxButtons.OK, MessageBoxIcon.Warning); FileSettingsSave.Win7UpdatePatches = "0"; } FileSettingsSave.SaveSettings(); } } if (!RedistributablePackage.IsInstalled(RedistributablePackageVersion.VC2015to2019x86)) { var result = MessageBox.Show( "You do not have the 32-bit 2015-2019 VC++ Redistributable Package installed.\n \nThis will install in the Background\n \nThis may restart your computer. \n \nClick OK to install it.", "Compatibility", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning); if (result != DialogResult.OK) { MessageBox.Show("The game will not be started.", "Compatibility", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } var wc = new WebClient(); wc.DownloadFile("https://aka.ms/vs/16/release/VC_redist.x86.exe", "VC_redist.x86.exe"); var proc = Process.Start(new ProcessStartInfo { Verb = "runas", Arguments = "/quiet", FileName = "VC_redist.x86.exe" }); if (proc == null) { MessageBox.Show("Failed to run package installer. The game will not be started.", "Compatibility", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } if (Environment.Is64BitOperatingSystem == true) { if (!RedistributablePackage.IsInstalled(RedistributablePackageVersion.VC2015to2019x64)) { var result = MessageBox.Show( "You do not have the 64-bit 2015-2019 VC++ Redistributable Package installed.\n \nThis will install in the Background\n \nThis may restart your computer. \n \nClick OK to install it.", "Compatibility", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning); if (result != DialogResult.OK) { MessageBox.Show("The game will not be started.", "Compatibility", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } var wc = new WebClient(); wc.DownloadFile("https://aka.ms/vs/16/release/VC_redist.x64.exe", "VC_redist.x64.exe"); var proc = Process.Start(new ProcessStartInfo { Verb = "runas", Arguments = "/quiet", FileName = "VC_redist.x64.exe" }); if (proc == null) { MessageBox.Show("Failed to run package installer. The game will not be started.", "Compatibility", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } } } Console.WriteLine("Application path: " + Path.GetDirectoryName(Application.ExecutablePath)); if (!string.IsNullOrEmpty(FileSettingsSave.GameInstallation)) { if (!FunctionStatus.HasWriteAccessToFolder(FileSettingsSave.GameInstallation)) { MessageBox.Show("This application requires admin priviledge. Restarting..."); } } //StaticConfiguration.DisableErrorTraces = false; if (!File.Exists("servers.json")) { try { File.WriteAllText("servers.json", "[]"); } catch { /* ignored */ } } if (Properties.Settings.Default.IsRestarting) { Properties.Settings.Default.IsRestarting = false; Properties.Settings.Default.Save(); Thread.Sleep(3000); } Theming.CheckIfThemeExists(); /* Check If Launcher Failed to Connect to any APIs */ 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) { /* Close Splash Screen (Just in Case) */ if (IsSplashScreenLive == true) { _SplashScreen.Abort(); } Process.GetProcessById(Process.GetCurrentProcess().Id).Kill(); } } LanguageListUpdater.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); } /* Check Permission for Launcher Folder and File it Self */ FileORFolderPermissions.CheckLauncherPerms("Folder", Path.Combine(AppDomain.CurrentDomain.BaseDirectory)); Log.Info("PROXY: Starting Proxy"); ServerProxy.Instance.Start(); /* Check ServerList Status */ if (FunctionStatus.ServerListStatus != "Loaded") { ServerListUpdater.GetList(); } /* Close Splash Screen */ if (IsSplashScreenLive == true) { _SplashScreen.Abort(); } Log.Visuals("CORE: Starting MainScreen"); Application.Run(new MainScreen()); }
private async Task <bool> IsReady(AzureHttpClient client, string sitename) { bool isReady = false; for (int i = 0; i < ATTEMPTS && !isReady; i++) { FunctionStatusWrapper statusWrapper = await client.RequestAzure <FunctionStatusWrapper>(HttpMethod.Get, $"/providers/Microsoft.Web/sites/{sitename}/deployments", "2016-08-01"); if (statusWrapper != null && !statusWrapper.Value.IsNullOrEmpty()) { bool hasFinishedDeployment = true; for (int j = 0; j < statusWrapper.Value.Count && hasFinishedDeployment; j++) { FunctionStatus status = statusWrapper.Value[j]; hasFinishedDeployment = status != null && status.Properties != null && !string.IsNullOrEmpty(status.Properties.LogUrl); if (hasFinishedDeployment) { List <FunctionStatusLog> logs = await client.Request <List <FunctionStatusLog> >(HttpMethod.Get, status.Properties.LogUrl); hasFinishedDeployment = !logs.IsNullOrEmpty(); if (hasFinishedDeployment) { bool isDeployed = false; for (int k = 0; k < logs.Count && !isDeployed; k++) { isDeployed = logs[k].Message.Contains(SUCCESS); } hasFinishedDeployment = isDeployed && status.Properties.Active && status.Properties.Complete && status.Properties.EndTime != null && status.Properties.Status == STATUS; } } } if (hasFinishedDeployment) { FunctionWrapper functionWrapper = await client.RequestAzure <FunctionWrapper>(HttpMethod.Get, $"/providers/Microsoft.Web/sites/{sitename}/functions", "2016-08-01"); if (functionWrapper != null && !functionWrapper.Value.IsNullOrEmpty()) { bool areFunctionsReady = true; for (int j = 0; j < functionWrapper.Value.Count && areFunctionsReady; j++) { Function function = functionWrapper.Value[j]; areFunctionsReady = function != null && function.Properties != null && function.Properties.Config != null && !function.Properties.Config.Disabled; } isReady = areFunctionsReady; } } } if (!isReady) { await Task.Delay(WAIT); } } return(isReady); }
private void SetVisuals() { /*******************************/ /* Set Window Name / * /*******************************/ Text = "Register - SBRW Launcher: v" + Application.ProductVersion; /*******************************/ /* Set Initial position & Icon / * /*******************************/ FunctionStatus.CenterParent(this); /*******************************/ /* Set Font / * /*******************************/ FontFamily DejaVuSans = FontWrapper.Instance.GetFontFamily("DejaVuSans.ttf"); FontFamily DejaVuSansBold = FontWrapper.Instance.GetFontFamily("DejaVuSans-Bold.ttf"); float MainFontSize = UnixOS.Detected() ? 9f : 9f * 96f / CreateGraphics().DpiY; float SecondaryFontSize = UnixOS.Detected() ? 8f : 8f * 96f / CreateGraphics().DpiY; Font = new Font(DejaVuSans, SecondaryFontSize, FontStyle.Regular); /* Registering Panel */ RegisterEmail.Font = new Font(DejaVuSans, MainFontSize, FontStyle.Regular); RegisterPassword.Font = new Font(DejaVuSans, MainFontSize, FontStyle.Regular); RegisterConfirmPassword.Font = new Font(DejaVuSans, MainFontSize, FontStyle.Regular); RegisterTicket.Font = new Font(DejaVuSans, MainFontSize, FontStyle.Regular); RegisterAgree.Font = new Font(DejaVuSansBold, MainFontSize, FontStyle.Bold); RegisterButton.Font = new Font(DejaVuSansBold, MainFontSize, FontStyle.Bold); RegisterCancel.Font = new Font(DejaVuSansBold, MainFontSize, FontStyle.Bold); CurrentWindowInfo.Font = new Font(DejaVuSansBold, MainFontSize, FontStyle.Bold); /********************************/ /* Set Theme Colors & Images / * /********************************/ /* Set Background with Transparent Key */ BackgroundImage = Theming.RegisterScreen; TransparencyKey = Theming.RegisterScreenTransparencyKey; CurrentWindowInfo.ForeColor = Theming.FivithTextForeColor; RegisterEmail.BackColor = Theming.Input; RegisterEmail.ForeColor = Theming.FivithTextForeColor; RegisterEmailBorder.Image = Theming.BorderEmail; RegisterPasswordBorder.Image = Theming.BorderPassword; RegisterPassword.BackColor = Theming.Input; RegisterPassword.ForeColor = Theming.FivithTextForeColor; RegisterConfirmPasswordBorder.Image = Theming.BorderPassword; RegisterConfirmPassword.BackColor = Theming.Input; RegisterConfirmPassword.ForeColor = Theming.FivithTextForeColor; RegisterTicketBorder.Image = Theming.BorderTicket; RegisterTicket.BackColor = Theming.Input; RegisterTicket.ForeColor = Theming.FivithTextForeColor; RegisterAgree.ForeColor = Theming.WinFormWarningTextForeColor; RegisterButton.BackgroundImage = Theming.GreenButton; RegisterButton.ForeColor = Theming.SeventhTextForeColor; RegisterCancel.BackgroundImage = Theming.GrayButton; RegisterCancel.ForeColor = Theming.FivithTextForeColor; /********************************/ /* Events / * /********************************/ RegisterEmail.TextChanged += new EventHandler(RegisterEmail_TextChanged); RegisterPassword.TextChanged += new EventHandler(RegisterPassword_TextChanged); RegisterConfirmPassword.TextChanged += new EventHandler(RegisterConfirmPassword_TextChanged); RegisterTicket.TextChanged += new EventHandler(RegisterTicket_TextChanged); RegisterAgree.CheckedChanged += new EventHandler(RegisterAgree_CheckedChanged); RegisterButton.MouseEnter += Greenbutton_hover_MouseEnter; RegisterButton.MouseLeave += Greenbutton_MouseLeave; RegisterButton.MouseUp += Greenbutton_hover_MouseUp; RegisterButton.MouseDown += Greenbutton_click_MouseDown; RegisterButton.Click += RegisterButton_Click; RegisterCancel.MouseEnter += new EventHandler(Graybutton_hover_MouseEnter); RegisterCancel.MouseLeave += new EventHandler(Graybutton_MouseLeave); RegisterCancel.MouseUp += new MouseEventHandler(Graybutton_hover_MouseUp); RegisterCancel.MouseDown += new MouseEventHandler(Graybutton_click_MouseDown); RegisterCancel.Click += new EventHandler(RegisterCancel_Click); /********************************/ /* Functions / * /********************************/ CurrentWindowInfo.Text = "REGISTER ON \n" + ServerListUpdater.ServerName("Register").ToUpper(); try { if (InformationCache.SelectedServerJSON.requireTicket != null && !string.IsNullOrWhiteSpace(InformationCache.SelectedServerJSON.requireTicket)) { _ticketRequired = InformationCache.SelectedServerJSON.requireTicket.ToLower() == "true"; } else { _ticketRequired = false; } } catch { } /* Show Ticket Box if its Required */ RegisterTicket.Visible = _ticketRequired; RegisterTicketBorder.Visible = _ticketRequired; }
static void Main() { CultureInfo.DefaultThreadCurrentCulture = CultureInfo.GetCultureInfo(InformationCache.Lang.Name); CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.GetCultureInfo(Translations.UI(Translations.Application_Language = InformationCache.Lang.Name)); AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); Application.ThreadException += Application_ThreadException; Application.EnableVisualStyles(); /* We need to set these once and Forget about it (Unless there is a bug such as HttpWebClient) */ AppContext.SetSwitch("Switch.System.Net.DontEnableSchUseStrongCrypto", false); AppContext.SetSwitch("Switch.System.Net.DontEnableSystemDefaultTlsVersions", false); ServicePointManager.DnsRefreshTimeout = (int)TimeSpan.FromSeconds(30).TotalMilliseconds; ServicePointManager.Expect100Continue = true; ServicePointManager.ServerCertificateValidationCallback = (Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => { bool isOk = true; if (sslPolicyErrors != SslPolicyErrors.None) { for (int i = 0; i < chain.ChainStatus.Length; i++) { if (chain.ChainStatus[i].Status == X509ChainStatusFlags.RevocationStatusUnknown) { continue; } chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain; chain.ChainPolicy.RevocationMode = X509RevocationMode.Online; chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 0, 15); chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags; bool chainIsValid = chain.Build((X509Certificate2)certificate); if (!chainIsValid) { isOk = false; break; } } } return(isOk); }; if (Debugger.IsAttached && !NFSW.IsRunning()) { Start(); } else { if (NFSW.IsRunning()) { if (NFSW.DetectGameProcess()) { MessageBox.Show(null, Translations.Database("Program_TextBox_GameIsRunning"), "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } else if (NFSW.DetectGameLauncherSimplified()) { MessageBox.Show(null, Translations.Database("Program_TextBox_SimplifiedIsRunning"), "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } else { MessageBox.Show(null, Translations.Database("Program_TextBox_SBRWIsRunning"), "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } FunctionStatus.LauncherForceClose = true; } if (FunctionStatus.LauncherForceClose) { FunctionStatus.ErrorCloseLauncher("User Tried to Launch SBRW Launcher with one Running Already", false); } else { /* Check if File needs to be Downloaded */ string LZMAPath = Strings.Encode(Path.Combine(Locations.LauncherFolder, Locations.NameLZMA)); if (File.Exists(LZMAPath)) { try { if (new FileInfo(LZMAPath).Length == 0) { File.Delete(LZMAPath); } } catch { } } /* INFO: this is here because this dll is necessary for downloading game files and I want to make it async. * Updated RedTheKitsune Code so it downloads the file if its missing. * It also restarts the launcher if the user click on yes on Prompt. - DavidCarbon */ if (!File.Exists("LZMA.dll")) { try { Uri URLCall = new Uri(URLs.File + "/LZMA.dll"); ServicePointManager.FindServicePoint(URLCall).ConnectionLeaseTimeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds; WebClient Client = new WebClient { Encoding = Encoding.UTF8 }; Client.Headers.Add("user-agent", "SBRW Launcher " + Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)"); Client.DownloadFileCompleted += (object sender, AsyncCompletedEventArgs e) => { if (File.Exists(LZMAPath)) { try { if (new FileInfo(LZMAPath).Length == 0) { File.Delete(LZMAPath); } } catch { } } }; FunctionStatus.LauncherForceClose = true; try { Client.DownloadFile(URLCall, LZMAPath); if (MessageBox.Show(null, Translations.Database("Program_TextBox_LZMA_Redownloaded"), "GameLauncher Restart Required", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes) { LauncherMustRestart = true; } } catch (Exception Error) { FunctionStatus.LauncherForceCloseReason = Error.Message; } finally { if (Client != null) { Client.Dispose(); } } } catch { } } if (FunctionStatus.LauncherForceClose) { FunctionStatus.ErrorCloseLauncher("Closing From Downloaded Missing LZMA", LauncherMustRestart); } else { Mutex No_Java = new Mutex(false, "GameLauncherNFSW-MeTonaTOR"); try { if (No_Java.WaitOne(0, false)) { if (!UnixOS.Detected()) { /* MONO Hates this... */ string[] File_List = { "CommandLine.dll - 2.8.0", "DiscordRPC.dll - 1.0.175.0", "Flurl.dll - 3.0.2", "Flurl.Http.dll - 3.2.0", "INIFileParser.dll - 2.5.2", "LZMA.dll - 9.10 beta", "Microsoft.WindowsAPICodePack.dll - 1.1.0.0", "Microsoft.WindowsAPICodePack.Shell.dll - 1.1.0.0", "Microsoft.WindowsAPICodePack.ShellExtensions.dll - 1.1.0.0", "Nancy.dll - 2.0.0", "Nancy.Hosting.Self.dll - 2.0.0", "Newtonsoft.Json.dll - 13.0.1", "System.Runtime.InteropServices.RuntimeInformation.dll - 4.6.24705.01. " + "Commit Hash: 4d1af962ca0fede10beb01d197367c2f90e92c97", "System.ValueTuple.dll - 4.6.26515.06 @BuiltBy: dlab-DDVSOWINAGE059 " + "@Branch: release/2.1 @SrcCode: https://github.com/dotnet/corefx/tree/30ab651fcb4354552bd4891619a0bdd81e0ebdbf", "WindowsFirewallHelper.dll - 2.1.4.81" }; List <string> Missing_File_List = new List <string>(); foreach (string File_String in File_List) { string[] Split_File_Version = File_String.Split(new string[] { " - " }, StringSplitOptions.None); if (!File.Exists(Path.Combine(Directory.GetCurrentDirectory(), Split_File_Version[0]))) { Missing_File_List.Add(Split_File_Version[0] + " - " + Translations.Database("Program_TextBox_File_NotFound")); } else { try { FileVersionInfo Version_Info = FileVersionInfo.GetVersionInfo(Split_File_Version[0]); string[] Version_Split = Version_Info.ProductVersion.Split('+'); string File_Version = Version_Split[0]; if (File_Version == "") { Missing_File_List.Add(Split_File_Version[0] + " - " + Translations.Database("Program_TextBox_File_Invalid")); } else { if (!HardwareInfo.CheckArchitectureFile(Split_File_Version[0])) { Missing_File_List.Add(Split_File_Version[0] + " - " + Translations.Database("Program_TextBox_File_Invalid_CPU")); } else { if (File_Version != Split_File_Version[1]) { Missing_File_List.Add(Split_File_Version[0] + " - " + Translations.Database("Program_TextBox_File_Invalid_Version") + "(" + Split_File_Version[1] + " != " + File_Version + ")"); } } } } catch { Missing_File_List.Add(Split_File_Version[0] + " - " + Translations.Database("Program_TextBox_File_Invalid")); } } } if (Missing_File_List.Count != 0) { string Message_Display = Translations.Database("Program_TextBox_File_Invalid_Start"); foreach (string File_String in Missing_File_List) { Message_Display += "• " + File_String + "\n"; } FunctionStatus.LauncherForceClose = true; MessageBox.Show(null, Message_Display, "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Error); } } if (FunctionStatus.LauncherForceClose) { FunctionStatus.ErrorCloseLauncher("Closing From Missing .dll Files Check", LauncherMustRestart); } else { Start(); } } else { MessageBox.Show(null, Translations.Database("Program_TextBox_SBRWIsRunning"), "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } finally { No_Java.Close(); No_Java.Dispose(); } } } } }
private static void Start() { DiscordLauncherPresence.Start("Start Up", null); if (!UnixOS.Detected()) { DiscordLauncherPresence.Status("Start Up", "Checking .NET Framework"); try { /* Check if User has a compatible .NET Framework Installed */ if (int.TryParse(RegistryCore.Read("Release", @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\"), out int NetFrame_Version)) { /* For now, allow edge case of Windows 8.0 to run .NET 4.6.1 where upgrading to 8.1 is not possible */ if (WindowsProductVersion.GetWindowsNumber() == 6.2 && NetFrame_Version <= 394254) { if (MessageBox.Show(null, Translations.Database("Program_TextBox_NetFrame_P1") + " .NETFramework, Version=v4.6.1 \n\n" + Translations.Database("Program_TextBox_NetFrame_P2"), "GameLauncher.exe - " + Translations.Database("Program_TextBox_NetFrame_P3"), MessageBoxButtons.YesNo, MessageBoxIcon.Error) == DialogResult.Yes) { Process.Start("https://dotnet.microsoft.com/download/dotnet-framework/net461"); } FunctionStatus.LauncherForceClose = true; } /* Otherwise, all other OS Versions should have 4.6.2 as a Minimum Version */ else if (NetFrame_Version <= 394802) { if (MessageBox.Show(null, Translations.Database("Program_TextBox_NetFrame_P1") + " .NETFramework, Version=v4.6.2 \n\n" + Translations.Database("Program_TextBox_NetFrame_P2"), "GameLauncher.exe - " + Translations.Database("Program_TextBox_NetFrame_P3"), MessageBoxButtons.YesNo, MessageBoxIcon.Error) == DialogResult.Yes) { Process.Start("https://dotnet.microsoft.com/download/dotnet-framework"); } FunctionStatus.LauncherForceClose = true; } else { Log.System("NET-FRAMEWORK: Supported Installed Version"); } } else { Log.Warning("NET-FRAMEWORK: Failed to Parse Version"); } } catch { FunctionStatus.LauncherForceClose = true; } } if (FunctionStatus.LauncherForceClose) { FunctionStatus.ErrorCloseLauncher("Closing From .NET Framework Check", false); } else { /* Splash Screen */ if (!Debugger.IsAttached) { /* Starts Splash Screen */ SplashScreen.ThreadStatus("Start"); } LogToFileAddons.RemoveLogs(); Log.StartLogging(); Log.Info("CURRENT DATE: " + Time.GetTime("Date")); Log.Checking("LAUNCHER MIGRATION: Appdata and/or Roaming Folders"); /* Deletes Folders that will Crash the Launcher (Cleanup Migration) */ try { if (Directory.Exists(Strings.Encode(Path.Combine(Locations.LocalAppDataFolder, "Soapbox_Race_World")))) { Directory.Delete(Strings.Encode(Path.Combine(Locations.LocalAppDataFolder, "Soapbox_Race_World")), true); } if (Directory.Exists(Strings.Encode(Path.Combine(Locations.RoamingAppDataFolder, "Soapbox_Race_World")))) { Directory.Delete(Strings.Encode(Path.Combine(Locations.RoamingAppDataFolder, "Soapbox_Race_World")), true); } if (Directory.Exists(Strings.Encode(Path.Combine(Locations.LocalAppDataFolder, "SoapBoxRaceWorld")))) { Directory.Delete(Strings.Encode(Path.Combine(Locations.LocalAppDataFolder, "SoapBoxRaceWorld")), true); } if (Directory.Exists(Strings.Encode(Path.Combine(Locations.RoamingAppDataFolder, "SoapBoxRaceWorld")))) { Directory.Delete(Strings.Encode(Path.Combine(Locations.RoamingAppDataFolder, "SoapBoxRaceWorld")), true); } if (Directory.Exists(Strings.Encode(Path.Combine(Locations.LocalAppDataFolder, "WorldUnited.gg")))) { Directory.Delete(Strings.Encode(Path.Combine(Locations.LocalAppDataFolder, "WorldUnited.gg")), true); } if (Directory.Exists(Strings.Encode(Path.Combine(Locations.RoamingAppDataFolder, "WorldUnited.gg")))) { Directory.Delete(Strings.Encode(Path.Combine(Locations.RoamingAppDataFolder, "WorldUnited.gg")), true); } } catch (Exception Error) { LogToFileAddons.OpenLog("LAUNCHER MIGRATION", null, Error, null, true); } Log.Completed("LAUNCHER MIGRATION"); Log.Checking("LAUNCHER XML: If File Exists or Not"); DiscordLauncherPresence.Status("Start Up", "Checking if UserSettings XML Exists"); /* Create Default Configuration Files (if they don't already exist) */ if (!File.Exists(Locations.UserSettingsXML)) { try { if (!Directory.Exists(Locations.UserSettingsFolder)) { Directory.CreateDirectory(Locations.UserSettingsFolder); } File.WriteAllBytes(Locations.UserSettingsXML, ExtractResource.AsByte("GameLauncher.Resources.UserSettings.UserSettings.xml")); } catch (Exception Error) { LogToFileAddons.OpenLog("LAUNCHER XML", null, Error, null, true); } } Log.Completed("LAUNCHER XML"); string Insider = string.Empty; if (EnableInsiderDeveloper.Allowed()) { Insider = "DEV TEST "; } else if (EnableInsiderBetaTester.Allowed()) { Insider = "BETA TEST "; } Log.Build(Insider + "BUILD: GameLauncher " + Application.ProductVersion + "_" + InsiderInfo.BuildNumberOnly()); Log.Checking("OS: Detecting"); DiscordLauncherPresence.Status("Start Up", "Checking Operating System"); try { if (UnixOS.Detected()) { InformationCache.OSName = UnixOS.FullName(); Log.System("SYSTEM: Detected OS: " + InformationCache.OSName); } else { InformationCache.OSName = WindowsProductVersion.ConvertWindowsNumberToName(); Log.System("SYSTEM: Detected OS: " + InformationCache.OSName); Log.System("SYSTEM: Windows Build: " + WindowsProductVersion.GetWindowsBuildNumber()); Log.System("SYSTEM: NT Version: " + Environment.OSVersion.VersionString); Log.System("SYSTEM: Video Card: " + HardwareInfo.GPU.CardName()); Log.System("SYSTEM: Driver Version: " + HardwareInfo.GPU.DriverVersion()); } Log.Completed("OS: Detected"); } catch (Exception Error) { LogToFileAddons.OpenLog("SYSTEM", null, Error, null, true); FunctionStatus.LauncherForceCloseReason = "Code: 0\n" + Translations.Database("Program_TextBox_System_Detection") + "\n" + Error.Message; FunctionStatus.LauncherForceClose = true; } if (FunctionStatus.LauncherForceClose) { FunctionStatus.ErrorCloseLauncher("Closing From Operating System Check", false); } else { /* Set Launcher Directory */ Log.Checking("SETUP: Setting Launcher Folder Directory"); Directory.SetCurrentDirectory(Locations.LauncherFolder); Log.Completed("SETUP: Current Directory now Set at -> " + Locations.LauncherFolder); if (!UnixOS.Detected()) { Log.Checking("FOLDER LOCATION: Checking Launcher Folder Directory"); DiscordLauncherPresence.Status("Start Up", "Checking Launcher Folder Locations"); switch (FunctionStatus.CheckFolder(Locations.LauncherFolder)) { case FolderType.IsTempFolder: case FolderType.IsUsersFolders: case FolderType.IsProgramFilesFolder: case FolderType.IsWindowsFolder: case FolderType.IsRootFolder: String Constructed_Msg = String.Empty; Constructed_Msg += Translations.Database("Program_TextBox_Folder_Check_Launcher") + "\n\n"; Constructed_Msg += Translations.Database("Program_TextBox_Folder_Check_Launcher_P2") + "\n"; Constructed_Msg += "• X:\\GameLauncher.exe " + Translations.Database("Program_TextBox_Folder_Check_Launcher_P3") + "\n"; Constructed_Msg += "• C:\\Program Files\n"; Constructed_Msg += "• C:\\Program Files (x86)\n"; Constructed_Msg += "• C:\\Users " + Translations.Database("Program_TextBox_Folder_Check_Launcher_P4") + "\n"; Constructed_Msg += "• C:\\Windows\n\n"; Constructed_Msg += Translations.Database("Program_TextBox_Folder_Check_Launcher_P5") + "\n"; Constructed_Msg += "• 'C:\\Soapbox Race World' " + Translations.Database("Program_TextBox_Folder_Check_Launcher_P6") + " 'C:\\SBRW'\n"; Constructed_Msg += Translations.Database("Program_TextBox_Folder_Check_Launcher_P7") + "\n\n"; MessageBox.Show(null, Constructed_Msg, "GameLauncher", MessageBoxButtons.OK, MessageBoxIcon.Error); FunctionStatus.LauncherForceClose = true; break; } Log.Completed("FOLDER LOCATION: Done"); } if (FunctionStatus.LauncherForceClose) { FunctionStatus.ErrorCloseLauncher("Closing From Invalid Launcher Location", false); } else { Log.Checking("WRITE TEST: Launcher Folder Test"); if (!FunctionStatus.HasWriteAccessToFolder(Locations.LauncherFolder)) { MessageBox.Show(Translations.Database("Program_TextBox_Folder_Write_Test")); } Log.Completed("WRITE TEST: Passed"); Log.Checking("INI FILES: Doing Nullsafe"); DiscordLauncherPresence.Status("Start Up", "Doing NullSafe ini Files"); FileSettingsSave.NullSafeSettings(); FileAccountSave.NullSafeAccount(); Log.Completed("INI FILES: Done"); /* Sets up Theming */ Theming.CheckIfThemeExists(); Log.Function("APPLICATION: Setting Language"); CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.GetCultureInfo(Translations.UI(Translations.Application_Language = FileSettingsSave.Lang.ToLower(), true)); Log.Completed("APPLICATION: Done Setting Language '" + Translations.UI(Translations.Application_Language) + "'"); /* Windows 7 TLS Check */ if (WindowsProductVersion.GetWindowsNumber() == 6.1) { Log.Checking("SSL/TLS: Windows 7 Detected"); DiscordLauncherPresence.Status("Start Up", "Checking Windows 7 SSL/TLS"); try { String MessageBoxPopupTLS = String.Empty; string keyName = @"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client"; string subKey = "DisabledByDefault"; if (Registry.GetValue(keyName, subKey, null) == null) { MessageBoxPopupTLS = Translations.Database("Program_TextBox_W7_TLS_P1") + "\n\n"; MessageBoxPopupTLS += "- HKLM/SYSTEM/CurrentControlSet/Control/SecurityProviders\n /SCHANNEL/Protocols/TLS 1.2/Client\n"; MessageBoxPopupTLS += "- Value: DisabledByDefault -> 0\n\n"; MessageBoxPopupTLS += Translations.Database("Program_TextBox_W7_TLS_P2") + "\n\n"; MessageBoxPopupTLS += Translations.Database("Program_TextBox_W7_TLS_P3"); /* There is only 'OK' Available because this IS Required */ if (MessageBox.Show(null, MessageBoxPopupTLS, "SBRW Launcher", MessageBoxButtons.OK, MessageBoxIcon.Warning) == DialogResult.OK) { RegistryCore.Write("DisabledByDefault", 0x0, @"SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client"); MessageBox.Show(null, Translations.Database("Program_TextBox_W7_TLS_P4"), "SBRW Launcher", MessageBoxButtons.OK, MessageBoxIcon.Information); } Log.Completed("SSL/TLS: Added Registry Key"); } else { Log.Completed("SSL/TLS: Done"); } } catch (Exception Error) { LogToFileAddons.OpenLog("SSL/TLS", null, Error, null, true); } } /* Windows 7 HotFix Check */ if (WindowsProductVersion.GetWindowsNumber() == 6.1 && string.IsNullOrWhiteSpace(FileSettingsSave.Win7UpdatePatches)) { Log.Checking("HotFixes: Windows 7 Detected"); DiscordLauncherPresence.Status("Start Up", "Checking Windows 7 HotFixes"); try { if (!ManagementSearcher.GetInstalledHotFix("KB3020369") || !ManagementSearcher.GetInstalledHotFix("KB3125574")) { String MessageBoxPopupKB = String.Empty; MessageBoxPopupKB = Translations.Database("Program_TextBox_W7_KB_P1") + "\n"; MessageBoxPopupKB += Translations.Database("Program_TextBox_W7_KB_P2") + "\n\n"; if (!ManagementSearcher.GetInstalledHotFix("KB3020369")) { MessageBoxPopupKB += "- " + Translations.Database("Program_TextBox_W7_KB_P3") + " KB3020369\n"; } if (!ManagementSearcher.GetInstalledHotFix("KB3125574")) { MessageBoxPopupKB += "- " + Translations.Database("Program_TextBox_W7_KB_P3") + " KB3125574\n"; } MessageBoxPopupKB += "\n" + Translations.Database("Program_TextBox_W7_KB_P4") + "\n"; if (MessageBox.Show(null, MessageBoxPopupKB, "SBRW Launcher", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK) { /* Since it's Informational we just need to know if they clicked 'OK' */ FileSettingsSave.Win7UpdatePatches = "1"; } else { /* or if they clicked 'Cancel' */ FileSettingsSave.Win7UpdatePatches = "0"; } FileSettingsSave.SaveSettings(); } Log.Completed("HotFixes: Done"); } catch (Exception Error) { LogToFileAddons.OpenLog("HotFixes", null, Error, null, true); } } } Log.Checking("JSON: Servers File"); try { if (File.Exists(Strings.Encode(Path.Combine(Locations.LauncherFolder, Locations.NameOldServersJSON)))) { if (File.Exists(Strings.Encode(Path.Combine(Locations.LauncherFolder, Locations.NameNewServersJSON)))) { File.Delete(Strings.Encode(Path.Combine(Locations.LauncherFolder, Locations.NameNewServersJSON))); } File.Move( Strings.Encode(Path.Combine(Locations.LauncherFolder, Locations.NameOldServersJSON)), Strings.Encode(Path.Combine(Locations.LauncherFolder, Locations.NameNewServersJSON))); Log.Completed("JSON: Renaming Servers File"); } else if (!File.Exists(Strings.Encode(Path.Combine(Locations.LauncherFolder, Locations.NameNewServersJSON)))) { try { File.WriteAllText( Strings.Encode(Path.Combine(Locations.LauncherFolder, Locations.NameNewServersJSON)), "[]"); Log.Completed("JSON: Created Servers File"); } catch (Exception Error) { LogToFileAddons.OpenLog("JSON SERVER FILE", null, Error, null, true); } } } catch (Exception Error) { LogToFileAddons.OpenLog("JSON SERVER FILE", null, Error, null, true); } Log.Checking("JSON: Done"); if (!string.IsNullOrWhiteSpace(FileSettingsSave.GameInstallation)) { Log.Checking("CLEANLINKS: Game Path"); if (File.Exists(Locations.GameLinksFile)) { ModNetHandler.CleanLinks(Locations.GameLinksFile, FileSettingsSave.GameInstallation); Log.Completed("CLEANLINKS: Done"); } else { Log.Completed("CLEANLINKS: Not Present"); } } Log.Checking("PROXY: Checking if Proxy Is Disabled from User Settings! It's value is " + FileSettingsSave.Proxy); if (FileSettingsSave.Proxy == "0") { Log.Core("PROXY: Starting Proxy (From Startup)"); ServerProxy.Instance.Start("Splash Screen [Program.cs]"); Log.Completed("PROXY: Started"); } else { Log.Completed("PROXY: Disabled"); } Log.Info("REDISTRIBUTABLE: Moved to Function"); /* (Starts Function Chain) Check if Redistributable Packages are Installed */ Redistributable.Check(); } } }
private void SplashScreen_Load(object sender, System.EventArgs e) { FunctionStatus.CenterScreen(this); }
public JsonResult CheckActionUnique(string action, string controller, FunctionStatus status) { if (string.IsNullOrEmpty(action) || string.IsNullOrEmpty(controller)) { return Json(new { success = false, message = "请填写Action Controller 和状态" }); } Function function = this.repository.FindBy(action, controller, status); if (function == null) return Json(new { success = true, message = "it's success" }); else return Json(new { success = false, message = "Action Controller , Status 不唯一!!!" }); }
public static void Latest() { Log.Checking("LAUNCHER UPDATE: Is Version Up to Date or not"); DiscordLauncherPresence.Status("Start Up", "Checking Latest Launcher Release Information"); try { Uri URLCall = new Uri((EnableInsiderBetaTester.Allowed() || EnableInsiderDeveloper.Allowed()) ? URLs.GitHub_Launcher_Beta : URLs.GitHub_Launcher_Stable); ServicePointManager.FindServicePoint(URLCall).ConnectionLeaseTimeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds; var Client = new WebClient { Encoding = Encoding.UTF8 }; if (!WebCalls.Alternative()) { Client = new WebClientWithTimeout { Encoding = Encoding.UTF8 }; } else { Client.Headers.Add("user-agent", "SBRW Launcher " + Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)"); } try { VersionJSON = Client.DownloadString(URLCall); VisualsAPIChecker.GitHubAPI = true; } catch (WebException Error) { APIChecker.StatusCodes(URLCall.GetComponents(UriComponents.HttpRequestUrl, UriFormat.SafeUnescaped), Error, (HttpWebResponse)Error.Response); } catch (Exception Error) { LogToFileAddons.OpenLog("LAUNCHER UPDATE [GITHUB]", null, Error, null, true); } finally { if (Client != null) { Client.Dispose(); } } if (IsJSONValid.ValidJson(VersionJSON) && VisualsAPIChecker.GitHubAPI) { LatestLauncherBuild = (EnableInsiderDeveloper.Allowed() || EnableInsiderBetaTester.Allowed()) ? JsonConvert.DeserializeObject <List <GitHubRelease> >(VersionJSON)[0].TagName : JsonConvert.DeserializeObject <GitHubRelease>(VersionJSON).TagName; Log.Info("LAUNCHER UPDATE: GitHub Latest Version -> " + LatestLauncherBuild); ValidJSONDownload = true; } else { Log.Error("LAUNCHER UPDATE: Failed to retrieve Latest Build information from GitHub"); ValidJSONDownload = false; } } catch (Exception Error) { LogToFileAddons.OpenLog("LAUNCHER UPDATE [GITHUB]", null, Error, null, true); } Log.Completed("LAUNCHER UPDATE: Done"); if (!UpdateStatusResult()) { Log.Info("FIRST TIME RUN: Moved to Function"); /* Do First Time Run Checks */ FunctionStatus.FirstTimeRun(); } else { if (DiscordLauncherPresence.Running()) { DiscordLauncherPresence.Stop("Close"); } if (ServerProxy.Running()) { ServerProxy.Instance.Stop("Force Close"); } Application.Exit(); } }
public static FunctionLog CreateFunctionLog(ResultsAndCertificationDbContext _dbContext, string name, DateTime startDate, DateTime?endDate, FunctionStatus status, string message, bool addToDbContext = true) { var functionLog = new FunctionLog { Name = name, StartDate = startDate, EndDate = endDate, Status = status, Message = message, CreatedBy = "Test User" }; if (addToDbContext) { _dbContext.Add(functionLog); } return(functionLog); }
public static void PingAPIStatus() { Log.Checking("API: Checking Status"); Log.Checking("API Status: WorldUnited"); switch (UnitedSC = APIChecker.CheckStatus(URLs.Main + "/serverlist.json", 15)) { case APIStatus.Online: UnitedSL = RetrieveJSON(URLs.Main + "/serverlist.json", "SL"); if (UnitedSL) { UnitedCDNL = RetrieveJSON(URLs.Main + "/cdn_list.json", "CDNL"); } Log.Completed("API Status: WorldUnited"); break; default: Log.Completed("API Status: WorldUnited"); break; } if (!UnitedAPI()) { Log.Checking("API Status: DavidCarbon"); switch (CarbonSC = APIChecker.CheckStatus(URLs.Static + "/serverlist.json", 15)) { case APIStatus.Online: if (!UnitedSL) { CarbonSL = RetrieveJSON(URLs.Static + "/serverlist.json", "SL"); } else { CarbonSL = true; } if (!UnitedCDNL) { CarbonCDNL = RetrieveJSON(URLs.Static + "/cdn_list.json", "CDNL"); } else { CarbonCDNL = true; } Log.Completed("API Status: DavidCarbon"); break; default: Log.Completed("API Status: DavidCarbon"); break; } } else { CarbonSL = true; CarbonCDNL = true; } if (!CarbonAPI()) { Log.Checking("API Status: DavidCarbon [Second]"); switch (CarbonTwoSC = APIChecker.CheckStatus(URLs.Static_Alt + "/serverlist.json", 15)) { case APIStatus.Online: if (!CarbonSL) { CarbonTwoSL = RetrieveJSON(URLs.Static_Alt + "/serverlist.json", "SL"); } else { CarbonTwoSL = true; } if (!CarbonCDNL) { CarbonTwoCDNL = RetrieveJSON(URLs.Static_Alt + "/cdn_list.json", "CDNL"); } else { CarbonTwoCDNL = true; } Log.Completed("API Status: DavidCarbon [Second]"); break; default: Log.Completed("API Status: DavidCarbon [Second]"); break; } } else { CarbonTwoSL = true; CarbonTwoCDNL = true; } Log.Checking("API: Test #2"); /* Check If Launcher Failed to Connect to any APIs */ if (!CarbonAPITwo()) { DiscordLauncherPresence.Status("Start Up", "Launcher Encountered API Errors"); if (MessageBox.Show(null, Translations.Database("VisualsAPIChecker_TextBox_No_API"), Translations.Database("VisualsAPIChecker_TextBox_No_API_P2"), MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes) { FunctionStatus.LauncherForceClose = true; } else { Log.Warning("PRE-CHECK: User has Bypassed 'No Internet Connection' Check and will Continue"); MessageBox.Show(Translations.Database("VisualsAPIChecker_TextBox_No_API_P3"), Translations.Database("VisualsAPIChecker_TextBox_No_API_P4")); } } Log.Completed("API: Test #2 Done"); if (FunctionStatus.LauncherForceClose) { FunctionStatus.ErrorCloseLauncher("Closing From API Check Error", false); } else { FunctionStatus.IsVisualAPIsChecked = true; Log.Info("LIST CORE: Moved to Function"); /* (Start Process) Check ServerList Status */ ServerListUpdater.GetList(); } }