static void Main() { Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; SettingsUtil.LoadSettings(out Settings); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); bool doOpenFile = false; if (Settings.Filename == null || !File.Exists(Settings.Filename)) { using (var dlg = new OpenFileDialog { DefaultExt = "obj", Filter = "OBJ files (*.obj)|*.obj|All files (*.*)|*.*" }) { if (Settings.LastDir != null) { dlg.InitialDirectory = Settings.LastDir; } var result = dlg.ShowDialog(); if (result == DialogResult.Cancel) { return; } Settings.Filename = dlg.FileName; Settings.LastDir = Path.GetDirectoryName(dlg.FileName); doOpenFile = true; } } Application.Run(new Mainform(doOpenFile)); Settings.Save(onFailure: SettingsOnFailure.ShowRetryWithCancel); }
private void Application_Startup(object sender, StartupEventArgs e) { SettingsUtil.LoadSettings(out Settings); // We must build as a console app and hide the console on startup, because all components print colored text to the console. // It's possible to intercept the text without a console attached, but reading Console.ForegroundColor works only in "true" console apps ShowWindow(GetConsoleWindow(), 0); }
static int Main(string[] args) { if (args.Length == 2 && args[0] == "--post-build-check") { return(PostBuildChecker.RunPostBuildChecks(args[1], Assembly.GetExecutingAssembly())); } SettingsUtil.LoadSettings(out ZiimHelperProgram.Settings); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Mainform()); Settings.Save(onFailure: SettingsOnFailure.ShowRetryOnly); return(0); }
public Form_Main() { InitializeComponent(); this.Icon = NiceHashMiner.Properties.Resources.logo; InitLocalization(); ComputeDeviceManager.SystemSpecs.QueryAndLog(); // Log the computer's amount of Total RAM and Page File Size ManagementObjectCollection moc = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_OperatingSystem").Get(); foreach (ManagementObject mo in moc) { long TotalRam = long.Parse(mo["TotalVisibleMemorySize"].ToString()) / 1024; long PageFileSize = (long.Parse(mo["TotalVirtualMemorySize"].ToString()) / 1024) - TotalRam; Helpers.ConsolePrint("NICEHASH", "Total RAM: " + TotalRam + "MB"); Helpers.ConsolePrint("NICEHASH", "Page File Size: " + PageFileSize + "MB"); } R = new Random((int)DateTime.Now.Ticks); Text += " v" + Application.ProductVersion + _betaAlphaPostfixString; label_NotProfitable.Visible = false; InitMainConfigGUIData(); // for resizing InitFlowPanelStart(); if (groupBox1.Size.Height > 0 && this.Size.Height > 0) { EmtpyGroupPanelHeight = groupBox1.Size.Height; MainFormHeight = this.Size.Height - EmtpyGroupPanelHeight; } else { EmtpyGroupPanelHeight = 59; MainFormHeight = 330 - EmtpyGroupPanelHeight; } ClearRatesALL(); SettingsUtil.Init(); SettingsUtil.LoadSettings(); }
static void Main(string[] args) { //CodecTests.TestRandom(); PatternHashTable.SelfTest(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); int worker, dummy; ThreadPool.SetMinThreads(Environment.ProcessorCount, 10); ThreadPool.SetMaxThreads(Environment.ProcessorCount, 10); ThreadPool.GetAvailableThreads(out worker, out dummy); System.Diagnostics.Debug.Assert(worker == Environment.ProcessorCount); if (args.Length == 0) { SettingsUtil.LoadSettings(out Settings); MainForm form = new MainForm(); Application.Run(form); Settings.Save(); } else if (args[0] == "?") { DlgMessage.ShowInfo("Usage:\n i4c.exe - run interactive GUI.\n i4c.exe <algorithm> <filename> [<arg1> <arg2> ...] - compress/decompress single file.\n i4c.exe benchmark <algorithm> [<arg1> <arg2> ...] - benchmark on all files in cur dir.\n\nAvailable algorithms:\n\n" + Compressors.Keys.Select(compr => "* " + compr + "\n").JoinString()); } else if (args[0] == "benchmark") { if (args.Length == 1) { DlgMessage.ShowError("Must also specify the name of the algorithm to benchmark"); return; } command_Benchmark(args[1], args.Skip(2).Select(val => (RVariant)val).ToArray()); } else { if (args.Length < 2) { DlgMessage.ShowError("Must specify at least the algorithm name and the file name"); return; } command_Single(args[1], args[0], args.Skip(2).Select(val => (RVariant)val).ToArray()); } }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Ut.RunMain(() => { SettingsUtil.LoadSettings(out Settings); Tr = Lingo.LoadTranslationOrDefault <Translation>("AccountsWeb", ref Settings.Language); Interface = new WebInterface(); TrayForm = new TrayForm(); if (Settings.LastFileName != null) { OpenFile(Settings.LastFileName); } #if DEBUG var defaultTr = new Translation(); using (var tempConfigForm = new ConfigForm(new GncFileWrapper())) using (var g = new Lingo.TranslationFileGenerator(PathUtil.AppPathCombine("../../users/rs/GnuCash/AccountsWeb/Translation.g.cs"))) { g.TranslateControl(TrayForm, defaultTr.TrayForm); g.TranslateControl(TrayForm.TrayMenu, defaultTr.TrayMenu); g.TranslateControl(tempConfigForm, defaultTr.Config); } #endif Application.Run(); Settings.Save(); }, excp => { var message = "\n" + "An internal error has occurred in RunLogged: "; foreach (var ex in excp.SelectChain(ex => ex.InnerException)) { message += "\n" + ex.GetType() + ": " + ex.Message; message += "\n" + ex.StackTrace; } DlgMessage.ShowError(message); }); }
static int Main(string[] args) { if (args.Length == 2 && args[0] == "--generate-dto") { TypescriptDto.GenerateTypescriptFile(args[1]); return(0); } else if (args.Length != 0) { return(1); } SettingsUtil.LoadSettings(out Settings); Server = new Server(Settings); Server.Start(); while (true) { Thread.Sleep(TimeSpan.FromMinutes(1)); } }
static int Main(string[] args) { try { Console.OutputEncoding = Encoding.UTF8; } catch { } if (args.Length == 2 && args[0] == "--post-build-check") { return(Ut.RunPostBuildChecks(args[1], Assembly.GetExecutingAssembly())); } Classify.DefaultOptions.AddTypeOptions(typeof(Color), new ClassifyColorSubstitute()); SettingsUtil.LoadSettings(out Settings); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Mainform(Settings)); Settings.SaveLoud(); return(0); }
/// <summary> /// Loads Propeller settings from the appropriate location. Using this method ensures that settings are loaded in /// exactly the same way and from the same place as the Propeller engine would load them.</summary> /// <param name="settingsPath"> /// Path and filename of the settings to load.</param> /// <param name="log"> /// Information about how the settings were loaded is logged here. Must not be <c>null</c>.</param> /// <param name="firstRunEver"> /// Adjusts the log messages for improved human readability.</param> public static PropellerSettings LoadSettings(string settingsPath, LoggerBase log, bool firstRunEver) { settingsPath = settingsPath ?? SettingsUtil.GetAttribute <PropellerSettings>().GetFileName(); log.Info((firstRunEver ? "Loading settings file: " : "Reloading settings file: ") + settingsPath); PropellerSettings settings; var success = false; try { success = SettingsUtil.LoadSettings(out settings, settingsPath); if (success) { settings.SaveQuiet(settingsPath); return(settings); } } catch (Exception e) { settings = new PropellerSettings(); log.Error("Settings file could not be loaded: {0} ({1}). Using default settings.".Fmt(e.Message, e.GetType().FullName)); } if (!success) { if (!File.Exists(settingsPath)) { try { settings.Save(settingsPath); log.Info("Default settings saved to {0}.".Fmt(settingsPath)); } catch (Exception ex) { log.Warn("Attempt to save default settings to {0} failed: {1} ({2})".Fmt(settingsPath, ex.Message, ex.GetType().FullName)); } } } return(settings); }
static void Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Mutex m = null; try { m = new Mutex(true, "Global\\ExpSokMutex7FDC0158CF9E"); } catch { } SettingsUtil.LoadSettings(out Settings); #if DEBUG Lingo.AlsoSaveTranslationsTo = PathUtil.AppPathCombine(@"..\..\Src\Translations"); #endif Tr = Lingo.LoadTranslationOrDefault <Translation>("ExpSok", ref Settings.Language); Application.Run(new Mainform()); GC.KeepAlive(m); Settings.Save(); }
static int Main(string[] args) { // Configure Classify. This goes before the post-build check because it depends on it Classify.DefaultOptions = new ClassifyOptions() .AddTypeOptions(typeof(W.Color), new colorTypeOptions()) .AddTypeOptions(typeof(D.Color), new colorTypeOptions()) .AddTypeOptions(typeof(Filename), new filenameTypeOptions()) .AddTypeOptions(typeof(ObservableCollection <LayerBase>), new listLayerBaseOptions()) .AddTypeOptions(typeof(ObservableCollection <EffectBase>), new listEffectBaseOptions()); if (args.Length == 2 && args[0] == "--post-build-check") { return(RT.Util.Ut.RunPostBuildChecks(args[1], Assembly.GetExecutingAssembly())); } System.Windows.Forms.Application.EnableVisualStyles(); System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(false); #if DEBUG CompositePath.Tests(); #endif Thread.CurrentThread.Name = "Main"; #if !DEBUG AppDomain.CurrentDomain.UnhandledException += (_, ea) => { bool copy = DlgMessage.ShowError(App.Translation.Error.ExceptionGlobal, App.Translation.Error.ErrorToClipboard_Copy, App.Translation.Error.ErrorToClipboard_OK) == 0; if (copy) { if (Ut.ClipboardSet(Ut.ExceptionToDebugString(ea.ExceptionObject))) { DlgMessage.ShowInfo(App.Translation.Error.ErrorToClipboard_Copied); } } }; #else var dummy = App.Translation.Error.ExceptionGlobal; // to keep Lingo happy that the string is used var dummy2 = new StringBuilder(); // to keep the "using" clause used #endif // Find all the layer and effect types in the assembly (required before settings are loaded) App.LayerTypes = findTypes <LayerBase>("layer"); App.EffectTypes = findTypes <EffectBase>("effect"); // Load all settings SettingsUtil.LoadSettings(out App.Settings); UpdateSettingsIfNecessary(); // Guess the language if the OS language has changed (or this is the first run) var osLingo = Ut.GetOsLanguage(); if (App.Settings.OsLingo != osLingo) { App.Settings.OsLingo = App.Settings.Lingo = osLingo; } // Load translation App.Translation = Lingo.LoadTranslationOrDefault <Translation>("TankIconMaker", ref App.Settings.Lingo); // Run the UI var app = new App(); app.InitializeComponent(); app.Run(); // Save settings upon exit, even though they should be saved on every change anyway App.Settings.SaveQuiet(); return(0); }
private static int mainCore(string[] args) { Mutex mutex = null; if (_args.MutexName != null && !_args.ShadowCopy) { var sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null); var mutexsecurity = new MutexSecurity(); mutexsecurity.AddAccessRule(new MutexAccessRule(sid, MutexRights.FullControl, AccessControlType.Allow)); mutexsecurity.AddAccessRule(new MutexAccessRule(sid, MutexRights.ChangePermissions, AccessControlType.Deny)); mutexsecurity.AddAccessRule(new MutexAccessRule(sid, MutexRights.Delete, AccessControlType.Deny)); bool created; mutex = new Mutex(false, _args.MutexName, out created, mutexsecurity); if (!created) { throw new TellUserException("The mutex \"{0}\" is already acquired by another application.".Fmt(_args.MutexName), returnCode: ExitCode.MutexInUse, silent: true); } } string destPath = null; if (_args.ShadowCopy) { var source = Assembly.GetExecutingAssembly(); int i = 0; while (true) { i += Rnd.Next(65536); destPath = Path.Combine(Path.GetTempPath(), "RunLogged-" + i); if (Directory.Exists(destPath)) { continue; } try { Directory.CreateDirectory(destPath); _shadowLock = File.Open(Path.Combine(destPath, "lock"), FileMode.CreateNew, FileAccess.Write, FileShare.None); // Now verify that another copy of RunLogged hasn't copied itself over just before we created the directory, // which is theoretically possible var entries = Directory.GetFileSystemEntries(destPath); if (entries.Length != 1 || !entries[0].EndsWith("lock")) { continue; } break; } catch { } } var destAssembly = Path.Combine(destPath, Path.GetFileName(source.Location)); var newArgs = args.Where(arg => arg != "--shadowcopy").Select(arg => arg.Any(ch => "&()[]{}^=;!'+,`~ ".Contains(ch)) ? "\"" + arg + "\"" : arg).JoinString(" "); File.Copy(source.Location, destAssembly); foreach (var dep in source.GetReferencedAssemblies()) { var file = new[] { ".dll", ".exe" }.Select(ext => Path.Combine(Path.GetDirectoryName(source.Location), dep.Name + ext)).FirstOrDefault(fn => File.Exists(fn)); if (file == null) { continue; } File.Copy(file, Path.Combine(destPath, Path.GetFileName(file))); } Process.Start(new ProcessStartInfo { FileName = destAssembly, Arguments = "--wipe-after-shutdown \"" + destPath + "\" " + newArgs, UseShellExecute = true, // shell execute = true: a new console window will be created // shell execute = false: will attach to existing console window, but because the original process exits, this // fools cmd.exe into becoming interactive again while RunLogged is still logging to it. This looks very broken. // Hence the least evil seems to be to just create a new console window; it's unlikely that someone who wants // to use RunLogged interactively would specify --shadowcopy anyway. }); return(0); } SettingsUtil.LoadSettings(out _settings); _settings.SaveQuiet(); _originalCurrentDirectory = Directory.GetCurrentDirectory(); Console.CancelKeyPress += (_, __) => { processCtrlC(); }; WinAPI.SetConsoleCtrlHandler(_ => { processCtrlC(); return(true); }, true); try { try { Directory.CreateDirectory(Path.GetDirectoryName(_args.LogFilename)); } catch { } _log = File.Open(_args.LogFilename, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read); _log.Seek(0, SeekOrigin.End); _logStartOffset = _log.Position; var t = new Thread(threadLogFlusher); t.IsBackground = true; t.Start(); } catch (Exception e) { throw new TellUserException("Could not open the log file for writing. File \"{0}\".\n{1}".Fmt(_args.LogFilename, e.Message), returnCode: ExitCode.CannotOpenLogFile); } _runner = new CommandRunner(); _runner.SetCommand(_args.CommandToRun); _runner.WorkingDirectory = Directory.GetCurrentDirectory(); _runner.StdoutText += runner_StdoutText; _runner.StderrText += runner_StderrText; _readingThread = new Thread(readingThread); _readingThread.Start(); if (_args.TrayIcon != null) { _tooltipPrefix = Path.GetFileName(_args.CommandToRun[0].Split(' ').FirstOrDefault("RunLogged").SubstringSafe(0, 50)); _trayIcon = new NotifyIcon { Icon = new System.Drawing.Icon(_args.TrayIcon), ContextMenuStrip = new ContextMenuStrip(), Visible = true, Text = _tooltipPrefix, }; _miPause = (ToolStripMenuItem)_trayIcon.ContextMenuStrip.Items.Add("&Pause for...", null, pause); _trayIcon.ContextMenuStrip.Items.Add("E&xit", null, (_, __) => { _runner.Abort(); }); _trayIcon.ContextMenuStrip.Renderer = new NativeToolStripRenderer(); _trayIcon.ContextMenuStrip.Opening += updateResumeMenu; _runner.CommandResumed += () => { updateResumeMenu(); }; } Application.Run(); GC.KeepAlive(mutex); return(_readingThreadExitCode); }
static void Main() { Console.OutputEncoding = Encoding.UTF8; Console.WindowWidth = 200; Console.WindowHeight = 40; var curUser = Environment.UserName; curUser = curUser.Substring(0, 1).ToUpper() + curUser.Substring(1).ToLower(); Settings settings; SettingsUtil.LoadSettings(out settings); var highscore = settings.Highscores[curUser]; var recent = new AutoDictionary <string, Highscore>(_ => new Highscore()); int cur = 0; ConsoleColoredString lastAttemptOutcome = null; while (true) { Console.Clear(); Console.WriteLine("Current highscores, in milliseconds:"); WriteToConsole(settings.Highscores.Concat(recent).ToDictionary()); if (lastAttemptOutcome != null) { Console.WriteLine(); ConsoleUtil.WriteLine("Last attempt: " + lastAttemptOutcome); } Console.WriteLine(); Console.WriteLine("Type every letter A-Z exactly once, either alphabetically or in any order. Wait 1 second when done, or press space to restart."); Console.WriteLine(); var pressed = new Dictionary <char, DateTime>(); Console.Title = string.Join(" ", Enumerable.Range('A', 26).Select(x => (char)x).Except(pressed.Keys).OrderBy(x => x)); while (true) { var key = Console.ReadKey(true); Console.Write((key.KeyChar + " ").ToUpper()); if (key.KeyChar < 'a' || key.KeyChar > 'z') { break; } var chr = char.ToUpper(key.KeyChar); if (pressed.ContainsKey(chr)) { break; } pressed[chr] = DateTime.UtcNow; Console.Title = string.Join(" ", Enumerable.Range('A', 26).Select(x => (char)x).Except(pressed.Keys).OrderBy(x => x)); if (pressed.Count == 26) { break; } } Console.WriteLine(); Console.WriteLine('\x7'); if (pressed.Count == 26) { Console.WriteLine("Don't press anything now, to confirm you've typed just the 26 letters accurately and nothing else!"); var wait = DateTime.UtcNow; while (DateTime.UtcNow < wait + TimeSpan.FromSeconds(1) && !Console.KeyAvailable) { Thread.Sleep(10); } } if (pressed.Count == 26 && !Console.KeyAvailable) { UpdateHighscore(highscore, pressed); cur++; UpdateHighscore(recent[$"Recent: {cur:00}"], pressed); if (recent.ContainsKey($"Recent: {cur - 20:00}")) { recent.Remove($"Recent: {cur - 20:00}"); } lastAttemptOutcome = ""; char expected = 'A'; bool alphabetic = true; foreach (var kvp in pressed.OrderBy(kvp => kvp.Value)) { if (kvp.Key != expected) { alphabetic = false; } lastAttemptOutcome += $"{kvp.Key} ".Color(kvp.Key != expected ? ConsoleColor.Red : alphabetic ? ConsoleColor.Green : ConsoleColor.White); expected = (char)(kvp.Key + 1); } lastAttemptOutcome = (alphabetic ? "ALPHABETIC" : "any order") + " " + lastAttemptOutcome; settings.Save(); } else { lastAttemptOutcome = "OOPS!...".Color(ConsoleColor.Magenta); } Console.WriteLine(); Console.WriteLine(); } }