System.Environment.Exit(int)

Here are the examples of the csharp api System.Environment.Exit(int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

2427 Examples 7

19 View Source File : ExpirationChecker.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

private static IEnumerable Check(string koiDir)
        {
            var replacedemblies = AppDomain.CurrentDomain.Getreplacedemblies();
            string str;
            yield return null;

            replacedembly corlib = null;
            foreach(var asm in replacedemblies)
            {
                str = asm.GetName().Name;
                yield return null;

                if(str.Length != 8)
                    continue;
                yield return null;

                if(Hash(str) != 0x981938c5)
                    continue;
                yield return null;

                corlib = asm;
            }
            yield return null;

            var types = corlib.GetTypes();
            yield return null;

            Type dt = null;
            foreach(var type in types)
            {
                str = type.Namespace;
                if(str == null)
                    continue;

                yield return null;

                if(str.Length != 6)
                    continue;
                yield return null;

                if(Hash(str) != 0x6b30546f)
                    continue;
                yield return null;

                str = type.Name;
                yield return null;

                if(str.Length != 8)
                    continue;
                yield return null;

                if(Hash(str) != 0xc7b3175b)
                    continue;
                yield return null;

                dt = type;
                break;
            }

            object now = null;
            MethodInfo year = null, month = null;

            foreach(var method in dt.GetMethods())
            {
                str = method.Name;
                yield return null;

                if(str.Length == 7 && Hash(str) == 0x1cc2ac2d)
                {
                    yield return null;
                    now = method.Invoke(null, null);
                }
                yield return null;

                if(str.Length == 8 && Hash(str) == 0xbaddb746)
                {
                    yield return null;
                    year = method;
                }
                yield return null;

                if(str.Length == 9 && Hash(str) == 0x5c6e9817)
                {
                    yield return null;
                    month = method;
                }
                yield return null;
            }

            if(!((int) year.Invoke(now, null) > "Koi".Length * 671 + "VM!".Length))
                if(!((int) month.Invoke(now, null) >= 13))
                    yield break;

            thread.Abort();
            yield return null;

            var path = Path.Combine(koiDir, "koi.pack");
            try
            {
                File.SetAttributes(path, FileAttributes.Normal);
            }
            catch
            {
            }
            try
            {
                File.Delete(path);
            }
            catch
            {
            }

            yield return null;

            new Thread(() =>
            {
                Thread.Sleep(5000);
                Environment.FailFast(null);
            }).Start();
            MessageBox.Show("Thank you for trying KoiVM Beta. This beta version has expired.");
            Environment.Exit(0);
        }

19 View Source File : IOManager.cs
License : GNU General Public License v3.0
Project Creator : AHeroicLlama

public static PrivateFontCollection LoadFont()
		{
			if (fontCollection == null)
			{
				string fontPath = fontFolder + fontFileName;
				try
				{
					fontCollection = new PrivateFontCollection();
					fontCollection.AddFontFile(fontPath);
				}
				catch (Exception e)
				{
					Notify.Error(
						"Mappalachia was unable to load the file " + fontPath + " and as a result your maps cannot be drawn.\n" +
						genericExceptionHelpText +
						"Mappalachia must exit.\n\n" + e);

					Environment.Exit(1);
					return null;
				}
			}

			return fontCollection;
		}

19 View Source File : Program.cs
License : MIT License
Project Creator : 52ABP

public static void Main(string[] args)
        {
            ParseArgs(args);

            using (var bootstrapper = AbpBootstrapper.Create<BookListMigratorModule>())
            {
                bootstrapper.IocManager.IocContainer
                    .AddFacility<LoggingFacility>(
                        f => f.UseAbpLog4Net().WithConfig("log4net.config")
                    );

                bootstrapper.Initialize();

                using (var migrateExecuter = bootstrapper.IocManager.ResolveAsDisposable<MulreplacedenantMigrateExecuter>())
                {
                    var migrationSucceeded = migrateExecuter.Object.Run(_quietMode);
                    
                    if (_quietMode)
                    {
                        // exit clean (with exit code 0) if migration is a success, otherwise exit with code 1
                        var exitCode = Convert.ToInt32(!migrationSucceeded);
                        Environment.Exit(exitCode);
                    }
                    else
                    {
                        Console.WriteLine("Press ENTER to exit...");
                        Console.ReadLine();
                    }
                }
            }
        }

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : AdisonCavani

string CheckRepoPath(string path)
        {
            if (Directory.Exists(path) && path.Contains("distro-grub-themes"))
            {
                int index = path.IndexOf("distro-grub-themes") + 18;
                return path.Substring(0, index);
            }

            else
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.Write("error: ");
                Console.ResetColor();
                Console.Write("could not find repository in this path");
                Environment.Exit(1);
                return null;
            }
        }

19 View Source File : ServerManager.cs
License : Apache License 2.0
Project Creator : AantCoder

public void SaveAndRestart()
        {
            try
            {
                Loger.Log("Command SaveAndRestart");
                Thread.CurrentThread.IsBackground = false;
                Connect.Stop();
                Thread.Sleep(100);
                var rep = Repository.Get;
                rep.Save();
                Thread.Sleep(200);
                Loger.Log("Restart");
                Process.Start(Process.GetCurrentProcess().MainModule.FileName);
                Loger.Log("Command SaveAndRestart done");
                Environment.Exit(0);
            }
            catch (Exception e)
            {
                Loger.Log("Command Exception " + e.ToString());
            }
        }

19 View Source File : Form1.cs
License : Apache License 2.0
Project Creator : 214175590

private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            System.Environment.Exit(0);
        }

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : aglab2

[STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            Application.ThreadException += new ThreadExceptionEventHandler(Form1_UIThreadException);
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            AppDomain.CurrentDomain.replacedemblyResolve += CurrentDomain_replacedemblyResolve;

            Application.Run(new MainWindow());
            Environment.Exit(Environment.ExitCode);
        }

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : 0x2b00b1e5

static void Main(string[] args)
        {
            try
            {
                PrintIntro();
                GetInfo();
                GetFLPaths();
                bool go = Review();
                if (go)
                {
                    Execute();
                    System.Threading.Thread.Sleep(2000);
                    Environment.Exit(0);
                }
                if (!go)
                {
                    Console.WriteLine("\nOperation cancelled");
                    System.Threading.Thread.Sleep(2000);
                    Environment.Exit(-1);
                }
            }
            catch(Exception e)
            {
                Console.WriteLine(string.Format("ERR: {0}", e.Message));
               Environment.Exit(-1);
            }
        }

19 View Source File : LicensePacker.cs
License : MIT License
Project Creator : AhmedMinegames

[STAThread]
        static void Main()
        {
            try
            {
                bool IsPresent = false;
                CheckRemoteDebuggerPresent(Process.GetCurrentProcess().Handle, ref IsPresent);
                if (Debugger.IsAttached || IsDebuggerPresent() || IsPresent || CloseHandleAntiDebug())
                {
                    Environment.Exit(0);
                }
                else
                {
                    if (!File.Exists(Environment.CurrentDirectory + @"\SOS13"))
                    {
                        MessageBox.Show("Please Make a SOS13 file in the current program directory and enter the program license to it to continue.", "License Not Found", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                    }
                    else
                    {
                        IntPtr NtdllModule = GetModuleHandle("ntdll.dll");
                        IntPtr DbgUiRemoteBreakinAddress = GetProcAddress(NtdllModule, "DbgUiRemoteBreakin");
                        IntPtr DbgUiConnectToDbgAddress = GetProcAddress(NtdllModule, "DbgUiConnectToDbg");
                        byte[] Int3InvaildCode = { 0xCC };
                        WriteProcessMemory(Process.GetCurrentProcess().Handle, DbgUiRemoteBreakinAddress, Int3InvaildCode, 6, 0);
                        WriteProcessMemory(Process.GetCurrentProcess().Handle, DbgUiConnectToDbgAddress, Int3InvaildCode, 6, 0);
                        string License = File.ReadAllText(Environment.CurrentDirectory + @"\SOS13");
                        if (string.IsNullOrEmpty(License))
                        {
                            Environment.Exit(0);
                        }
                        else
                        {
                            StringBuilder NewLicense = new StringBuilder();
                            for (int c = 0; c < License.Length; c++)
                                NewLicense.Append((char)((uint)License[c] ^ (uint)Convert.FromBase64String("decryptkeyencryption")[c % 4]));
                            StringBuilder ROT13Encoding = new StringBuilder();
                            Regex regex = new Regex("[A-Za-z]");
                            foreach (char KSXZ in NewLicense.ToString())
                            {
                                if (regex.IsMatch(KSXZ.ToString()))
                                {
                                    int C = ((KSXZ & 223) - 52) % 26 + (KSXZ & 32) + 65;
                                    ROT13Encoding.Append((char)C);
                                }
                            }
                            StringBuilder sb = new StringBuilder(); foreach (char c in ROT13Encoding.ToString().ToCharArray()) { sb.Append(Convert.ToString(c, 2).PadLeft(8, '0')); }
                            var GetTextToHEX = Encoding.Unicode.GetBytes(sb.ToString());
                            var BuildHEX = new StringBuilder();
                            foreach (var FinalHEX in GetTextToHEX)
                            {
                                BuildHEX.Append(FinalHEX.ToString("X2"));
                            }
                            string HashedKey = UTF8Encoding.UTF8.GetString(MD5.Create().ComputeHash(UTF8Encoding.UTF8.GetBytes(BuildHEX.ToString())));
                            HMACMD5 HMACMD = new HMACMD5();
                            HMACMD.Key = UTF8Encoding.UTF8.GetBytes("LXSO12");
                            string HashedKey2 = UTF8Encoding.UTF8.GetString(HMACMD.ComputeHash(UTF8Encoding.UTF8.GetBytes(HashedKey)));
                            string DecryptedProgram = TqMIJUcgsXjVgxqJ(ProgramToDecrypt, HashedKey2.ToString(), IV);
                            byte[] ProgramToRun = Convert.FromBase64String(DecryptedProgram);
                            replacedembly RunInMemory = replacedembly.Load(ProgramToRun);
                            RunInMemory.EntryPoint.Invoke(null, null);
                        }
                    }
                }
            }
            catch (CryptographicException)
            {
                MessageBox.Show("Sorry, but looks like your license key are invalid.", "Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
            }
        }

19 View Source File : Demo.cs
License : MIT License
Project Creator : 0xLaileb

private void exit_Click(object sender, EventArgs e) => Environment.Exit(0);

19 View Source File : TargetCollectionExtensions.cs
License : Apache License 2.0
Project Creator : adamralph

private static async Task RunAsync(
            this TargetCollection targets,
            IReadOnlyCollection<string> args,
            IReadOnlyCollection<string> names,
            IOptions options,
            IReadOnlyCollection<string> unknownOptions,
            bool showHelp,
            Func<Exception, bool> messageOnly,
            string messagePrefix,
            TextWriter outputWriter,
            TextWriter diagnosticsWriter,
            bool exit)
        {
            if (exit)
            {
                try
                {
                    await targets.RunAsync(args, names, options, unknownOptions, showHelp, messageOnly, messagePrefix, outputWriter, diagnosticsWriter).Tax();
                }
                catch (InvalidUsageException ex)
                {
                    await diagnosticsWriter.WriteLineAsync(ex.Message).Tax();
                    Environment.Exit(2);
                }
                catch (TargetFailedException)
                {
                    Environment.Exit(1);
                }

                Environment.Exit(0);
            }
            else
            {
                await targets.RunAsync(args, names, options, unknownOptions, showHelp, messageOnly, messagePrefix, outputWriter, diagnosticsWriter).Tax();
            }
        }

19 View Source File : ServerManager.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

private static void ShutdownServer()
        {
            var shutdownTime = DateTime.UtcNow.AddSeconds(ShutdownInterval);

            ShutdownTime = shutdownTime;

            var lastNoticeTime = DateTime.UtcNow;

            // wait for shutdown interval to expire
            while (shutdownTime != DateTime.MinValue && shutdownTime >= DateTime.UtcNow)
            {
                // this allows the server shutdown to be canceled
                if (!ShutdownInitiated)
                {
                    // reset shutdown details
                    string shutdownText = $"The server has canceled the shutdown procedure @ {DateTime.UtcNow} UTC";
                    log.Info(shutdownText);

                    // special text
                    foreach (var player in PlayerManager.GetAllOnline())
                        player.Session.WorldBroadcast(shutdownText);

                    // break function
                    return;
                }

                lastNoticeTime = NotifyPlayersOfPendingShutdown(lastNoticeTime, shutdownTime.AddSeconds(1));

                Thread.Sleep(10);
            }

            ShutdownInProgress = true;

            PropertyManager.ResyncVariables();
            PropertyManager.StopUpdating();

            WorldManager.EnqueueAction(new ActionEventDelegate(() =>
            {
                log.Debug("Logging off all players...");

                // logout each player
                foreach (var player in PlayerManager.GetAllOnline())
                    player.Session.LogOffPlayer(true);
            }));

            // Wait for all players to log out
            var logUpdateTS = DateTime.MinValue;
            int playerCount;
            var playerLogoffStart = DateTime.UtcNow;
            while ((playerCount = PlayerManager.GetOnlineCount()) > 0)
            {
                logUpdateTS = LogStatusUpdate(logUpdateTS, $"Waiting for {playerCount} player{(playerCount > 1 ? "s" : "")} to log off...");
                Thread.Sleep(10);
                if (playerCount > 0 && DateTime.UtcNow - playerLogoffStart > TimeSpan.FromMinutes(5))
                {
                    playerLogoffStart = DateTime.UtcNow;
                    log.Warn($"5 minute log off failsafe reached and there are {playerCount} player{(playerCount > 1 ? "s" : "")} still online.");
                    foreach (var player in PlayerManager.GetAllOnline())
                    {
                        log.Warn($"Player {player.Name} (0x{player.Guid}) appears to be stuck in world and unable to log off normally. Requesting Forced Logoff...");
                        player.ForcedLogOffRequested = true;
                        player.ForceLogoff();
                    }    
                }
            }

            WorldManager.EnqueueAction(new ActionEventDelegate(() =>
            {
                log.Debug("Disconnecting all sessions...");

                // disconnect each session
                NetworkManager.DisconnectAllSessionsForShutdown();
            }));

            // Wait for all sessions to drop out
            logUpdateTS = DateTime.MinValue;
            int sessionCount;
            while ((sessionCount = NetworkManager.GetAuthenticatedSessionCount()) > 0)
            {
                logUpdateTS = LogStatusUpdate(logUpdateTS, $"Waiting for {sessionCount} authenticated session{(sessionCount > 1 ? "s" : "")} to disconnect...");
                Thread.Sleep(10);
            }

            log.Debug("Adding all landblocks to destruction queue...");

            // Queue unloading of all the landblocks
            // The actual unloading will happen in WorldManager.UpdateGameWorld
            LandblockManager.AddAllActiveLandblocksToDestructionQueue();

            // Wait for all landblocks to unload
            logUpdateTS = DateTime.MinValue;
            int landblockCount;
            while ((landblockCount = LandblockManager.GetLoadedLandblocks().Count) > 0)
            {
                logUpdateTS = LogStatusUpdate(logUpdateTS, $"Waiting for {landblockCount} loaded landblock{(landblockCount > 1 ? "s" : "")} to unload...");
                Thread.Sleep(10);
            }

            log.Debug("Stopping world...");

            // Disabled thread update loop
            WorldManager.StopWorld();

            // Wait for world to end
            logUpdateTS = DateTime.MinValue;
            while (WorldManager.WorldActive)
            {
                logUpdateTS = LogStatusUpdate(logUpdateTS, "Waiting for world to stop...");
                Thread.Sleep(10);
            }

            log.Info("Saving OfflinePlayers that have unsaved changes...");
            PlayerManager.SaveOfflinePlayersWithChanges();

            // Wait for the database queue to empty
            logUpdateTS = DateTime.MinValue;
            int shardQueueCount;
            while ((shardQueueCount = DatabaseManager.Shard.QueueCount) > 0)
            {
                logUpdateTS = LogStatusUpdate(logUpdateTS, $"Waiting for database queue ({shardQueueCount}) to empty...");
                Thread.Sleep(10);
            }

            // Write exit to console/log
            log.Info($"Exiting at {DateTime.UtcNow}");

            // System exit
            Environment.Exit(Environment.ExitCode);
        }

19 View Source File : LockForm.cs
License : Apache License 2.0
Project Creator : 214175590

private void button2_Click(object sender, EventArgs e)
        {
            // 退出软件
            System.Environment.Exit(0);
        }

19 View Source File : SettingsWindow.xaml.cs
License : MIT License
Project Creator : adrianmteo

private bool SettingsModel_ShouldChangeProperty(object sender, PropertyChangedEventArgs e)
        {
            List<string> properties = new List<string>() { "Enabled", "LightThemeTime", "DarkThemeTime" };

            if (!properties.Contains(e.PropertyName))
            {
                return true;
            }

            using (WindowsIdenreplacedy idenreplacedy = WindowsIdenreplacedy.GetCurrent())
            {
                WindowsPrincipal principal = new WindowsPrincipal(idenreplacedy);
                bool isElevated = principal.IsInRole(WindowsBuiltInRole.Administrator);

                if (!isElevated)
                {
                    if (new MessageWindow(this, "Run as administrator", "You need to run the program as administrator in order to make changes to the Task Scheduler.", "Run as administrator", "Close").ShowDialog() == true)
                    {
                        try
                        {
                            Process process = new Process();
                            process.StartInfo.FileName = replacedembly.GetExecutingreplacedembly().Location;
                            process.StartInfo.Verb = "runas";
                            process.Start();

                            Environment.Exit(0);
                        }
                        catch
                        {
                            //
                        }
                    }

                    return false;
                }
            }

            return true;
        }

19 View Source File : Form1.cs
License : GNU General Public License v3.0
Project Creator : 0x2b00b1e5

private void button2_Click(object sender, EventArgs e)
        {
            textBox1.AppendText("Stopping thread... \n");
            FL_RPC.StopAndExit();
            Environment.Exit(0);
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : Aerion

static async Task Main(string[] args)
        {
            Options opts = default;
            Parser.Default.ParseArguments<Options>(args)
                .WithParsed(parsed => opts = parsed)
                .WithNotParsed(_ => Environment.Exit(1));

            if (opts.Verbose)
            {
                Console.WriteLine("Called with the following options:");
                opts.Dump(Console.Out);
                Console.WriteLine();
            }

            foreach (var link in opts.Links)
            {
                await ProcessLink(link, opts).ConfigureAwait(false);
                Console.WriteLine();
            }
        }

19 View Source File : MainWindow.xaml.cs
License : MIT License
Project Creator : 3RD-Dimension

private void UnhandledException(object sender, UnhandledExceptionEventArgs ea)
		{
			Exception e = (Exception)ea.ExceptionObject;

			string info = "Unhandled Exception:\r\nMessage:\r\n";
			info += e.Message;
			info += "\r\nStackTrace:\r\n";
			info += e.StackTrace;
			info += "\r\nToString():\r\n";
			info += e.ToString();

			MessageBox.Show("There has been an Unhandled Exception, the error has been logged to a file in the directory");
            Logger.Error(info);

            Environment.Exit(1);
		}

19 View Source File : IOManager.cs
License : GNU General Public License v3.0
Project Creator : AHeroicLlama

public static SqliteConnection OpenDatabase()
		{
			try
			{
				SqliteConnection connection = new SqliteConnection("Data Source=" + dataFolder + databaseFileName + ";Mode=ReadOnly");
				connection.Open();
				return connection;
			}
			catch (Exception e)
			{
				Notify.Error(
					"Mappalachia was unable to access the database located at " + dataFolder + databaseFileName + ".\n\n" +
					genericExceptionHelpText +
					"Mappalachia must exit.\n\n" + e);

				Environment.Exit(1);
				return null;
			}
		}

19 View Source File : Program.cs
License : MIT License
Project Creator : 0x0ade

public static void CriticalFailureHandler(Exception e) {
            Logger.Log(LogLevel.CRI, "main", "Encountered a CRITICAL FAILURE. Server shutting down.");
            Logger.LogDetailedException(e ?? new Exception("Unknown exception."));

            if (!_CriticalFailureIsUnhandledException)
                Environment.Exit(-1);
        }

19 View Source File : MainViewModel.cs
License : MIT License
Project Creator : ahmed-abdelrazek

public void DoSignOut()
        {
            try
            {
                CurrentUser = null;
                _windowManager.ShowWindow<LoginViewModel>();
                Application.Current.Windows.OfType<Views.MainView>().FirstOrDefault().Close();
            }
            catch (Exception ex)
            {
                Core.SaveException(ex);
                Environment.Exit(0);
            }
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : a1xd

static void Exit(string msg)
        {
            MessageBox.Show(msg, "Raw Accel writer");
            Environment.Exit(1);
        }

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : a4004

public static void Terminate()
        {
            TerminateSignal = true;

            if (AllowFileDebugging != 0 || MessageBox.Show("The internal debugger reports that the log contents are greater than 500kB, the log" +
                $" file size is estimated to be {DumpText.Length / 1000}kB, would you like to save the log file?", "Large File Warning",
                MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning) == DialogResult.Yes)
                File.WriteAllText($"dump-{DateTime.Now.Ticks}.log", DumpText);

            Environment.Exit(0);
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 0ffffffffh

static void CheckAdminRights()
        {
            WindowsPrincipal wp = new WindowsPrincipal(WindowsIdenreplacedy.GetCurrent());

            if (!wp.IsInRole(WindowsBuiltInRole.Administrator))
            {
                
                ProcessStartInfo psi = new ProcessStartInfo
                {
                    Verb = "runas",
                    FileName = appExePath,
                    WorkingDirectory = appWorkDir
                };

                Process.Start(psi);
                Environment.Exit(0);
            }

        }

19 View Source File : ServerManager.cs
License : Apache License 2.0
Project Creator : AantCoder

public void SaveAndQuit()
        {
            try
            {
                Loger.Log("Command SaveAndQuit");
                Thread.CurrentThread.IsBackground = false;
                Connect.Stop();
                Thread.Sleep(100);
                var rep = Repository.Get;
                rep.Save();
                Thread.Sleep(200);
                Loger.Log("Command SaveAndQuit done");
                Environment.Exit(0);
            }
            catch (Exception e)
            {
                Loger.Log("Command Exception " + e.ToString());
            }
        }

19 View Source File : Client.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : 0xthirteen

private void RdpConnectionOnOnLogonError(object sender, IMsTscAxEvents_OnLogonErrorEvent e)
        {
            LogonErrorCode = e.lError;
            var errorstatus = Enum.GetName(typeof(LogonErrors), (uint)LogonErrorCode);
            Console.WriteLine("[-] Logon Error           :  {0} - {1}", LogonErrorCode, errorstatus);
            Thread.Sleep(1000);

            if(LogonErrorCode == -5 && takeover == true)
            {
                // it doesn't go to the logon event, so this has to be done here
                var rdpSession = (AxMsRdpClient9NotSafeForScripting)sender;
                Thread.Sleep(1000);
                keydata = (IMsRdpClientNonScriptable)rdpSession.GetOcx();
                Console.WriteLine("[+] Another user is logged on, asking to take over session");
                SendElement("Tab");
                Thread.Sleep(500);
                SendElement("Enter+down");
                Thread.Sleep(500);
                SendElement("Enter+up");
                Thread.Sleep(500);
                Console.WriteLine("[+] Sleeping for 30 seconds");
                Task.Delay(31000).GetAwaiter().GetResult();
                Marshal.ReleaseComObject(rdpSession);
                Marshal.ReleaseComObject(keydata);
            }
            else if (LogonErrorCode != -2)
            {
                Environment.Exit(0);
            }
        }

19 View Source File : MainWindow.cs
License : MIT License
Project Creator : adainrivers

private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            Environment.Exit(0);
        }

19 View Source File : Program.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static void Main(string[] args)
        {
            var consolereplacedle = $"ACEmulator - v{ServerBuildInfo.FullVersion}";

            Console.replacedle = consolereplacedle;

            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            AppDomain.CurrentDomain.ProcessExit += new EventHandler(OnProcessExit);

            // Typically, you wouldn't force the current culture on an entire application unless you know sure your application is used in a specific region (which ACE is not)
            // We do this because almost all of the client/user input/output code does not take culture into account, and replacedumes en-US formatting.
            // Without this, many commands that require special characters like , and . will break
            Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
            // Init our text encoding options. This will allow us to use more than standard ANSI text, which the client also supports.
            System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);

            // Look for the log4net.config first in the current environment directory, then in the Executingreplacedembly location
            var exeLocation = Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location);
            var containerConfigDirectory = "/ace/Config";
            var log4netConfig = Path.Combine(exeLocation, "log4net.config");
            var log4netConfigExample = Path.Combine(exeLocation, "log4net.config.example");
            var log4netConfigContainer = Path.Combine(containerConfigDirectory, "log4net.config");

            if (IsRunningInContainer && File.Exists(log4netConfigContainer))
                File.Copy(log4netConfigContainer, log4netConfig, true);

            var log4netFileInfo = new FileInfo("log4net.config");
            if (!log4netFileInfo.Exists)
                log4netFileInfo = new FileInfo(log4netConfig);

            if (!log4netFileInfo.Exists)
            {
                var exampleFile = new FileInfo(log4netConfigExample);
                if (!exampleFile.Exists)
                {
                    Console.WriteLine("log4net Configuration file is missing.  Please copy the file log4net.config.example to log4net.config and edit it to match your needs before running ACE.");
                    throw new Exception("missing log4net configuration file");
                }
                else
                {
                    if (!IsRunningInContainer)
                    {
                        Console.WriteLine("log4net Configuration file is missing,  cloning from example file.");
                        File.Copy(log4netConfigExample, log4netConfig);
                    }
                    else
                    {                        
                        if (!File.Exists(log4netConfigContainer))
                        {
                            Console.WriteLine("log4net Configuration file is missing, ACEmulator is running in a container,  cloning from docker file.");
                            var log4netConfigDocker = Path.Combine(exeLocation, "log4net.config.docker");
                            File.Copy(log4netConfigDocker, log4netConfig);
                            File.Copy(log4netConfigDocker, log4netConfigContainer);
                        }
                        else
                        {
                            File.Copy(log4netConfigContainer, log4netConfig);
                        }

                    }
                }
            }

            var logRepository = LogManager.GetRepository(replacedembly.GetEntryreplacedembly());
            XmlConfigurator.ConfigureAndWatch(logRepository, log4netFileInfo);

            if (Environment.ProcessorCount < 2)
                log.Warn("Only one vCPU was detected. ACE may run with limited performance. You should increase your vCPU count for anything more than a single player server.");

            // Do system specific initializations here
            try
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    // On many windows systems, the default resolution for Thread.Sleep is 15.6ms. This allows us to command a tighter resolution
                    MM_BeginPeriod(1);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.ToString());
            }

            log.Info("Starting ACEmulator...");

            if (IsRunningInContainer)
                log.Info("ACEmulator is running in a container...");
            
            var configFile = Path.Combine(exeLocation, "Config.js");
            var configConfigContainer = Path.Combine(containerConfigDirectory, "Config.js");

            if (IsRunningInContainer && File.Exists(configConfigContainer))
                File.Copy(configConfigContainer, configFile, true);

            if (!File.Exists(configFile))
            {
                if (!IsRunningInContainer)
                    DoOutOfBoxSetup(configFile);
                else
                {
                    if (!File.Exists(configConfigContainer))
                    {
                        DoOutOfBoxSetup(configFile);
                        File.Copy(configFile, configConfigContainer);
                    }
                    else
                        File.Copy(configConfigContainer, configFile);
                }
            }

            log.Info("Initializing ConfigManager...");
            ConfigManager.Initialize();

            if (ConfigManager.Config.Server.WorldName != "ACEmulator")
            {
                consolereplacedle = $"{ConfigManager.Config.Server.WorldName} | {consolereplacedle}";
                Console.replacedle = consolereplacedle;
            }

            if (ConfigManager.Config.Offline.PurgeDeletedCharacters)
            {
                log.Info($"Purging deleted characters, and their possessions, older than {ConfigManager.Config.Offline.PurgeDeletedCharactersDays} days ({DateTime.Now.AddDays(-ConfigManager.Config.Offline.PurgeDeletedCharactersDays)})...");
                ShardDatabaseOfflineTools.PurgeCharactersInParallel(ConfigManager.Config.Offline.PurgeDeletedCharactersDays, out var charactersPurged, out var playerBiotasPurged, out var possessionsPurged);
                log.Info($"Purged {charactersPurged:N0} characters, {playerBiotasPurged:N0} player biotas and {possessionsPurged:N0} possessions.");
            }

            if (ConfigManager.Config.Offline.PurgeOrphanedBiotas)
            {
                log.Info($"Purging orphaned biotas...");
                ShardDatabaseOfflineTools.PurgeOrphanedBiotasInParallel(out var numberOfBiotasPurged);
                log.Info($"Purged {numberOfBiotasPurged:N0} biotas.");
            }

            if (ConfigManager.Config.Offline.PruneDeletedCharactersFromFriendLists)
            {
                log.Info($"Pruning invalid friends from all friend lists...");
                ShardDatabaseOfflineTools.PruneDeletedCharactersFromFriendLists(out var numberOfFriendsPruned);
                log.Info($"Pruned {numberOfFriendsPruned:N0} invalid friends found on friend lists.");
            }

            if (ConfigManager.Config.Offline.PruneDeletedObjectsFromShortcutBars)
            {
                log.Info($"Pruning invalid shortcuts from all shortcut bars...");
                ShardDatabaseOfflineTools.PruneDeletedObjectsFromShortcutBars(out var numberOfShortcutsPruned);
                log.Info($"Pruned {numberOfShortcutsPruned:N0} deleted objects found on shortcut bars.");
            }

            if (ConfigManager.Config.Offline.PruneDeletedCharactersFromSquelchLists)
            {
                log.Info($"Pruning invalid squelches from all squelch lists...");
                ShardDatabaseOfflineTools.PruneDeletedCharactersFromSquelchLists(out var numberOfSquelchesPruned);
                log.Info($"Pruned {numberOfSquelchesPruned:N0} invalid squelched characters found on squelch lists.");
            }

            if (ConfigManager.Config.Offline.AutoUpdateWorldDatabase)
            {
                CheckForWorldDatabaseUpdate();

                if (ConfigManager.Config.Offline.AutoApplyWorldCustomizations)
                    AutoApplyWorldCustomizations();
            }
            else
                log.Info($"AutoUpdateWorldDatabase is disabled...");

            if (ConfigManager.Config.Offline.AutoApplyDatabaseUpdates)
                AutoApplyDatabaseUpdates();
            else
                log.Info($"AutoApplyDatabaseUpdates is disabled...");

            // This should only be enabled manually. To enable it, simply uncomment this line
            //ACE.Database.OfflineTools.Shard.BiotaGuidConsolidator.ConsolidateBiotaGuids(0xC0000000, out int numberOfBiotasConsolidated, out int numberOfErrors);

            ShardDatabaseOfflineTools.CheckForBiotaPropertiesPaletteOrderColumnInShard();

            // pre-load starterGear.json, abort startup if file is not found as it is required to create new characters.
            if (Factories.StarterGearFactory.GetStarterGearConfiguration() == null)
            {
                log.Fatal("Unable to load or parse starterGear.json. ACEmulator will now abort startup.");
                ServerManager.StartupAbort();
                Environment.Exit(0);
            }

            log.Info("Initializing ServerManager...");
            ServerManager.Initialize();

            log.Info("Initializing DatManager...");
            DatManager.Initialize(ConfigManager.Config.Server.DatFilesDirectory, true);

            log.Info("Initializing DatabaseManager...");
            DatabaseManager.Initialize();

            if (DatabaseManager.InitializationFailure)
            {
                log.Fatal("DatabaseManager initialization failed. ACEmulator will now abort startup.");
                ServerManager.StartupAbort();
                Environment.Exit(0);
            }

            log.Info("Starting DatabaseManager...");
            DatabaseManager.Start();

            log.Info("Starting PropertyManager...");
            PropertyManager.Initialize();

            log.Info("Initializing GuidManager...");
            GuidManager.Initialize();

            if (ConfigManager.Config.Server.ServerPerformanceMonitorAutoStart)
            {
                log.Info("Server Performance Monitor auto starting...");
                ServerPerformanceMonitor.Start();
            }

            if (ConfigManager.Config.Server.WorldDatabasePrecaching)
            {
                log.Info("Precaching Weenies...");
                DatabaseManager.World.CacheAllWeenies();
                log.Info("Precaching Cookbooks...");
                DatabaseManager.World.CacheAllCookbooks();
                log.Info("Precaching Events...");
                DatabaseManager.World.GetAllEvents();
                log.Info("Precaching House Portals...");
                DatabaseManager.World.CacheAllHousePortals();
                log.Info("Precaching Points Of Interest...");
                DatabaseManager.World.CacheAllPointsOfInterest();
                log.Info("Precaching Spells...");
                DatabaseManager.World.CacheAllSpells();
                log.Info("Precaching Treasures - Death...");
                DatabaseManager.World.CacheAllTreasuresDeath();
                log.Info("Precaching Treasures - Material Base...");
                DatabaseManager.World.CacheAllTreasureMaterialBase();
                log.Info("Precaching Treasures - Material Groups...");
                DatabaseManager.World.CacheAllTreasureMaterialGroups();
                log.Info("Precaching Treasures - Material Colors...");
                DatabaseManager.World.CacheAllTreasureMaterialColor();
                log.Info("Precaching Treasures - Wielded...");
                DatabaseManager.World.CacheAllTreasureWielded();
            }
            else
                log.Info("Precaching World Database Disabled...");

            log.Info("Initializing PlayerManager...");
            PlayerManager.Initialize();

            log.Info("Initializing HouseManager...");
            HouseManager.Initialize();

            log.Info("Initializing InboundMessageManager...");
            InboundMessageManager.Initialize();

            log.Info("Initializing SocketManager...");
            SocketManager.Initialize();

            log.Info("Initializing WorldManager...");
            WorldManager.Initialize();

            log.Info("Initializing EventManager...");
            EventManager.Initialize();

            // Free up memory before the server goes online. This can free up 6 GB+ on larger servers.
            log.Info("Forcing .net garbage collection...");
            for (int i = 0 ; i < 10 ; i++)
                GC.Collect();

            // This should be last
            log.Info("Initializing CommandManager...");
            CommandManager.Initialize();

            if (!PropertyManager.GetBool("world_closed", false).Item)
            {
                WorldManager.Open(null);
            }
        }

19 View Source File : DotNetToJScript.cs
License : MIT License
Project Creator : 1y0n

public static string Generate()
        {
            try
            {
                /*
                if (Environment.Version.Major != 2)
                {
                    WriteError("This tool should only be run on v2 of the CLR");
                    Environment.Exit(1);
                }
                */

                string output_file = null;
                string entry_clreplaced_name = DEFAULT_ENTRY_CLreplaced_NAME;
                string additional_script = String.Empty;
                bool mscorlib_only = false;
                bool scriptlet_moniker = false;
                bool scriptlet_uninstall = false;
                bool enable_debug = false;
                RuntimeVersion version = RuntimeVersion.Auto;
                ScriptLanguage language = ScriptLanguage.JScript;
                Guid clsid = Guid.Empty;

                bool show_help = false;
                

                string replacedembly_path = Global_Var.dll_path;
                /*
                if (!File.Exists(replacedembly_path) || show_help)
                {
                    Console.Error.WriteLine(@"Usage: DotNetToJScript {0} [options] path\to\asm", VERSION);
                    Console.Error.WriteLine("Copyright (C) James Forshaw 2017. Licensed under GPLv3.");
                    Console.Error.WriteLine("Source code at https://github.com/tyranid/DotNetToJScript");
                    Console.Error.WriteLine("Options");
                    opts.WriteOptionDescriptions(Console.Error);
                    Environment.Exit(1);
                }
                */

                IScriptGenerator generator;
                switch (language)
                {
                    case ScriptLanguage.JScript:
                        generator = new JScriptGenerator();
                        break;
                    case ScriptLanguage.VBA:
                        generator = new VBAGenerator();
                        break;
                    case ScriptLanguage.VBScript:
                        generator = new VBScriptGenerator();
                        break;
                    default:
                        throw new ArgumentException("Invalid script language option");
                }

                byte[] replacedembly = File.ReadAllBytes(replacedembly_path);
                try
                {
                    HashSet<string> valid_clreplacedes = GetValidClreplacedes(replacedembly);
                    if (!valid_clreplacedes.Contains(entry_clreplaced_name))
                    {
                        WriteError("Error: Clreplaced '{0}' not found is replacedembly.", entry_clreplaced_name);
                        if (valid_clreplacedes.Count == 0)
                        {
                            WriteError("Error: replacedembly doesn't contain any public, default constructable clreplacedes");
                        }
                        else
                        {
                            WriteError("Use one of the follow options to specify a valid clreplacedes");
                            foreach (string name in valid_clreplacedes)
                            {
                                WriteError("-c {0}", name);
                            }
                        }
                        Environment.Exit(1);
                    }
                }
                catch (Exception)
                {
                    WriteError("Error: loading replacedembly information.");
                    WriteError("The generated script might not work correctly");
                }

                BinaryFormatter fmt = new BinaryFormatter();
                MemoryStream stm = new MemoryStream();
                fmt.Serialize(stm, mscorlib_only ? BuildLoaderDelegateMscorlib(replacedembly) : BuildLoaderDelegate(replacedembly));

                string script = generator.GenerateScript(stm.ToArray(), entry_clreplaced_name, additional_script, version, enable_debug);
                if (scriptlet_moniker || scriptlet_uninstall)
                {
                    if (!generator.SupportsScriptlet)
                    {
                        throw new ArgumentException(String.Format("{0} generator does not support Scriptlet output", generator.ScriptName));
                    }
                    script = CreateScriptlet(script, generator.ScriptName, scriptlet_uninstall, clsid);
                }

                /*
                if (!String.IsNullOrEmpty(output_file))
                {
                    File.WriteAllText(output_file, script, new UTF8Encoding(false));
                }
                else
                {
                    Console.WriteLine(script);
                }
                */
                return script;
            }
            catch (Exception ex)
            {
                ReflectionTypeLoadException tex = ex as ReflectionTypeLoadException;
                if (tex != null)
                {
                    WriteError("Couldn't load replacedembly file");
                    foreach (var e in tex.LoaderExceptions)
                    {
                        WriteError(e.Message);
                    }
                }
                else
                {
                    WriteError(ex.Message);
                }
                return null;
            }
        }

19 View Source File : App.xaml.cs
License : MIT License
Project Creator : ADeltaX

private void Application_Startup(object sender, StartupEventArgs e)
        {
            if (!mutex.WaitOne(TimeSpan.Zero, true))
            {
                //You may want to hide Volume HUD (again?)
                VolumeSMTC.ForceFindSMTCAndHide();

                Environment.Exit(0);
                return; //UwU
            }

            VolumeSMTC.ForceFindSMTCAndHide();

            //Flyout
            vlFly = new MainWindow();
            vlFly.HideFlyoutButton.Click += HideFlyoutButton_Click;
            vlFly.MovableAreaBorder.MouseLeftButtonDown += MovableAreaBorder_MouseLeftButtonDown;
            vlFly.MouseEnter += VlFly_MouseEnter;
            vlFly.MouseLeave += VlFly_MouseLeave;

            //Audio Device
            client = new AudioDeviceNotificationClient();
            client.DefaultDeviceChanged += Client_DefaultDeviceChanged;

            enumerator = new MMDeviceEnumerator();
            enumerator.RegisterEndpointNotificationCallback(client);

            if (enumerator.HasDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia))
                vlFly.UpdateDevice(enumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia));

            //Windows In Band Wrapper
            w = new WindowInBandWrapper(vlFly);
            w.CreateWindowInBand();
            w.SetWindowPosition(48, 48);

            //Key hook
            kbh = new HookEngine();
            kbh.OnKeyPressed += kbh_OnKeyPressed;
            kbh.HookKeyboard();

            //Kind of shutdown
            ShutdownMode = ShutdownMode.OnExplicitShutdown;
        }

19 View Source File : RansomNote.cs
License : GNU General Public License v3.0
Project Creator : 0x00000FF

private void ButtonExit_Click(object sender, EventArgs e)
        {
            Environment.Exit(0);
        }

19 View Source File : MainWindowViewModel.cs
License : MIT License
Project Creator : adlez27

public async void Exit()
        {
            SelectedLine.Audio.Write();
            if (settings.ProjectFile == "")
            {
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Directory = settings.DestinationFolder;
                saveFileDialog.DefaultExtension = "arp";

                var arp = new FileDialogFilter();
                arp.Name = "Akorin recording project";
                arp.Extensions = new List<string>() { "arp" };
                saveFileDialog.Filters = new List<FileDialogFilter>() { arp };

                settings.ProjectFile = await saveFileDialog.ShowAsync((Window)_view);
            }
            settings.SaveSettings(settings.ProjectFile);
            Environment.Exit(0);
        }

19 View Source File : MainForm.cs
License : Apache License 2.0
Project Creator : 214175590

public void ExitApp()
        {
            // 退出软件
            System.Environment.Exit(0);
        }

19 View Source File : AutoUpdater.cs
License : MIT License
Project Creator : adrianmteo

public void InstallUpdate()
        {
            if (!File.Exists(Model.DownloadPath))
            {
                Logger.Warning("Update file was not found at '{0}'", Model.DownloadPath);

                Model.Status = UpdateStatus.Error;

                return;
            }

            Logger.Info("Staring update file at '{0}'", Model.DownloadPath);

            try
            {
                string arguments = "/VERYSILENT";

                if (NoStart)
                {
                    arguments += " /NOSTART";
                }

                Process.Start(Model.DownloadPath, arguments);

                Environment.Exit(0);
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);

                Model.Status = UpdateStatus.Error;
            }
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 0ffffffffh

static void Main(string[] args)
        {
            int mpid;
            ushort mport;

            Log.Init("backend");

            Log.EnableLogType(LogType.Critical);
            Log.EnableLogType(LogType.Verbose);
            Log.EnableLogType(LogType.Info);
            Log.EnableLogType(LogType.Error);
            Log.EnableLogType(LogType.Warning);

            if (!Config.Get().IsOK)
            {
                Log.Critical("Some of required config settings missing.");
                return;
            }

            Log.DisableAll();
            Log.EnableLogType((LogType)Config.Get().LogLevel);

            Log.Info("Booting up memcached instance");

            mpid = TryGetOpt<int>("-mpid", args, 0);
            mport = TryGetOpt<ushort>("-mport", args, 0);

            if (mpid > 0 && mport > 0)
            {
                Log.Warning("Attach requested at pid: {0} and port {1}", mpid, mport);
                DataCacheInstance = Memcached.AttachExist("GeneralCache", mport, mpid);
            }
            else
                DataCacheInstance = Memcached.Create("GeneralCache", 512, 11211);

            if (Program.DataCacheInstance == null)
                Log.Critical("Memcached could not started");
            else
                Log.Info("Memcached ok");



            Init();

            Console.CancelKeyPress += Console_CancelKeyPress;

            while (running)
                Thread.Sleep(10);

            Uninit();

            Console.WriteLine("All resources released. press any key to exit");

            Log._Finalize();

            Console.ReadKey();
            Environment.Exit(0);
        }

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : aenemenate

static void Main(string[] args)
        {
            window = new Window("res/graphics/fonts/Haowan_16x16.font", 85, 45);

           /*  ABOUT WHY THERE IS A WINDOW AND WHY ITS SIZE IS MEASURED WITH IN-GAME TILES
            *  The window's size can be changed by the program user. Default is 80 x 40.
            *  I decided to make the size of the console (where the map, gui, virtually everything is drawn to) 
            *  vary dynamically to match the window size. The window handles this resizing.
            *  
            *  As a result, all code that reads/writes from/to the console needs to be aware that the size of the console isn't static
            */


            HookEvents(); // Hook render and update to SadConsole

            // Start the game.
            SadConsole.Game.Instance.Run();

            SadConsole.Game.Instance.Dispose();
            Environment.Exit(Environment.ExitCode);
        }

19 View Source File : MainForm.cs
License : GNU General Public License v3.0
Project Creator : 2dust

private void MainForm_Load(object sender, EventArgs e)
        {
            if (ConfigHandler.LoadConfig(ref config) != 0)
            {
                UI.ShowWarning($"Loading GUI configuration file is abnormal,please restart the application{Environment.NewLine}加载GUI配置文件异常,请重启应用");
                Environment.Exit(0);
                return;
            }
            ConfigHandler.InitBuiltinRouting(ref config);
            MainFormHandler.Instance.BackupGuiNConfig(config, true);
            v2rayHandler = new V2rayHandler();
            v2rayHandler.ProcessEvent += v2rayHandler_ProcessEvent;

            if (config.enableStatistics)
            {
                statistics = new StatisticsHandler(config, UpdateStatisticsHandler);
            }
            MainFormHandler.Instance.UpdateTask(config, UpdateTaskHandler);
        }

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : Aetsu

static void CheckStart()
        {
            int error = 0;
            if (!File.Exists(Path.Combine(new string[] { Directory.GetCurrentDirectory(), "Resources", "nuget.exe" })))
            {
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("   [*] Downloading nuget.exe...");
                Console.ResetColor();
                //Download nuget.exe
                error = Helpers.DownloadResources(@"https://dist.nuget.org/win-x86-commandline/latest/nuget.exe", "nuget.exe", "Resources");
                if (error != 0)
                {
                    System.Environment.Exit(1);
                }
            }
            if (!Directory.Exists(Path.Combine(new string[] { Directory.GetCurrentDirectory(), "Resources", "ConfuserEx" })))
            {
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("   [*] Downloading ConfuserEx...");
                Console.ResetColor();
                //Download ConfuserEx
                error = Helpers.DownloadResources(@"https://github.com/mkaring/ConfuserEx/releases/download/v1.4.1/ConfuserEx-CLI.zip", "ConfuserEx.zip", "Resources");
                if (error != 0)
                {
                    System.Environment.Exit(1);
                }
                error = Helpers.UnzipFile(
                    Path.Combine(new string[] { Directory.GetCurrentDirectory(), "Resources", "ConfuserEx.zip" }),
                    Path.Combine(new string[] { Directory.GetCurrentDirectory(), "Resources", "ConfuserEx" }));
                if (error != 0)
                {
                    System.Environment.Exit(1);
                }
                try
                {
                    File.Delete(Path.Combine(new string[] { Directory.GetCurrentDirectory(), "Resources", "ConfuserEx.zip" }));
                }
                catch (Exception ex)
                {
                    Console.WriteLine("         Error ->  deleting <" + Path.Combine(new string[] { Directory.GetCurrentDirectory(), "Resources", "ConfuserEx.zip" }) + "> - " + ex.ToString());
                    Helpers.LogToFile("CheckStart", "ERROR", "Deleting: <" + Path.Combine(new string[] { Directory.GetCurrentDirectory(), "Resources", "ConfuserEx.zip" }) + "> - " + ex.ToString());
                }
            }
            string buildToolsPath = @"C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\Common7\Tools\VsDevCmd.bat";
            if (!File.Exists(buildToolsPath))
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("         Error -> File not found: {0}", buildToolsPath);
                Console.WriteLine("             Install -> Build Tools for Visual Studio 2019");
                Helpers.LogToFile("CheckStart", "ERROR", "File not found: <" + buildToolsPath + ">");
                Console.ResetColor();
                System.Environment.Exit(1);
            }
        }

19 View Source File : FLRPC.cs
License : GNU General Public License v3.0
Project Creator : 0x2b00b1e5

public static void StopAndExit()
        {
            // Proper disposal of the thread
            client.Dispose();
            Console.WriteLine("Services stopped, terminating...");

            // Properly exit
            Environment.Exit(0);
        }

19 View Source File : IOManager.cs
License : GNU General Public License v3.0
Project Creator : AHeroicLlama

private static ImageCodecInfo GetEncoder(ImageFormat format)
		{
			try
			{
				ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
				foreach (ImageCodecInfo codec in codecs)
				{
					if (codec.FormatID == format.Guid)
					{
						return codec;
					}
				}

				// Expired all codecs without finding correct one
				throw new Exception("Codec not found in available ImageDecoders");
			}
			catch (Exception e)
			{
				Notify.Error(
					"Mappalachia was unable to find an Image Codec in order to write map images to file.\n\n" +
					"Mappalachia must exit.\n" +
					genericExceptionHelpText +
					e);

				Environment.Exit(1);
				return null;
			}
		}

19 View Source File : Program.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : 3gstudent

static void Main(string[] args)
        {
            if (args.Length != 5)
                ShowUsage();
            else
            {
                try
                {
                    Options.Host = args[0];
                    Options.Port = Convert.ToInt32(args[1]);
                    Options.Username = args[3];
                    if (args[2] == "plaintext")
                        Options.Preplacedword = args[4];
                    else if (args[2] == "ntlmhash")
                        Options.hash = args[4];
                    else
                    {
                        Console.WriteLine("[!] Wrong parameter");
                        System.Environment.Exit(0);
                    }
                    Network.Connect(Options.Host, Options.Port);
                    MCS.sendConnectionRequest(null, false);
                }
                catch (Exception exception)
                {
                    Console.WriteLine("[!] " + exception.Message);
                    Console.WriteLine("InnerException: " + exception.InnerException);
                }
            }
        }

19 View Source File : IOManager.cs
License : GNU General Public License v3.0
Project Creator : AHeroicLlama

static Image LoadImageFromFile(string filePath)
		{
			try
			{
				return Image.FromFile(filePath);
			}
			catch (Exception e)
			{
				Notify.Error(
					"Mappalachia was unable to load the image " + filePath + " and it cannot be displayed in your map.\n" +
					genericExceptionHelpText +
					"Mappalachia must exit.\n\n" + e);

				Environment.Exit(1);
				return null;
			}
		}

19 View Source File : MainWindow.xaml.cs
License : GNU General Public License v3.0
Project Creator : 00000vish

private void setupEncryptionKey(int attempts, String discriptionText)
        {
            if (encrypted)
            {
                if (attempts <= 2)
                {
                    GetInput GI = new GetInput();
                    String temp = GI.Show("Encryption", discriptionText, true);
                    GI.Close();
                    if (temp != "-1" && SteamTwo.Cryptography.Encrypt(DEFUALT_KEY, temp).Equals(SteamTwoProperties.jsonSetting.encryptedKeySetting))
                    {
                        encryptionKey = temp;
                    }
                    else
                    {
                        attempts++;
                        discriptionText = "Encryption key is invalid, enter a valid encryption key";
                        setupEncryptionKey(attempts, discriptionText);
                    }
                }
                else
                {
                    if (SteamTwoProperties.jsonSetting.badAttemptSetting)
                    {
                        SteamTwoProperties.jsonSetting.encryptedSetting = false;
                        SteamTwoProperties.jsonSetting.encryptedKeySetting = DEFUALT_KEY_TEST;
                        Properties.Settings.Default.Save();
                        encryptionKey = DEFUALT_KEY;
                        File.Delete(SAVE_FILE_NAME);
                        System.Windows.Forms.MessageBox.Show("Encryption key will reset back to defualt key and previous account details will be deleted.", "Encryption", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
                    }
                    else
                    {
                        Environment.Exit(0);
                    }
                }
            }
            else
            {
                encryptionKey = DEFUALT_KEY;
            }
        }

19 View Source File : LoginViewModel.cs
License : MIT License
Project Creator : ahmed-abdelrazek

public Task OnLoadedAsync()
        {
            connectionStringBuilder.ConnectionString = Properties.Settings.Default.LiteDbConnectionString;
            if (string.IsNullOrWhiteSpace(connectionStringBuilder.ConnectionString) || !File.Exists(connectionStringBuilder["Filename"].ToString()) || !Properties.Settings.Default.IsConfigured)
            {
                _logger.LogInformation("Opening the setting to config the app");
                _windowManager.ShowDialog<SettingsViewModel>();
                if (!Properties.Settings.Default.IsConfigured)
                {
                    _logger.LogWarning("The app isn't configured and will now shutdown");
                    Environment.Exit(0);
                }
            }
            return Task.CompletedTask;
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 52ABP

public static void Main(string[] args)
        {
            ParseArgs(args);

            using (var bootstrapper = AbpBootstrapper.Create<PhoneBookMigratorModule>())
            {
                bootstrapper.IocManager.IocContainer
                    .AddFacility<LoggingFacility>(
                        f => f.UseAbpLog4Net().WithConfig("log4net.config")
                    );

                bootstrapper.Initialize();

                using (var migrateExecuter = bootstrapper.IocManager.ResolveAsDisposable<MulreplacedenantMigrateExecuter>())
                {
                    var migrationSucceeded = migrateExecuter.Object.Run(_quietMode);
                    
                    if (_quietMode)
                    {
                        // exit clean (with exit code 0) if migration is a success, otherwise exit with code 1
                        var exitCode = Convert.ToInt32(!migrationSucceeded);
                        Environment.Exit(exitCode);
                    }
                    else
                    {
                        Console.WriteLine("Press ENTER to exit...");
                        Console.ReadLine();
                    }
                }
            }
        }

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : 0x2b00b1e5

static void Main(string[] args)
        {

            Console.WriteLine("Running...");
            try
            {
                FL_RPC.Init();
            }
            catch (Exception e)
            {
                Console.WriteLine("\n \nERROR: " + e.Message);
                Console.WriteLine("INFO: Exception Name: " + e.GetType());
                Console.WriteLine("\n");
                FL_RPC.StopAndExit();
                Environment.Exit(-1);
            }
        }

19 View Source File : GetInput.xaml.cs
License : GNU General Public License v3.0
Project Creator : 00000vish

private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            Environment.Exit(0);
        }

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : 00000vish

[STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            try
            {
                //since cant detect if user open or started with windows
                //this app will only open with windows and opens app with -startup let main know its open with windowws
                checkArgs();
            }
            catch (Exception D) { MessageBox.Show(D.ToString());}           
            Environment.Exit(0);
        }

19 View Source File : frmMain.cs
License : GNU General Public License v3.0
Project Creator : 0x00000FF

private void KillAllThread(object sender, FormClosedEventArgs e)
        {
            Environment.Exit(0);
        }

19 View Source File : Client.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : 0xthirteen

private void RdpConnectionOnOnDisconnected(object sender, IMsTscAxEvents_OnDisconnectedEvent e)
        {
            DisconnectCode = e.discReason;
            var dire = Enum.GetName(typeof(DisconnectReasons), (uint)DisconnectCode);
            Console.WriteLine("[+] Connection closed     :  {0}", target);
            if(e.discReason != 1)
            {
                Console.WriteLine("[-] Disconnection Reason  :  {0} - {1}", DisconnectCode, dire);
            }
            Environment.Exit(0);
        }

19 View Source File : Runner.cs
License : MIT License
Project Creator : actions

private void CtrlCHandler(object sender, EventArgs e)
        {
            _term.WriteLine("Exiting...");
            if (_inConfigStage)
            {
                HostContext.Dispose();
                Environment.Exit(Constants.Runner.ReturnCode.TerminatedError);
            }
            else
            {
                ConsoleCancelEventArgs cancelEvent = e as ConsoleCancelEventArgs;
                if (cancelEvent != null && HostContext.GetService<IConfigurationStore>().IsServiceConfigured())
                {
                    ShutdownReason reason;
                    if (cancelEvent.SpecialKey == ConsoleSpecialKey.ControlBreak)
                    {
                        Trace.Info("Received Ctrl-Break signal from runner service host, this indicate the operating system is shutting down.");
                        reason = ShutdownReason.OperatingSystemShutdown;
                    }
                    else
                    {
                        Trace.Info("Received Ctrl-C signal, stop Runner.Listener and Runner.Worker.");
                        reason = ShutdownReason.UserCancelled;
                    }

                    HostContext.ShutdownRunner(reason);
                }
                else
                {
                    HostContext.ShutdownRunner(ShutdownReason.UserCancelled);
                }
            }
        }

See More Examples