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 Source : SocketListener.cs
with MIT License
from amazingalek

private void ProcessMessage(byte[] bytes, int count)
		{
			var message = Encoding.UTF8.GetString(bytes, 0, count);
			var jsons = message.Split('\n');
			foreach (var json in jsons)
			{
				if (string.IsNullOrWhiteSpace(json))
				{
					continue;
				}

				ModSocketMessage data;
				try
				{
					data = JsonConvert.DeserializeObject<ModSocketMessage>(json);
				}
				catch (Exception ex)
				{
					ConsoleUtils.WriteByType(MessageType.Warning, $"Failed to process following message:{Separator}\n{json}{Separator}");
					ConsoleUtils.WriteByType(MessageType.Warning, $"Reason: {ex.Message}");
					continue;
				}

				if (data.Type == MessageType.Quit && !_hasReceivedFatalMessage)
				{
					Environment.Exit(0);
				}
				else if (data.Type == MessageType.Fatal)
				{
					_hasReceivedFatalMessage = true;
				}

				var nameTypePrefix = $"[{data.SenderName}.{data.SenderType}] : ";

				var messageData = data.Message;
				messageData = messageData.Replace("\n", $"\n{new string(' ', nameTypePrefix.Length)}");

				ConsoleUtils.WriteByType(data.Type, $"{nameTypePrefix}{messageData}");
			}
		}

19 Source : CommonUtilities.cs
with GNU General Public License v2.0
from AmanoTooko

public static async void GetLatestVersion()
        {
            var wc = new WebClient();
            try
            {
                var nowVersion = replacedembly.GetExecutingreplacedembly().GetName().Version.ToString();
               
                System.Threading.Thread.Sleep(50);
                var newVersionJson = await UpdateHelper.UpdateHelper.CheckUpdate();
                System.Threading.Thread.Sleep(50);
                
                try
                {
                    var versionObj = JsonConvert.DeserializeObject<versionObject>(newVersionJson);
                    ParameterController.countDownPacket = versionObj.countDownPacket;
                    ParameterController.ensemblePacket = versionObj.ensemblePacket;
                    ParameterController.ensembleStartPacket = versionObj.ensembleStartPacket;
                    ParameterController.ensembleStopPacket = versionObj.ensembleStopPacket;
                    ParameterController.partyStopPacket = versionObj.partyStopPacket;
                    
                    if (versionObj.isRefuseToUse||versionObj.APIVersion==2)
                    {
                        Environment.Exit(-1);
                    }
                    if (nowVersion != versionObj.Version)
                    {
                        if (MessageBox.Show(new Form() { TopMost = true }, $"检测到新版本{versionObj.Version}已经发布,点击确定下载最新版哦!\r\n " +
                                           $"当然就算你点了取消,这个提示每次打开还会出现的哦!" +
                                           $"下载错误可以去NGA发布帖哦!bbs.nga.cn/read.php?tid=18790669 \r\n" +
                                           $"新版本更新内容:{versionObj.Description}", "哇——更新啦!",
                               MessageBoxButtons.OKCancel,
                               MessageBoxIcon.Information) == DialogResult.OK)
                        {
                            Process.Start("http://blog.ffxiv.cat/index.php/download/");

                        }
                        if (versionObj.isForceUpdate)
                        {
                            Environment.Exit(-2);
                        }
                    }
                       



                }
                catch (Exception e)
                {
                    MessageBox.Show(e.ToString());
                    Console.WriteLine(e);
                    
                }
                
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
                
            }
        }

19 Source : LauncherUpdater.cs
with GNU General Public License v3.0
from AM2R-Community-Developers

public static void Main()
        {
            log.Info("Running update check...");

            string version = VERSION.Replace(".", "");

            //update section

            //delete old files that have been left
            if (File.Exists(CrossPlatformOperations.CURRENTPATH + "/AM2RLauncher.bak"))
            {
                log.Info("AM2RLauncher.bak detected. Removing file.");
                File.Delete(CrossPlatformOperations.CURRENTPATH + "/AM2RLauncher.bak");
            }
            if (currentPlatform.IsWinForms && File.Exists(oldConfigPath))
            {
                log.Info(CrossPlatformOperations.LAUNCHERNAME + ".oldCfg detected. Removing file.");
                File.Delete(oldConfigPath);
            }
            if (currentPlatform.IsWinForms && Directory.Exists(CrossPlatformOperations.CURRENTPATH + "/oldLib"))
            {
                log.Info("Old lib folder detected, removing folder.");
                Directory.Delete(CrossPlatformOperations.CURRENTPATH + "/oldLib", true);
            }

            // Clean up old update libs
            if (currentPlatform.IsWinForms && Directory.Exists(CrossPlatformOperations.CURRENTPATH + "/lib"))
            {
                foreach (FileInfo file in new DirectoryInfo(CrossPlatformOperations.CURRENTPATH + "/lib").GetFiles())
                {
                    if (file.Name.EndsWith(".bak"))
                        file.Delete();
                }

                // Do the same for each subdir
                foreach (DirectoryInfo dir in new DirectoryInfo(CrossPlatformOperations.CURRENTPATH + "/lib").GetDirectories())
                {
                    foreach (FileInfo file in dir.GetFiles())
                    {
                        if (file.Name.EndsWith(".bak"))
                            file.Delete();
                    }
                }
            }

            //check settings if autoUpdateLauncher is set to true
            bool autoUpdate = bool.Parse(CrossPlatformOperations.ReadFromConfig("AutoUpdateLauncher"));

            if (autoUpdate)
            {
                log.Info("AutoUpdate Launcher set to true!");

                //this is supposed to fix the updater throwing an exception on windows 7 and earlier(?)
                //see this for information: https://stackoverflow.com/questions/2859790/the-request-was-aborted-could-not-create-ssl-tls-secure-channel and https://stackoverflow.com/a/50977774
                if (currentPlatform.IsWinForms)
                {
                    ServicePointManager.Expect100Continue = true;
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                }

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://github.com/AM2R-Community-Developers/AM2RLauncher/releases/latest");
                HttpWebResponse response = null;
                try
                {        
                    response = (HttpWebResponse)request.GetResponse();
                }
                catch (WebException)
                {
                    log.Error("WebException caught! Displaying MessageBox.");
                    MessageBox.Show(Language.Text.NoInternetConnection);
                    return;
                }

                Uri realUri = response.ResponseUri;
                string onlineVersion = realUri.AbsoluteUri.Substring(realUri.AbsoluteUri.LastIndexOf('/') + 1);
                bool isCurrentVersionOutdated = false;

                string[] localVersionArray = VERSION.Split('.');
                string[] onlineVersionArray = onlineVersion.Split('.');

                for (int i = 0; i < localVersionArray.Length; i++)
                {
                    if (int.Parse(onlineVersionArray[i]) > int.Parse(localVersionArray[i]))
                    {
                        isCurrentVersionOutdated = true;
                        break;
                    }
                }

                if (isCurrentVersionOutdated)
                {
                    log.Info("Current version (" + VERSION + ") is outdated! Initiating update for version " + onlineVersion + ".");

                    string tmpUpdatePath = CrossPlatformOperations.CURRENTPATH + "/tmpupdate/";
                    string zipPath = CrossPlatformOperations.CURRENTPATH + "/launcher.zip";

                    // Clean tmpupdate
                    if (Directory.Exists(tmpUpdatePath))
                        Directory.Delete(tmpUpdatePath);
                    if (!Directory.Exists(tmpUpdatePath))
                        Directory.CreateDirectory(tmpUpdatePath);

                    try
                    { 
                        using (var client = new WebClient())
                        {
                            string platformSuffix = "";
                            if (currentPlatform.IsWinForms) platformSuffix = "_win";
                            else if (currentPlatform.IsGtk) platformSuffix = "_lin";

                            log.Info("Downloading https://github.com/AM2R-Community-Developers/AM2RLauncher/releases/latest/download/AM2RLauncher_" + onlineVersion + platformSuffix + ".zip to " + zipPath + ".");
                            
                            client.DownloadFile("https://github.com/AM2R-Community-Developers/AM2RLauncher/releases/latest/download/AM2RLauncher_" + onlineVersion + platformSuffix + ".zip", zipPath);

                            log.Info("File successfully downloaded.");
                        }
                    }
                    catch(UnauthorizedAccessException)
                    {
                        log.Error("UnauthorizedAccessException caught! Displaying MessageBox.");
                        MessageBox.Show(Language.Text.UnauthorizedAccessMessage);
                        return;
                    }

                    ZipFile.ExtractToDirectory(zipPath, tmpUpdatePath);
                    log.Info("Updates successfully extracted to " + tmpUpdatePath);

                    File.Delete(zipPath);
                    File.Move(updatePath + "/" + CrossPlatformOperations.LAUNCHERNAME, CrossPlatformOperations.CURRENTPATH + "/AM2RLauncher.bak");
                    if (currentPlatform.IsWinForms) File.Move(CrossPlatformOperations.LAUNCHERNAME + ".config", CrossPlatformOperations.LAUNCHERNAME + ".oldCfg");

                    foreach (var file in new DirectoryInfo(tmpUpdatePath).GetFiles())
                    {
                        log.Info("Moving " +  file.FullName + " to " + CrossPlatformOperations.CURRENTPATH + "/" + file.Name);
                        File.Copy(file.FullName, updatePath + "/" + file.Name, true);
                    }
                    // for windows, the actual application is in "AM2RLauncher.dll". Which means, we need to update the lib folder as well.
                    if (currentPlatform.IsWinForms && Directory.Exists(CrossPlatformOperations.CURRENTPATH + "/lib"))
                    {
                        // Directory.Move(CrossPlatformOperations.CURRENTPATH + "/lib", CrossPlatformOperations.CURRENTPATH + "/oldLib");
                        // So, because Windows behavior is dumb...

                        // Rename all files in lib to *.bak
                        foreach (FileInfo file in new DirectoryInfo(CrossPlatformOperations.CURRENTPATH + "/lib").GetFiles())
                        {
                            file.CopyTo(file.Directory + file.Name + ".bak");
                        }

                        // Do the same for each subdir
                        foreach(DirectoryInfo dir in new DirectoryInfo(CrossPlatformOperations.CURRENTPATH + "/lib").GetDirectories())
                        {
                            foreach (FileInfo file in dir.GetFiles())
                            {
                                file.CopyTo(file.Directory + file.Name + ".bak");
                            }
                        }

                        // Yes, the above calls could be recursive. No, I can't be bothered to make them as such.

                        HelperMethods.DirectoryCopy(tmpUpdatePath + "lib", CrossPlatformOperations.CURRENTPATH + "/lib", true);
                    }
                    
                    Directory.Delete(tmpUpdatePath, true);

                    CrossPlatformOperations.CopyOldConfigToNewConfig();

                    log.Info("Files extracted. Preparing to restart executable...");

                    if (currentPlatform.IsGtk) System.Diagnostics.Process.Start("chmod", "+x ./AM2RLauncher.Gtk");

                    System.Diagnostics.Process.Start(updatePath + "/" + CrossPlatformOperations.LAUNCHERNAME);
                    Environment.Exit(0);
                }
            }
            else
            {
                log.Info("AutoUpdate Launcher set to false. Exiting update check.");
            }
        }

19 Source : Program.cs
with Apache License 2.0
from AmpScm

static void Run(string[] args)
        {
            List<string> argList = new List<string>(args);
            bool _transparentHack = false;
            while (argList.Count > 0 && argList[0].StartsWith("-"))
            {
                string arg = argList[0];
                if (arg == "--")
                {
                    argList.RemoveAt(0);
                    break;
                }
                switch (arg)
                {
                    case "-th":
                        _transparentHack = true;
                        break;
                    default:
                        Console.Error.WriteLine("Unhandled argument {0}", arg);
                        Environment.Exit(1);
                        break;
                }
                argList.RemoveAt(0);
            }

            if (argList.Count < 2)
            {
                Console.Error.WriteLine("Required argument missing");
                Console.Error.WriteLine("BitmapExtractor [-th] <replacedembly> <dir>");
                Environment.Exit(1);
            }
            string from = argList[0];
            string dir = argList[1];

            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir);

            CommandTable table = new CommandTable();

            Console.WriteLine("Dumping bitmaps in {0} to {1}:", from, dir);

            replacedembly asm = null;
            try
            {
                asm = replacedembly.LoadFile(from);
            }
            catch { }


            try
            {
                if (asm != null
                    ? !table.Read(replacedembly.LoadFile(from), new ReadErrorHandler())
                    : !table.Read(from, new ReadErrorHandler()))
                {
                    Console.Error.WriteLine("* Loading failed, exiting *");
                    Environment.Exit(1);
                }
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e.ToString());
                Environment.Exit(1);
            }

            BitmapItemList bitmaps = table.GetBitmapList();

            foreach (BitmapItem bi in bitmaps)
            {
                uint resourceId = bi.IDResource;
                Dictionary<uint, int> map = new Dictionary<uint, int>();
                Color transparentColor = Color.FromArgb(0xFF, 0xFF, 0, 0xFF);
                bool haveColor = false;

                for (int i = 0; i < bi.UsedSlots.Length; i++)
                {
                    map[bi.UsedSlots[i]] = i;
                    if (_transparentHack && !haveColor && bi.UsedSlots[i] == 1)
                    {
                        Bitmap bm = bitmaps.GetBitmap(bi.GID, bi.UsedSlots[i]);
                        transparentColor = bm.GetPixel(0, 0);
                        Console.WriteLine("Found color: {0}", transparentColor);
                        haveColor = true;
                    }
                }

                ButtonList bl = table.GetButtonList();

                foreach (CommandButton cb in table.GetButtonList())
                {
                    if (cb.IconGID != bi.GID)
                        continue;

                    Bitmap bm = bitmaps.GetBitmap(cb.IconGID, cb.IconIndex);
                    string name = cb.CanonicalName.Trim(' ', '.', '\t', '&').Replace(" ", "").Replace("&", "");

                    if (bm == null)
                    {
                        Console.WriteLine("Couldn't get icon for {0}", name);
                        continue;
                    }

                    if (_transparentHack)
                        bm.MakeTransparent(transparentColor);

                    try
                    {
                        bm.Save(Path.Combine(dir, name + ".png"), ImageFormat.Png);
                        Console.WriteLine("Writing {0}. Succeeded", name);
                    }
                    catch
                    {
                        Console.WriteLine("Writing {0}. Failed", name);
                    }
                }
            }
            Console.WriteLine("Done");
        }

19 Source : Program.cs
with MIT License
from anastasios-stamoulis

void load_data() {
      if (!System.IO.Directory.Exists(DATASET_PATH)) {
        Console.WriteLine("You need to download the data set first");
        System.Environment.Exit(1);
      }
      create_map_txt_files();
    }

19 Source : Util.cs
with MIT License
from anastasios-stamoulis

public static string download_model_if_needed(string fullpath, string dstFilename, string downlink_url) {
      System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
      if (fullpath == null) {
        fullpath = fullpathForDownloadedFile(dstDir: "DownloadedModels", dstFilename: dstFilename);
      }
      if (System.IO.File.Exists(fullpath)) {
        return fullpath;
      }
      var success = FromStackOverflow.FileDownloader.DownloadFile(downlink_url, fullpath, timeoutInMilliSec: 3600000);
      if (!success) {
        System.Console.WriteLine("There was a problem with the download of the caffe model");
        System.Environment.Exit(1);
      }
      return fullpath;
    }

19 Source : Program.cs
with GNU General Public License v3.0
from AndreiFedarets

private static void ReportFatalError(Exception exception)
        {
            LoggingProvider.Current.Log(TraceEventType.Critical, exception);
            Thread thread = new Thread(() =>
            {
                MessageBox.Show(string.Format("Unable to run application.{0}{1}", Environment.NewLine, exception), "Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Environment.Exit(0);
            });
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
        }

19 Source : ChronosApplication.cs
with GNU General Public License v3.0
from AndreiFedarets

public void Close()
        {
            lock (Lock)
            {
                if (!CanClose())
                {
                    return;
                }
                if (_applicationState == ApplicationState.Started)
                {
                    ApplicationState = ApplicationState.Closing;
                    try
                    {
                        OnBeginShutdown();
                        CloseInternal();
                        _replacedemblyResolver.Dispose();
                        _currentProcess.Dispose();
                        AppDomain.CurrentDomain.UnhandledException -= OnUnhandledException;
                        _shared = null;
                        ApplicationState = ApplicationState.Closed;
                        OnEndShutdown();
                    }
                    catch (Exception exception)
                    {
                        LoggingProvider.Current.Log(System.Diagnostics.TraceEventType.Critical, exception);
                        throw;
                    }
                    finally
                    {
                        Dispose();
                        DisposableTracker.TraceUndisposedResources();
                    }
                    if (_processOwner)
                    {
                        //TODO: Replace this code with more appropriate process closing
                        ThreadPool.QueueUserWorkItem(c =>
                            {
                                Thread.Sleep(1000);
                                Environment.Exit(0);
                            });
                    }
                }
            }
        }

19 Source : App.xaml.cs
with GNU General Public License v3.0
from AndreiFedarets

private void ReportFatalError(Exception exception)
        {
            LoggingProvider.Current.Log(TraceEventType.Critical, exception);
            Thread thread = new Thread(() =>
            {
                MessageBox.Show(string.Format("Unable to run application.{0}{1}", Environment.NewLine, exception), "Fatal Error", MessageBoxButton.OK, MessageBoxImage.Error);
                Environment.Exit(0);
            });
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
        }

19 Source : Update.cs
with MIT License
from ANF-Studios

public void DownloadWinPath(in ReleaseInfo releaseInfo, Action finalJob = null)
        {
            bool appveyor = Environment.GetEnvironmentVariable("APPVEYOR", EnvironmentVariableTarget.Process) == "True";
            if (!confirmDownload)
            {
                Console.WriteLine("Release Information:\n"
                    + $"replacedle: {releaseInfo.ReleaseName}\n"
                    + $"Version: v{releaseInfo.TagName}"
                    + (releaseInfo.IsPrerelease ? " (Prerelease)\n" : "\n")
                    + $"File: {releaseInfo.Releasereplacedet.ExecutableName}\n");
                Console.Write($"Confirm installation of WinPath v{releaseInfo.TagName} (y/n): ");

                if (!appveyor)
                    if ((Console.ReadKey()).Key == ConsoleKey.Y)
                        confirmDownload = true;
                    else
                        Environment.Exit(Environment.ExitCode);
                else
                    return;
            }

            Directory.CreateDirectory(downloadDirectory);

            Console.WriteLine("\nDownloading " + releaseInfo.Releasereplacedet.ExecutableName + "...");
            try
            {
                using (WebClient webClient = new WebClient())
                {
                    webClient.Headers.Add(HttpRequestHeader.UserAgent, "WinPath");
                    webClient.DownloadFile(releaseInfo.Releasereplacedet.DownloadUrl, downloadDirectory + "WinPath.exe");
                    webClient.DownloadFile(releaseInfo.Updater.DownloadUrl, downloadDirectory + "WinPath.Updater.exe");
                }
            }
            catch (WebException exception)
            {
                Console.WriteLine("Couldn't download WinPath due to an error in networking:\n" + exception);
                Environment.Exit(1);
            }
            catch (Exception exception)
            {
                Console.WriteLine("Couldn't download WinPath:\n" + exception.Message);
                Environment.Exit(1);
            }
            finally
            {
                Console.WriteLine("Downloaded WinPath v" + releaseInfo.TagName + "...");
                Console.WriteLine("Installing WinPath...");

                bool administratorPermissions = IsUserAnAdmin();
                int processExitCode = 1; // Default to unsuccessful.

                ProcessStartInfo process = new ProcessStartInfo
                {
                    FileName = downloadDirectory + "WinPath.Updater.exe",
                    Arguments = "launching_from_winpath", // To tell WinPath.Updater that a user isn't launching it.
                    UseShellExecute = !administratorPermissions,
                    Verb = administratorPermissions ? string.Empty : "runas",
                    CreateNoWindow = true
                };
                try
                {
                    Console.WriteLine("Starting update...");
                    if (appveyor)
                    {
                        const string installationPath = "C:\\Program Files\\WinPath\\";
                        Directory.CreateDirectory(installationPath);
                        File.Move(downloadDirectory + "\\WinPath.exe", installationPath + "WinPath.exe");
                        processExitCode = 0;
                    }
                    else
                    {
                        var application = Process.Start(process);
                        application.WaitForExit();
                        processExitCode = application.ExitCode;
                        Console.WriteLine("Installer exited with code: " + application.ExitCode);
                    }
                }
                catch (System.ComponentModel.Win32Exception exception)
                {
                    if (exception.NativeErrorCode == 1223)
                        Console.WriteLine("Could not install WinPath because administrator permissions were not provided!");
                    else
                        Console.WriteLine("Could not install WinPath: " + exception.Message);
                }
                catch (Exception exception)
                {
                    Console.WriteLine("Could not update WinPath: " + exception.Message);
                }
                if (processExitCode == 0) // If application exited successfully.
                {
                    WinPath.Library.UserPath userPath = WinPath.Program.GetUserPath();
                    string path = Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.User);
                    if (!path.EndsWith(";"))
                        Environment.SetEnvironmentVariable("Path", (path += ";"), EnvironmentVariableTarget.User);
                    path = path.Replace("/", "\\");
                    if (Environment.Is64BitOperatingSystem)
                       if (!(path.Contains("%programfiles%\\winpath", StringComparison.CurrentCultureIgnoreCase) || path.Contains("c:\\program files\\winpath", StringComparison.CurrentCultureIgnoreCase)))
                           userPath.AddToPath("%PROGRAMFILES%\\WinPath\\", true, DateTime.Now.ToFileTime().ToString());
                    else
                       if (!(path.Contains("%programfiles(x86)%\\winpath", StringComparison.CurrentCultureIgnoreCase) || path.Contains("c:\\program files (x86)\\winpath", StringComparison.CurrentCultureIgnoreCase)))
                           userPath.AddToPath("%PROGRAMFILES(X86)%\\WinPath\\", true, DateTime.Now.ToFileTime().ToString());
                    Console.WriteLine("[STATUS] Installed WinPath successfully!");
                    Environment.ExitCode = 0;
                }
                else // If not.
                {
                    Console.WriteLine("[STATUS] Could not update WinPath! Please see the log file: " + logDirectory + "log.txt");
                    Environment.ExitCode = 1;
                }
                finalJob?.Invoke();
            }
        }

19 Source : Update.cs
with MIT License
from ANF-Studios

public List<Release> GetReleases()
        {
            string response = String.Empty;
            List<Release> releases;
            try
            {
                using (WebClient webClient = new WebClient())
                {
                    webClient.Headers.Add(HttpRequestHeader.UserAgent, "WinPath");
                    response = webClient.DownloadString(Update.releases);
                    #if DEBUG
                        Console.WriteLine("Response: " + response);
                    #endif
                }

                releases = JsonSerializer.Deserialize<List<Release>>(response);
                return releases;
                //Console.WriteLine(releases[(releases.Count - 1)].replacedets[4].DownloadUrl);
            }
            catch (WebException webException)
            {
                Console.WriteLine("Could not make web request!\n" + webException.Message);
                Environment.Exit(exitCode: 1);
            }
            return null;
        }

19 Source : Update.cs
with MIT License
from ANF-Studios

public replacedet GetreplacedetForProcess(in Release release)
        {
            if (release.replacedets.Count < 1)
            {
                Console.WriteLine($"There are no executables in release v{release.TagName}! Exiting...");
                Environment.Exit(1);
            }

            replacedet? processedreplacedet = null;
            string architecture = GetArchitecture(RuntimeInformation.ProcessArchitecture).ToLower();
            release.replacedets.ForEach((replacedet) => {
                if (OperatingSystem.IsWindowsVersionAtLeast(10) && Environment.Is64BitOperatingSystem)
                    if (replacedet.ExecutableName.Contains("win10-x64"))
                        processedreplacedet = replacedet;
                if (replacedet.ExecutableName.ToLower().Contains(architecture))
                    processedreplacedet = replacedet;
            });
            return (replacedet)processedreplacedet;
        }

19 Source : MainWindow.xaml.cs
with GNU General Public License v3.0
from andyvorld

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

19 Source : Program.cs
with MIT License
from ANF-Studios

public static void Main(string[] args)
        {
            Console.replacedle = AppDomain.CurrentDomain.FriendlyName;
            string currentVersion = GetInstalledWinPathVersion();

            if (currentVersion is null)
                Environment.Exit(-1);

            if (currentVersion == "0.2.0") // Backwards compatibility support.
                executableDirectory = $"{Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)}\\WinPath\\temp\\download\\WinPath.exe";

            if (int.Parse(currentVersion[2].ToString()) > 2)
            {
                if (args.Length < 1) // To prevent crashing if args is 0 in the next if-statement.
                    return;
                if (args[0] != launchingFromWinPath)
                    return;
            }
            try
            {
                if (Environment.Is64BitOperatingSystem)
                {
                    Directory.CreateDirectory(
                        //Environment.GetFolderPath(
                        //    Environment.SpecialFolder.ProgramFiles
                        //)
                        "C:\\Program Files" + "\\WinPath"
                    );
                    File.Move(
                        executableDirectory,
                        //Environment.GetFolderPath(
                        //    Environment.SpecialFolder.ProgramFiles
                        //)
                        "C:\\Program Files" + "\\WinPath\\WinPath.exe",
                        true
                    );
                }
                else
                {
                    Directory.CreateDirectory(
                        //Environment.GetFolderPath(
                        //    Environment.SpecialFolder.ProgramFilesX86
                        //)
                        "C:\\Program Files (x86)" + "\\WinPath"
                    );
                    File.Move(
                        executableDirectory,
                        //Environment.GetFolderPath(
                        //    Environment.SpecialFolder.ProgramFilesX86
                        //)
                        "C:\\Program Files (x86)" + "\\WinPath\\WinPath.exe",
                        true
                    );
                }
                Console.WriteLine("WinPath is installed successfully!");
                Environment.ExitCode = 0;
            }
            catch (Exception exception)
            {
                Console.WriteLine("Could not install WinPath: " + exception.Message);
                //Console.ReadKey();
                Directory.CreateDirectory(logDirectory.Replace("log.txt", string.Empty));
                File.AppendAllText(
                    logDirectory,
                    DateTime.Today.ToLongDateString()
                    + "\n"
                    + errorMessage
                    + exception.Message
                    + "\n"
                    + "Please report this to the developer."
                    + "\n"
                );
                Console.WriteLine("Exception logged at " + logDirectory);
                Environment.ExitCode = 1;
            }
            Environment.Exit(Environment.ExitCode);
        }

19 Source : Program.cs
with GNU General Public License v3.0
from Angelinsky7

static void Main(string[] args) {

            if (args.Length != 3) { Environment.Exit(3); return; }

            String msi = args[0];
            String location = args[1];
            Int32 pid = Int32.Parse(args[2]);

            if (pid == 0) { Environment.Exit(100); return; }
            if (!File.Exists(msi)) { Environment.Exit(404); return; }

            Process apptray = Process.GetProcessById(pid);
            String appNameFilename = apptray.MainModule.FileName;
            Boolean apptrayAsExited = apptray.WaitForExit(60000);

            if (!apptrayAsExited) { Environment.Exit(500); return; }

            ProcessStartInfo installerInfo = new ProcessStartInfo() {
                Arguments = $"/i {msi}",
                UseShellExecute = true,
                FileName = "msiexec",
                Verb = "runas"
            };

            Boolean installerAsExited = false;
            try {
                Process installer = Process.Start(installerInfo);
                installerAsExited = installer.WaitForExit(60000);
            } catch (Win32Exception ex) {
                if (ex.NativeErrorCode == 1223) { Environment.Exit(1223); return; }
            }

            if (installerAsExited && File.Exists(appNameFilename)) {
                Process.Start(new ProcessStartInfo() {
                    Arguments = $"/C del /Q /F {msi}",
                    CreateNoWindow = true,
                    WindowStyle = ProcessWindowStyle.Hidden,
                    FileName = "cmd",
                });
                Process.Start(appNameFilename);
            }

        }

19 Source : UpdateSettingsViewModel.cs
with MIT License
from AnnoDesigner

private async void ExecuteDownloadPresets(object param)
        {
            if (FoundPresetRelease is null)
            {
                return;
            }

            BusyContent = _localizationHelper.GetLocalization("UpdatePreferencesBusyDownloadPresets");
            IsBusy = true;

            if (!_commons.CanWriteInFolder())
            {
                //already asked for admin rights?
                if (Environment.GetCommandLineArgs().Any(x => x.Trim().Equals(Constants.Argument_Ask_For_Admin, StringComparison.OrdinalIgnoreCase)))
                {
                    _messageBoxService.ShowWarning($"You have no write access to the folder.{Environment.NewLine}The update can not be installed.",
                        _localizationHelper.GetLocalization("Error"));

                    IsBusy = false;
                    return;
                }

                _messageBoxService.ShowMessage(_localizationHelper.GetLocalization("UpdateRequiresAdminRightsMessage"),
                    _localizationHelper.GetLocalization("AdminRightsRequired"));

                _appSettings.Save();
                _commons.RestartApplication(true, Constants.Argument_Ask_For_Admin, App.ExecutablePath);
            }

            //Context is required here, do not use ConfigureAwait(false)
            var newLocation = await _updateHelper.DownloadReleaseAsync(FoundPresetRelease);
            logger.Debug($"downloaded new preset ({FoundPresetRelease.Version}): {newLocation}");

            IsBusy = false;

            _appSettings.Save();
            _commons.RestartApplication(false, null, App.ExecutablePath);

            Environment.Exit(-1);
        }

19 Source : App.xaml.cs
with MIT License
from AnnoDesigner

private void LogUnhandledException(Exception ex, string @event)
        {
            logger.Error(ex, @event);

            ShowMessageWithUnexpectedError(false);
            MainWindow.DataContext.AnnoCanvas.CheckUnsavedChangesBeforeCrash();

            Environment.Exit(-1);
        }

19 Source : App.xaml.cs
with MIT License
from AnnoDesigner

public static void ShowMessageWithUnexpectedError(bool exitProgram = true)
        {
            var message = "An unhandled exception occurred.";

            //find loaction of log file
            var fileTarget = LogManager.Configuration.FindTargetByName("MainLogger") as FileTarget;
            var logFile = fileTarget?.FileName.Render(new LogEventInfo());
            if (!string.IsNullOrWhiteSpace(logFile))
            {
                logFile = Path.Combine(Path.GetDirectoryName(replacedembly.GetEntryreplacedembly().Location), logFile);
                if (File.Exists(logFile))
                {
                    logFile = logFile.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
                    message += $"{Environment.NewLine}{Environment.NewLine}Details in \"{logFile}\".";
                }
            }

            _messageBoxService.ShowError(message);

            if (exitProgram)
            {
                Environment.Exit(-1);
            }
        }

19 Source : App.xaml.cs
with MIT License
from AnnoDesigner

private async void Application_Startup(object sender, StartupEventArgs e)
        {
            // retrieve file argument if given
            if (e.Args.Length > 0)
            {
                if (!e.Args[0].Equals(Constants.Argument_Ask_For_Admin, StringComparison.OrdinalIgnoreCase))
                {
                    FilenameArgument = e.Args[0];
                }
            }

            using var mutexAnnoDesigner = new Mutex(true, MutexHelper.MUTEX_ANNO_DESIGNER, out var createdNewMutex);
            //Are there other processes still running?
            if (!createdNewMutex)
            {
                try
                {
                    var currentTry = 0;
                    const int maxTrys = 10;
                    while (!createdNewMutex && currentTry < maxTrys)
                    {
                        logger.Trace($"Waiting for other processes to finish. Try {currentTry} of {maxTrys}");

                        createdNewMutex = mutexAnnoDesigner.WaitOne(TimeSpan.FromSeconds(1), true);
                        currentTry++;
                    }

                    if (!createdNewMutex)
                    {
                        _messageBoxService.ShowMessage(Localization.Localization.Instance.GetLocalization("AnotherInstanceIsAlreadyRunning"));
                        Environment.Exit(-1);
                    }
                }
                catch (AbandonedMutexException)
                {
                    //mutex was killed
                    createdNewMutex = true;
                }
            }

            try
            {
                //check if file is not corrupt
                _appSettings.Reload();

                if (_appSettings.SettingsUpgradeNeeded)
                {
                    _appSettings.Upgrade();
                    _appSettings.SettingsUpgradeNeeded = false;
                    _appSettings.Save();
                }
            }
            catch (ConfigurationErrorsException ex)
            {
                logger.Error(ex, "Error upgrading settings.");

                _messageBoxService.ShowError(_localizationHelper.GetLocalization("ErrorUpgradingSettings"));

                var fileName = "";
                if (!string.IsNullOrEmpty(ex.Filename))
                {
                    fileName = ex.Filename;
                }
                else
                {
                    if (ex.InnerException is ConfigurationErrorsException innerException && !string.IsNullOrEmpty(innerException.Filename))
                    {
                        fileName = innerException.Filename;
                    }
                }

                if (File.Exists(fileName))
                {
                    File.Delete(fileName);
                }

                _appSettings.Reload();
            }

            //var updateWindow = new UpdateWindow();                
            await _updateHelper.ReplaceUpdatedPresetsFilesAsync();

            var recentFilesSerializer = new RecentFilesAppSettingsSerializer(_appSettings);

            IRecentFilesHelper recentFilesHelper = new RecentFilesHelper(recentFilesSerializer, _fileSystem, _appSettings.MaxRecentFiles);
            ITreeLocalizationLoader treeLocalizationLoader = new TreeLocalizationLoader(_fileSystem);

            var mainVM = new MainViewModel(_commons, _appSettings, recentFilesHelper, _messageBoxService, _updateHelper, _localizationHelper, _fileSystem, treeLocalizationLoader: treeLocalizationLoader);

            //TODO MainWindow.ctor calls AnnoCanvas.ctor loads presets -> change logic when to load data 
            MainWindow = new MainWindow(_appSettings);
            MainWindow.DataContext = mainVM;

            //If language is not recognized, bring up the language selection screen
            if (!_commons.LanguageCodeMap.ContainsKey(_appSettings.SelectedLanguage))
            {
                var w = new Welcome();
                w.DataContext = mainVM.WelcomeViewModel;
                w.ShowDialog();
            }
            else
            {
                _commons.CurrentLanguage = _appSettings.SelectedLanguage;
            }

            MainWindow.ShowDialog();
        }

19 Source : Commons.cs
with MIT License
from AnnoDesigner

public void RestartApplication(bool asAdmin, string parameters, string path = null)
        {
            var arguments = string.Empty;
            if (!string.IsNullOrWhiteSpace(parameters))
            {
                arguments = parameters;
            }

            arguments = arguments.Trim();

            if (string.IsNullOrWhiteSpace(path))
            {
                path = App.ExecutablePath;
            }

            var psi = new ProcessStartInfo();
            psi.FileName = path;
            psi.Arguments = arguments;

            if (asAdmin)
            {
                psi.Verb = "runas";
            }

            logger.Trace($"{nameof(RestartApplication)} {nameof(asAdmin)}: {asAdmin}{Environment.NewLine}Path: \"{psi.FileName}\"{Environment.NewLine}Arguments: {psi.Arguments}");

            var process = new Process();
            process.StartInfo = psi;
            process.Start();

            Environment.Exit(-1);
            //Application.Current.Shutdown();//sometimes hangs
        }

19 Source : Program.cs
with MIT License
from AnnoDesigner

private static void ParseArguments(string[] args)
        {
            if (args?.Any(x => x.Trim().Equals(ARG_FORCE_DOWNLOAD, StringComparison.OrdinalIgnoreCase)) == true)
            {
                logger.Trace($"used parameter: {ARG_FORCE_DOWNLOAD}");

                ForceDownload = true;
            }

            if (args?.Any(x => x.Trim().Equals(ARG_NO_WAIT, StringComparison.OrdinalIgnoreCase)) == true)
            {
                logger.Trace($"used parameter: {ARG_NO_WAIT}");

                NoWait = true;
            }

            if (args?.Any(x => x.Trim().Equals(ARG_PRETTY_PRINT, StringComparison.OrdinalIgnoreCase)) == true)
            {
                logger.Trace($"used parameter: {ARG_PRETTY_PRINT}");

                UsePrettyPrint = true;
            }

            if (args?.Any(x => x.Trim().StartsWith(ARG_OUTPUT_DIRECTORY, StringComparison.OrdinalIgnoreCase)) == true)
            {
                var curArg = args.SingleOrDefault(x => x.Trim().StartsWith(ARG_OUTPUT_DIRECTORY, StringComparison.OrdinalIgnoreCase));

                logger.Trace($"used parameter: {curArg}");

                if (!string.IsNullOrWhiteSpace(curArg))
                {
                    var splitted = curArg.Split('=');
                    if (splitted.Length == 2)
                    {
                        var outputPath = splitted[1];
                        if (string.IsNullOrWhiteSpace(outputPath))
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine($"Please specify an output directory.");
                            Environment.Exit(-1);
                        }
                        else
                        {
                            var parsedDirectory = Path.GetDirectoryName(outputPath);
                            if (!Directory.Exists(outputPath))
                            {
                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine($"The specified directory was not found: \"{outputPath}\"");
                                Environment.Exit(-1);
                            }

                            OutputDirectory = outputPath;
                        }
                    }
                }
            }

            if (args?.Any(x => x.Trim().StartsWith(ARG_VERSION, StringComparison.OrdinalIgnoreCase)) == true)
            {
                var curArg = args.SingleOrDefault(x => x.Trim().StartsWith(ARG_VERSION, StringComparison.OrdinalIgnoreCase));

                logger.Trace($"used parameter: {curArg}");

                if (!string.IsNullOrWhiteSpace(curArg))
                {
                    var splitted = curArg.Split('=');
                    if (splitted.Length == 2)
                    {
                        var versionString = splitted[1];
                        if (string.IsNullOrWhiteSpace(versionString))
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine($"Please specify a version. (x.x.x.x)");
                            Environment.Exit(-1);
                        }
                        else
                        {
                            if (!Version.TryParse(versionString, out Version parsedVersion))
                            {
                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine($"The specified version could not be parsed: \"{versionString}\" Please use format x.x.x.x");
                                Environment.Exit(-1);
                            }

                            PresetVersion = parsedVersion;
                        }
                    }
                }
            }
        }

19 Source : App.xaml.cs
with MIT License
from AnnoDesigner

private void LogUnhandledException(Exception ex, string @event)
        {
            logger.Error(ex, @event);

            var message = "An unhandled exception occurred.";

            //find loaction of log file
            var fileTarget = LogManager.Configuration.FindTargetByName("MainLogger") as FileTarget;
            var logFile = fileTarget?.FileName.Render(new LogEventInfo());
            if (!string.IsNullOrWhiteSpace(logFile))
            {
                logFile = Path.Combine(Path.GetDirectoryName(replacedembly.GetEntryreplacedembly().Location), logFile);
                if (File.Exists(logFile))
                {
                    logFile = logFile.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
                    message += $"{Environment.NewLine}{Environment.NewLine}Details in \"{logFile}\".";
                }
            }

            MessageBox.Show(message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);

            Environment.Exit(-1);
        }

19 Source : Program.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta

[MethodImpl(MethodImplOptions.NoInlining)]
        public static void Main(
            string[] args)
        {
            // ダミーで FFXIV.Framework を読み込む
            var span = CommonHelper.GetRandomTimeSpan(0.25);

            if (args == null ||
                args.Length < 2)
            {
                return;
            }

            var apiKey = args[0];
            var fileName = args[1];
            var isOnlyHistogram = args.Length >= 3 ? bool.Parse(args[2]) : false;
            var targetZoneID = args.Length >= 4 ? int.Parse(args[3]) : 0;
            var difficulty = args.Length >= 5 ? args[4] : string.Empty;

            StatisticsDatabase.Instance.APIKey = apiKey;

            if (!isOnlyHistogram)
            {
                StatisticsDatabase.Instance.CreateAsync(fileName, targetZoneID, difficulty).Wait();
                Console.WriteLine($"[FFLogs] rankings downloaded.");
            }

            StatisticsDatabase.Instance.CreateHistogramAsync(fileName).Wait();
            Console.WriteLine($"[FFLogs] histgram replacedyzed.");

            File.WriteAllLines(
                $"{fileName}.timestamp.txt",
                new[] { DateTime.Now.ToString() },
                new UTF8Encoding(false));

            Console.WriteLine($"[FFLogs] database completed. save to {fileName}.");

            Thread.Sleep(span);
            Environment.Exit(0);
        }

19 Source : Program.cs
with MIT License
from AntonyCorbett

public static void Main(string[] args)
        {
            try
            {
                Environment.Exit(Execute(args));
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex.Message);
                Environment.Exit(-20);
            }
        }

19 Source : Program.cs
with MIT License
from aolszowka

static void Main(string[] args)
        {
            if (!args.Any())
            {
                Console.WriteLine("You did not provide the required targetProject argument.");
                Environment.Exit(1);
            }

            // Get the DotGraph File
            string dotGraphFile = args.FirstOrDefault();

            // See if the target project flag has been set
            string targetProject = _ParseForTargetProjectFlag(args);

            if (string.IsNullOrWhiteSpace(dotGraphFile) || !File.Exists(dotGraphFile))
            {
                string missingDotGraphFile = "The Provided DotGraph Argument was not valid. This tool requires a valid DotGraph File.";
                Console.WriteLine(missingDotGraphFile);
                Environment.Exit(1);
            }

            if (string.IsNullOrWhiteSpace(targetProject))
            {
                string missingTargetProject = "You must provide a `-TargetProject` to this tool.";
                Console.WriteLine(missingTargetProject);
                Environment.Exit(1);
            }

            ProcessOperation operation = _ParseForOperation(args);

            IDictionary<string, SortedSet<string>> loadedGraph = DotGraph.LoadDependencyGraph(dotGraphFile);

            string consoleOutput = string.Empty;

            switch (operation)
            {
                case ProcessOperation.Default:
                case ProcessOperation.IdentifyRequiredProjects:
                    {
                        consoleOutput = IdentifyRequiredProjects.Execute(targetProject, loadedGraph);
                        break;
                    }
                case ProcessOperation.IdentifyAffectedProjects:
                    {
                        consoleOutput = IdentifyAffectedProjects.Execute(targetProject, loadedGraph);
                        break;
                    }
                case ProcessOperation.IdentifyDirectDependencyCounts:
                    {
                        consoleOutput = IdentifyDirectDependencyCounts.Execute(targetProject, loadedGraph);
                        break;
                    }
                default:
                    {
                        Console.WriteLine($"Unknown Operation {operation.ToString()}");
                        Environment.Exit(1);
                        break;
                    }
            }

            Console.WriteLine(consoleOutput);
        }

19 Source : ICU.cs
with MIT License
from aoso3

private void radButton4_Click(object sender, EventArgs e)
        {
            if (player1)
                camera_1.StopPlay();
            if (player2)
                camera_2.StopPlay();

            if (play)
            {
                t1.Abort();
                t2.Abort();
                p1.Abort();
                //p2.Abort();
            }
            try
            {
                Application.Exit();
            }
            catch (Exception eee)
            {
                Environment.Exit(Environment.ExitCode);

            }
        }

19 Source : NotLogging.cs
with Apache License 2.0
from apache

private static void Usage() 
		{
			System.Console.WriteLine(
				"Usage: NotLogging <true|false> <runLength>" + Environment.NewLine +
				"\t true indicates shipped code" + Environment.NewLine +
				"\t false indicates code in development" + Environment.NewLine +
				"\t runLength is an int representing the run length of loops"  + Environment.NewLine +
				"\t We suggest that runLength be at least 1000000 (1 million).");
			Environment.Exit(1);
		}

19 Source : HomeController.cs
with Apache License 2.0
from appsuite

public IActionResult KillApp()
        {
            Console.WriteLine("Kaboom.");
            Environment.Exit(-1);
            return View();
        }

19 Source : GetInjectedThreads.cs
with MIT License
from Apr4h

[HandleProcessCorruptedStateExceptions]
        public static List<InjectedThread> InjectedThreads()
        {
            // Check if running as administrator first? Or at least check if SeDebugPrivilege enabled?
            if(IsUserAnAdmin() == false)
            {
                Console.WriteLine("Program is not running as Administrator. Exiting...");
                System.Environment.Exit(1);
            }

            List<InjectedThread> injectedThreads = new List<InjectedThread>();

            // Create array of Process objects for each running process
            Process[] runningProcesses = Process.GetProcesses();

            // Iterate over each process and get all threads by ID
            foreach (Process process in runningProcesses)
            {
                // PID 0 and PID 4 aren't valid targets for injection
                if (process.Id != 0 && process.Id != 4)
                {
                    IntPtr hProcess;

                    try
                    {
                        // Get handle to the process
                        hProcess = OpenProcess(ProcessAccessFlags.All, false, process.Id);
                    }
                    catch (System.ComponentModel.Win32Exception)
                    {
                        Console.WriteLine($"Couldn't get handle to process: {process.Id} - System.ComponentModel.Win32Exception - Access Is Denied");
                        continue;
                    }
                    catch (System.InvalidOperationException)
                    {
                        Console.WriteLine($"Couldn't get handle to process {process.Id} - System.InvalidOperationException - Process has Exited");
                        continue;
                    }

                    // Get all threads under running process
                    ProcessThreadCollection threadCollection = process.Threads;

                    // Iterate over each thread under the process
                    foreach (ProcessThread thread in threadCollection)
                    {
                        // Get handle to the thread
                        IntPtr hThread = OpenThread(ThreadAccess.AllAccess, false, thread.Id);

                        // Create buffer to store pointer to the thread's base address - NTQueryInformationThread writes to this buffer
                        IntPtr buf = Marshal.AllocHGlobal(IntPtr.Size);

                        // Retrieve thread's Win32StartAddress - Different to thread.StartAddress
                        Int32 result = NtQueryInformationThread(hThread, ThreadInfoClreplaced.ThreadQuerySetWin32StartAddress, buf, IntPtr.Size, IntPtr.Zero);

                        if(result == 0)
                        {
                            // Need to Marshal Win32 type pointer from CLR type IntPtr to access the thread's base address via pointer
                            IntPtr threadBaseAddress = Marshal.ReadIntPtr(buf);

                            // Retrieve MEMORY_BASIC_INFORMATION struct for each thread - replacedumes 64bit processes, otherwise need to use MEMORY_BASIC_INFORMATION32
                            MEMORY_BASIC_INFORMATION64 memBasicInfo = new MEMORY_BASIC_INFORMATION64();
                            VirtualQueryEx(hProcess, threadBaseAddress, out memBasicInfo, (uint)Marshal.SizeOf(typeof(MEMORY_BASIC_INFORMATION64)));

                            // Check the State and Type fields for the thread's MEMORY_BASIC_INFORMATION
                            // Resolve to false suggests code running from this thread does not have a corresponding image file on disk, likely code injection
                            if (memBasicInfo.State == MemoryBasicInformationState.MEM_COMMIT && memBasicInfo.Type != MemoryBasicInformationType.MEM_IMAGE)
                            {
                                // Create new InjectedThread object and set initial variables
                                InjectedThread injectedThread = new InjectedThread()
                                {
                                    ProcessName = process.ProcessName,
                                    ProcessID = process.Id,
                                    ThreadId = thread.Id,
                                    BaseAddress = threadBaseAddress,
                                    Path = process.MainModule.FileName,
                                    Size = (int)memBasicInfo.RegionSize,
                                    CommandLine = GetProcessCommandLine(process),
                                    MemoryState = Enum.GetName(typeof(MemoryBasicInformationState), memBasicInfo.State),
                                    MemoryType = Enum.GetName(typeof(MemoryBasicInformationType), memBasicInfo.Type),
                                    MemoryProtection = Enum.GetName(typeof(MemoryBasicInformationProtection), memBasicInfo.Protect),
                                    AllocatedMemoryProtection = Enum.GetName(typeof(MemoryBasicInformationProtection), memBasicInfo.AllocationProtect),
                                    BasePriority = thread.BasePriority,
                                    ThreadStartTime = thread.StartTime
                                };

                                // Get handle to thread token. If Impersonation is not being used, thread will use Process access token
                                // Try OpenThreadToken() - if it fails, use OpenProcessToken()
                                if (OpenThreadToken(hThread, TokenAccessFlags.TOKEN_QUERY, false, out IntPtr hToken) == false)
                                {                                  
                                    // Thread doesn't have a unique token
                                    injectedThread.IsUniqueThreadToken = false;

                                    // Open process token instead
                                    if (OpenProcessToken(hProcess, TokenAccessFlags.TOKEN_QUERY, out hToken) == false)
                                    {
                                        Console.WriteLine($"Error opening thread and process token: {Marshal.GetLastWin32Error()}\nProcess ID {process.Id}");
                                    }
                                }
                                else
                                {
                                    injectedThread.IsUniqueThreadToken = true;
                                }

                                // Query process or thread token information
                                injectedThread.SecurityIdentifier = QueryToken(hToken, TOKEN_INFORMATION_CLreplaced.TokenUser);
                                injectedThread.Privileges = QueryToken(hToken, TOKEN_INFORMATION_CLreplaced.TokenPrivileges);
                                injectedThread.Integrity = QueryToken(hToken, TOKEN_INFORMATION_CLreplaced.TokenIntegrityLevel);
                                injectedThread.LogonId = QueryToken(hToken, TOKEN_INFORMATION_CLreplaced.TokenOrigin);
                                injectedThread.Username = GetProcessOwner(process.Id);

                                // Get logon session information and add it to the InjectedThread object
                                if (!string.IsNullOrEmpty(injectedThread.LogonId))
                                {
                                    GetLogonSessionData(hToken, injectedThread);
                                }

                                // Get thread's allocated memory via ReadProcessMemory
                                injectedThread.ThreadBytes = GetThreadMemoryBytes(hProcess, threadBaseAddress, injectedThread.Size);

                                // Read the full process memory ;
                                injectedThread.ProcessBytes = GetProcessMemoryBytes(hProcess);

                                // Read full name of executable image for the process
                                int capacity = 1024;
                                StringBuilder stringBuilder = new StringBuilder(capacity);
                                QueryFullProcessImageName(hProcess, 0, stringBuilder, ref capacity);
                                injectedThread.KernelPath = stringBuilder.ToString(0, capacity);

                                // Check whether the kernel image path matches Process.MainModule.Filename
                                if(injectedThread.Path.ToLower() != injectedThread.KernelPath.ToLower())
                                {
                                    injectedThread.PathMismatch = true;
                                }

                                injectedThreads.Add(injectedThread);
                                CloseHandle(hToken);
                            }

                            CloseHandle(hThread);
                        }
                    }

                    CloseHandle(hProcess);
                }
            }

            return injectedThreads;
        }

19 Source : ConsoleUI.cs
with MIT License
from Apr4h

private static void GetBeaconsFromFile(string fileName)
        {
            OutputMessageToConsole(LogLevel.Info, $"Scanning file: {fileName}");
            List<Beacon> beacons = new List<Beacon>();

            if (File.Exists(fileName))
            {
                // Check the size of the file. If > 500MB, and notify that scanning will take time
                var fileSize = new FileInfo(fileName).Length;
                if (fileSize > Int32.MaxValue)
                {
                    OutputMessageToConsole(LogLevel.Warn, $"\tFile is large: {fileSize / (1024 * 1024)} MB. Scanning will be slow.");
                }

                // Yara scan the file and return any matches
                List<BeaconMatch> beaconMatches = CobaltStrikeScan.YaraScanFile(fileName, opts.Verbose);

                // Extract config bytes at each match offset and parse the beacon config from them
                if (beaconMatches.Count > 0)
                {
                    if (opts.Verbose)
                    {
                        OutputMessageToConsole(LogLevel.Info, $"\t{beaconMatches.Count} Signature(s) detected in file. Attempting to extract and parse config...\n");
                    }
                    foreach (BeaconMatch match in beaconMatches)
                    {
                        try
                        {
                            byte[] beaconConfigBytes = new byte[4096];
                            // Get a byte array from the offset of the file with beacon matches to avoid cases
                            // where the file is too big to read in to a File object
                            using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                            {
                                fileStream.Seek((long)match.Offset, SeekOrigin.Begin);
                                fileStream.Read(beaconConfigBytes, 0, 4096);
                            }
                            match.Offset = 0;
                            beacons.Add(new Beacon(beaconConfigBytes, match.Offset, match.Version));
                        }
                        catch (System.IO.IOException)
                        {
                            /* 
                            if (opts.Verbose)
                            {
                                OutputMessageToConsole(LogLevel.Error, $"Error extracting signatured data from file at offset: {match.Offset}");
                            }
                            */
                        }
                    }

                    if (beacons.Count > 0)
                    {
                        foreach (Beacon beacon in beacons)
                        {
                            if (beacon.isValidBeacon())
                            {
                                OutputMessageToConsole(LogLevel.Success, $"Cobalt Strike Beacon Configuration\n");
                                beacon.OutputToConsole();
                            }
                        }
                    }
                    else
                        OutputBeaconNotFoundMessage();
                }
                else { OutputBeaconNotFoundMessage(); }
            }
            else
            {
                OutputMessageToConsole(LogLevel.Error, $"File doesn't exist: {fileName}\nExiting...");
                System.Environment.Exit(1);
            }        
        }

19 Source : MCMUISubModule.cs
with MIT License
from Aragas

private static void CheckLoadOrder()
        {
            var loadedModules = ModuleInfoHelper.GetLoadedModules().ToList();
            if (loadedModules.Count == 0) return;

            var sb = new StringBuilder();
            if (!ModuleInfoHelper.ValidateLoadOrder(typeof(MCMUISubModule), out var report))
            {
                sb.AppendLine(report);
                sb.AppendLine();
                sb.AppendLine(TextObjectHelper.Create(SMessageContinue)?.ToString() ?? "ERROR");
                switch (MessageBox.Show(sb.ToString(), TextObjectHelper.Create(SWarningreplacedle)?.ToString() ?? "ERROR", MessageBoxButtons.YesNo))
                {
                    case DialogResult.Yes:
                        Environment.Exit(1);
                        break;
                }
            }
        }

19 Source : Utilities.cs
with MIT License
from Arefu

public static void Log(string Message, Event LogLevel, bool ShouldQuit = false, int ExitCode = 0)
        {
            switch (LogLevel)
            {
                case Event.Warning:
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.Write("[Warning]: ");
                    Console.ResetColor();
                    break;

                case Event.Information:
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.Write("[Information]: ");
                    Console.ResetColor();
                    break;

                case Event.Error:
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.Write("[Error]: ");
                    Console.ResetColor();
                    break;

                case Event.Alert:
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.Write("[Information]: ");
                    Console.ResetColor();
                    break;

                case Event.Meta:
                    Console.ForegroundColor = ConsoleColor.DarkMagenta;
                    Console.Write("[Meta Information]: ");
                    Console.ResetColor();
                    break;

                default:
                    throw new ArgumentOutOfRangeException(nameof(LogLevel), LogLevel, null);
            }

            Console.WriteLine(Message);

            if (ShouldQuit)
                Environment.Exit(ExitCode);
        }

19 Source : Utilities.cs
with MIT License
from Arefu

public static List<string> ParseTocFile()
        {
            StreamReader Reader;
            var LocalVarFiles = new List<string>();
            try
            {
                Reader = new StreamReader($"{GetInstallDir()}\\YGO_DATA.TOC");
            }
            catch (Exception)
            {
                using (var Ofd = new OpenFileDialog())
                {
                    Ofd.replacedle = "Select YuGiOh.exe";
                    Ofd.Filter = "YuGiOh.exe | YuGiOh.exe";
                    var Result = Ofd.ShowDialog();
                    if (Result != DialogResult.OK) Environment.Exit(1);
                    Reader = new StreamReader(File.Open($"{new FileInfo(Ofd.FileName).DirectoryName}\\YGO_DATA.TOC",
                        FileMode.Open, FileAccess.Read));
                }
            }

            Reader.ReadLine(); //Dispose First Line.
            while (!Reader.EndOfStream)
            {
                var Line = Reader.ReadLine();
                if (Line == null) continue;

                Line = Line.TrimStart(' '); //Trim Starting Spaces.
                Line = Regex.Replace(Line, @"  +", " ", RegexOptions.Compiled); //Remove All Extra Spaces.
                var LineData = Line.Split(' '); //Split Into Chunks.
                LocalVarFiles.Add(LineData[2]); //Add To List For Manip.
            }

            return LocalVarFiles;
        }

19 Source : Cyclone.cs
with MIT License
from Arefu

[STAThread]
        private static void Main()
        {
            //Load ZIB.
            var ZibFolder = "";
            using (var Fbd = new FolderBrowserDialog())
            {
                Fbd.ShowNewFolderButton = false;
                Fbd.Description = "Select the ZIB folder.";
                Fbd.SelectedPath = Application.StartupPath;

                if (Fbd.ShowDialog() != DialogResult.OK)
                    Environment.Exit(1);
                else
                    ZibFolder = Fbd.SelectedPath;
            }

            switch (new DirectoryInfo(ZibFolder).Name.Replace(" Unpacked", string.Empty))
            {
                // PC version .zib files
                case "busts.zib":
                    Packer.Pack(ZibFolder, 0x2390);
                    break;
                case "cardcropHD400.jpg.zib":
                    Packer.Pack(ZibFolder);
                    break;
                case "cardcropHD401.jpg.zib":
                    Packer.Pack(ZibFolder);
                    break;
                case "decks.zib":
                    Packer.Pack(ZibFolder, 0x8650);
                    break;
                case "packs.zib":
                    Packer.Pack(ZibFolder, 0x750);
                    break;

                // switch version .zib files
                case "cardcropHD400.illust_a.jpg.zib":
                    Packer.Pack(ZibFolder, 0xE750);
                    break;
                case "cardcropHD400.illust_j.jpg.zib":
                    Packer.Pack(ZibFolder, 0x903D0);
                    break;
                default:
                    throw new Exception("This is either an unsupported ZIB");
            }
        }

19 Source : Program.cs
with MIT License
from Arefu

[STAThread]
        private static void Main()
        {
            Console.replacedle = "Lithe";
            var Credits = "";
            using (var Ofd = new OpenFileDialog())
            {
                Ofd.replacedle = "Select Credits To Encode/Decode";
                Ofd.Filter = "Credits file (*.dat, *.txt) | *.dat; *.txt";
                if (Ofd.ShowDialog() == DialogResult.OK)
                    Credits = Ofd.FileName;
                else
                    Environment.Exit(1);
            }

            if (Utilities.IsExt(Credits, ".dat"))
            {
                using (var Reader = new BinaryReader(File.Open(Credits, FileMode.Open, FileAccess.Read)))
                {
                    var CreditsContent = Reader.ReadBytes((int) new FileInfo(Credits).Length);
                    File.WriteAllText("credits.txt",
                        Encoding.Unicode.GetString(CreditsContent)
                            .Replace("?",
                                string.Empty)); //Two Start Characters Are A Magic Byte Letting The Game Know To In-Line Images
                    Utilities.Log("Finished Parsing.", Utilities.Event.Information);
                }
            }
            else
            {
                using (var Writer = new BinaryWriter(File.Open("credits.dat", FileMode.Append, FileAccess.Write)))
                {
                    using (var Reader =
                        new BinaryReader(File.Open("credits.txt", FileMode.OpenOrCreate, FileAccess.Read)))
                    {
                        var Content = Reader.ReadBytes((int) Reader.BaseStream.Length);
                        Writer.Write(new byte[] {0xFF, 0xFE});
                        foreach (var Char in Encoding.ASCII.GetString(Content))
                            switch (Char)
                            {
                                case '\r':
                                    Writer.Write(new byte[] {0x0D, 0x00});
                                    break;

                                case '\n':
                                    Writer.Write(new byte[] {0x0A, 0x00});
                                    break;

                                default:
                                    Writer.Write(new byte[] {Convert.ToByte(Char), 0x00});
                                    break;
                            }
                    }
                }

                Utilities.Log("Finished Encoding.", Utilities.Event.Information);
            }
        }

19 Source : Program.cs
with MIT License
from Arefu

[STAThread]
        private static void Main()
        {
            Console.replacedle = "Vortex";

            if (File.Exists("YGO_DATA.dat"))
                File.Delete("YGO_DATA.dat");
            if (File.Exists("YGO_DATA.toc"))
                File.Delete("YGO_DATA.toc");

            var YgoFolder = "";
            using (var Fbd = new FolderBrowserDialog())
            {
                Fbd.ShowNewFolderButton = false;
                Fbd.Description = "Select the YGO_DATA folder.";
                Fbd.SelectedPath = Application.StartupPath;

                if (Fbd.ShowDialog() != DialogResult.OK)
                    Environment.Exit(1);
                else
                    YgoFolder = Fbd.SelectedPath;
            }

            if (!YgoFolder.Contains("YGO_DATA"))
                throw new Exception("YGO_DATA Folder Not Found!");

            Files = Utilities.ParseTocFile();
            FilesToPack = Directory.GetFiles($"{YgoFolder}", "*.*", SearchOption.AllDirectories);

            File.AppendAllText("YGO_DATA.toc", "UT\n");

            using (var Writer = new BinaryWriter(File.Open("YGO_DATA.dat", FileMode.Append, FileAccess.Write)))
            {
                foreach (var Item in Files)
                {
                    var CurrentFileName = FilesToPack?.First(File => File.Contains(Item));

                    Utilities.Log($"Packing File: {CurrentFileName}.", Utilities.Event.Information);
                    var CurrentFileNameLength = Utilities.DecToHex(CurrentFileName
                        .Split(new[] {"YGO_DATA"}, StringSplitOptions.None).Last().TrimStart('\\').Length);
                    var CurrentFileSize = Utilities.DecToHex(new FileInfo($"{CurrentFileName}").Length);

                    while (CurrentFileSize.Length != 12)
                        CurrentFileSize = CurrentFileSize.Insert(0, " ");
                    while (CurrentFileNameLength.Length != 2)
                        CurrentFileNameLength = CurrentFileNameLength.Insert(0, " ");

                    var Reader = new BinaryReader(File.Open(CurrentFileName, FileMode.Open, FileAccess.Read));
                    var NewSize = new FileInfo(CurrentFileName).Length;
                    while (NewSize % 4 != 0)
                        NewSize = NewSize + 1;

                    var BufferSize = NewSize - new FileInfo(CurrentFileName).Length;
                    Writer.Write(Reader.ReadBytes((int) new FileInfo(CurrentFileName).Length));

                    if (BufferSize > 0)
                        while (BufferSize != 0)
                        {
                            Writer.Write(new byte[] {00});
                            BufferSize = BufferSize - 1;
                        }

                    File.AppendAllText("YGO_DATA.toc",
                        $"{CurrentFileSize} {CurrentFileNameLength} {CurrentFileName.Split(new[] {"YGO_DATA\\"}, StringSplitOptions.None).Last()}\n");
                }
            }

            Utilities.Log("Finished Packing Files.", Utilities.Event.Information);
        }

19 Source : Form1.cs
with MIT License
from Arefu

private void OpenToolStripMenuItem_Click(object Sender, EventArgs Args)
        {
            if (FileQuickViewList.Nodes.Count != 0) return;

            Reader?.Close();
            try
            {
                InstallDir = Utilities.GetInstallDir();
                Reader = new StreamReader(File.Open($"{InstallDir}\\YGO_DATA.TOC", FileMode.Open, FileAccess.Read));
            }
            catch
            {
                var Reply = MessageBox.Show(this, "Do You Want To Locate Game?", "Game Not Fuond!",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk);
                if (Reply == DialogResult.No) Environment.Exit(1);
                else
                    using (var Ofd = new OpenFileDialog())
                    {
                        Ofd.replacedle = "Select YuGiOh.exe";
                        Ofd.Filter = "YuGiOh.exe | YuGiOh.exe";
                        var Result = Ofd.ShowDialog();
                        if (Result != DialogResult.OK) Environment.Exit(1);
                        Reader = new StreamReader(File.Open($"{new FileInfo(Ofd.FileName).DirectoryName}\\YGO_DATA.TOC",
                            FileMode.Open, FileAccess.Read));
                        InstallDir = new FileInfo(Ofd.FileName).DirectoryName;
                    }
            }

            Reader.ReadLine();

            GameLocLabel.ForeColor = Color.Green;
            GameLocLabel.Text = "Game Loaded";

            var RootNode = new TreeNode("YGO_DATA");
            FileQuickViewList.Nodes.Add(RootNode);
            while (!Reader.EndOfStream)
            {
                var Line = Reader.ReadLine();
                if (Line == null) continue;
                Line = Line.TrimStart(' ');
                Line = Regex.Replace(Line, @"  +", " ", RegexOptions.Compiled);
                var LineData = Line.Split(' ');
                Data.Add(new FileData(Utilities.HexToDec(LineData[0]), Utilities.HexToDec(LineData[1]), LineData[2]));
                LineData[2].Split('\\').Aggregate(RootNode,
                    (Current, File) => Current.Nodes.ContainsKey(File)
                        ? Current.Nodes[File]
                        : Current.Nodes.Add(File, File));
            }

            Reader?.Close();
            GiveIcons(FileQuickViewList.Nodes[0]);
            FileQuickViewList.Nodes[0].Expand();
            FileQuickViewList.SelectedNode = FileQuickViewList.Nodes[0];
            FileQuickViewList_NodeMouseClick(new object(),
                new TreeNodeMouseClickEventArgs(FileQuickViewList.Nodes[0], MouseButtons.Left, 1, 0, 0));
        }

19 Source : Program.cs
with MIT License
from Arefu

[STAThread]
        private static void Main()
        {
            Console.replacedle = "Embargo";

            using (var Ofd = new OpenFileDialog())
            {
                Ofd.replacedle = "Select DLL To Inject";
                Ofd.Filter = "Language file (*.dll) | *.dll";
                if (Ofd.ShowDialog() != DialogResult.OK)
                    Environment.Exit(1);

                var ResultStatus = Injector.Inject("YuGiOh", Ofd.FileName);
                if (ResultStatus != InjectionStatus.Success)
                    MessageBox.Show("Error Status: " + ResultStatus, "Error During Inject!", MessageBoxButtons.OK,
                        MessageBoxIcon.Error);
            }
        }

19 Source : Entrypoint.cs
with MIT License
from Arkhist

[MethodImpl(MethodImplOptions.NoInlining)]
        internal static void Load()
        {
            try
            {
                Paths.SetExecutablePath(typeof(HN.Program).replacedembly.GetName().Name);

                Logger.Listeners.Add(new ConsoleLogger());
                AccessTools.PropertySetter(typeof(TraceLogSource), nameof(TraceLogSource.IsListening)).Invoke(null, new object[] { true });
                ConsoleManager.Initialize(true);

                // Start chainloader for plugins
                var chainloader = new HacknetChainloader();
                chainloader.Initialize();
                chainloader.Execute();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Fatal loading exception:");
                Console.WriteLine(ex);
                Console.ReadLine();
                Environment.Exit(1);
            }
        }

19 Source : PathfinderUpdaterPlugin.cs
with MIT License
from Arkhist

internal static void OnDrawMainMenu(MainMenuEvent args)
        {
            if (PathfinderUpdaterPlugin.VersionToRequest == null)
                return;
            
            GuiData.spriteBatch.Draw(Utils.white, new Rectangle(0, 0, GuiData.spriteBatch.GraphicsDevice.Viewport.Width, GuiData.spriteBatch.GraphicsDevice.Viewport.Height), new Color(0, 0, 0, 0.65f));
            GuiData.spriteBatch.Draw(Utils.white, new Rectangle(700, 250, 500, 300), Color.Black);
            Texreplacedem.doLabel(new Vector2(750, 260), $"New Pathfinder Version {PathfinderUpdaterPlugin.VersionToRequest}", Color.White);
            Texreplacedem.doSmallLabel(new Vector2(750, 300), "Do you want to update? Yes will close the game.", Color.White);
            if (AcceptVersion.Do())
            {
                PathfinderUpdaterPlugin.AcceptedUpdate.Value = PathfinderUpdaterPlugin.VersionToRequest.ToString();
                Environment.Exit(0);
            }
            else if (DenyVersion.Do())
            {
                PathfinderUpdaterPlugin.VersionToRequest = null;
                EventManager<DrawMainMenuEvent>.RemoveHandler(OnDrawMainMenu);
            }
            else if (SkipVersion.Do())
            {
                PathfinderUpdaterPlugin.CurrentVersion.Value = PathfinderUpdaterPlugin.VersionToRequest.ToString();
                PathfinderUpdaterPlugin.VersionToRequest = null;
                EventManager<DrawMainMenuEvent>.RemoveHandler(OnDrawMainMenu);
            }
        }

19 Source : App.xaml.cs
with GNU General Public License v3.0
from armandoalonso

private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            e.Handled = true;
            if (!ApplicationError)
            {
                //create log
                var sb = new StringBuilder();

                sb.AppendLine("There was an unhandled error in the application. see logs below => ");
                sb.AppendLine($"ERROR MESSAGE => {e.Exception.Message}");
                sb.AppendLine($"ERROR TRACE => {e.Exception.StackTrace}");
                sb.AppendLine($"ERROR INNER EX => {e.Exception.InnerException}");
                sb.AppendLine($"ERROR SOURCE => {e.Exception.Source}");

                sb.AppendLine();
                sb.AppendLine("EXCEPTION LIST =>");

                foreach (var exception in LogManager.Exceptions)
                {
                    sb.AppendLine("\n===============================================================\n");
                    sb.AppendLine($"ERROR MESSAGE => {exception.Message}");
                    sb.AppendLine($"ERROR TRACE => {exception.StackTrace}");
                    sb.AppendLine($"ERROR INNER EX => {exception.InnerException}");
                    sb.AppendLine($"ERROR SOURCE => {exception.Source}");
                    sb.AppendLine("\n===============================================================\n");
                }

                var logFile = Path.Combine( OptionsManager.CurrentOptions.DataPath, $"app_log.txt");
                ProcessHelper.Insatnce.WriteFile(logFile, sb.ToString());
                ProcessHelper.Insatnce.StartProcess(logFile);
            }

            Environment.Exit(0);

        }

19 Source : Utils.cs
with MIT License
from arsium

public static void OneInstance()
        {
            MT = new Mutex(true, MUTEX, out OW);
            if (!OW)
            {
                Environment.Exit(0);
            }
        }

19 Source : OneMiner.cs
with GNU General Public License v3.0
from arunsatyarth

public void CloseApp()
        {
            m_keepRunning = false;
            Environment.Exit(0);
            
        }

19 Source : Program.cs
with Apache License 2.0
from aryice

static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();
            int readvalue = 0;
            Console.WriteLine("当前时间:" + DateTime.Now);
            while (true)
            {
                Console.WriteLine("请输入操作选项:获取所有记录数(1),根据条件查询(2),数据写入(3),分离数据库(4),附加数据库(5),表添加索引(6),表删除索引(7),服务器缓存清除(9),检查服务器连接(11),检查数据库连接(12),检查表连接(13),删除记录(14),修改记录(15),清空某一数据结构存储(16),退出(q)");
                string getread = Console.ReadLine();
                if (getread.ToLower().Trim() == "q")
                {
                    System.Environment.Exit(0); 
                }
                readvalue = CommonHelper.ToInt(getread);
                sw.Restart();
                switch (readvalue)
                {
                    case 1: TestDB.getrowallcount(); break;
                    case 2: TestDB.getlistcondition(); break;
                    case 3: TestDB.addrow(); break;
                    case 4: TestDB.databasedetach(); break;
                    case 5: TestDB.databaseattach(); break;
                    case 6: TestDB.tableindexadd(); break;
                    case 7: TestDB.tableindexdel(); break;
                    case 9: TestDB.servercacheclear(); break;
                    case 11: TestDB.serverconnectioncheck(); break;
                    case 12: TestDB.databaseexistsall(); break;
                    case 13: TestDB.tableexistsall(); break;
                    case 14: TestDB.delete(); break;
                    case 15: TestDB.update(); break;
                    case 16: TestDB.sqlbaseclear(); break;
                }
                sw.Stop();
                Console.WriteLine(" 执行时间:" + sw.ElapsedMilliseconds+"毫秒");
            }

            Console.WriteLine("当前时间:"+DateTime.Now);
            Console.ReadKey();
        }

19 Source : Program.cs
with GNU General Public License v3.0
from ASCOMInitiative

static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
        {
            Version replacedemblyVersion = replacedembly.GetExecutingreplacedembly().GetName().Version;

            // Create a trace logger and log the exception 
            TraceLogger TL = new TraceLogger("DynamicClientThreadException")
            {
                Enabled = true
            };
            TL.LogMessage("Main", string.Format("ASCOM Remote Dynamic Client Manager - Thread exception. Version: {0}", replacedemblyVersion.ToString()));
            TL.LogMessageCrLf("Main", e.Exception.ToString());

            // Display the exception in the default .txt editor and exit
            Process.Start(TL.LogFileName);

            TL.Enabled = false;
            TL.Dispose();
            TL = null;

            Environment.Exit(0);
        }

19 Source : Program.cs
with GNU General Public License v3.0
from ASCOMInitiative

static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception exception = (Exception)e.ExceptionObject;
            TraceLogger TL = new TraceLogger("RemoteAccessServerException")
            {
                Enabled = true
            };
            TL.LogMessageCrLf("Main", "Unhandled exception: " + exception.ToString());
            Process.Start(TL.LogFileName);
            TL.Enabled = false;
            TL.Dispose();
            Environment.Exit(0);
        }

19 Source : Program.cs
with GNU General Public License v3.0
from ASCOMInitiative

private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception exception = (Exception)e.ExceptionObject;
            TraceLogger TL = new TraceLogger("SetNetworkPemissionsException")
            {
                Enabled = true
            };

            TL.LogMessageCrLf("Main", "Unhandled exception: " + exception.ToString());
            TL.Enabled = false;
            TL.Dispose();
            Environment.Exit(0);
        }

19 Source : Program.cs
with GNU General Public License v3.0
from ASCOMInitiative

static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception exception = (Exception)e.ExceptionObject;

            Version replacedemblyVersion = replacedembly.GetExecutingreplacedembly().GetName().Version;

            // Create a trace logger and log the exception 
            TraceLogger TL = new TraceLogger("DynamicClientUnhandledException")
            {
                Enabled = true
            };
            TL.LogMessage("Main", string.Format("ASCOM Remote Dynamic Client Manager - Unhandled exception. Version: {0}", replacedemblyVersion.ToString()));
            TL.LogMessageCrLf("Main", exception.ToString());

            // Display the exception in the default .txt editor and exit
            Process.Start(TL.LogFileName);

            TL.Enabled = false;
            TL.Dispose();
            TL = null;

            Environment.Exit(0);
        }

19 Source : Program.cs
with GNU General Public License v3.0
from ASCOMInitiative

static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
        {
            TraceLogger TL = new TraceLogger("RemoteAccessServerException")
            {
                Enabled = true
            };
            TL.LogMessageCrLf("Main", "Thread exception: " + e.Exception.ToString());
            Process.Start(TL.LogFileName);

            TL.Enabled = false;
            TL.Dispose();

            //MessageBox.Show(e.Exception.Message, "Unhandled Thread Exception, see RemoteAccessServerException log for details.");
            Environment.Exit(0);
        }

19 Source : AddInActivatorHost.cs
with MIT License
from askguanyu

public static void Run(string[] args)
        {
            //// args[0] = AddInDomain replacedembly path
            //// args[1] = GUID
            //// args[2] = PID
            //// args[3] = AddInDomainSetup file
            //// args[4] = Redirect output or not

            if (args.Length < 4)
            {
                return;
            }

            string friendlyName = Path.GetFileNameWithoutExtension(replacedembly.GetEntryreplacedembly().Location);
            string guid = args[1];
            int processId = int.Parse(args[2]);
            AddInDomainSetup addInDomainSetup = AddInDomainSetup.ReadSetupFile(args[3]);
            AppDomain appDomain = AppDomain.CreateDomain(friendlyName, addInDomainSetup.Evidence, addInDomainSetup.AppDomainSetup);
            Type type = replacedembly.GetEntryreplacedembly().GetType("DevLib.AddIn.replacedemblyResolver");

            if (type == null)
            {
                throw new TypeLoadException(AddInConstants.replacedemblyResolverException);
            }

            // add AddInDomain replacedembly to resolver
            if (addInDomainSetup.Externalreplacedemblies == null)
            {
                addInDomainSetup.Externalreplacedemblies = new Dictionary<replacedemblyName, string>();
            }

            addInDomainSetup.Externalreplacedemblies[typeof(AddInActivatorHost).replacedembly.GetName()] = typeof(AddInActivatorHost).replacedembly.Location;

            object resolver = appDomain.CreateInstanceFromAndUnwrap(
                                        type.replacedembly.Location,
                                        type.FullName,
                                        false,
                                        BindingFlags.CreateInstance | BindingFlags.Public | BindingFlags.Instance,
                                        null,
                                        new[] { addInDomainSetup.Externalreplacedemblies },
                                        null,
                                        null,
                                        null);

            type.InvokeMember("Mount", BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public, null, resolver, null);

            AddInActivatorHost host = (AddInActivatorHost)appDomain.CreateInstanceFromAndUnwrap(
                                                                    typeof(AddInActivatorHost).replacedembly.Location,
                                                                    typeof(AddInActivatorHost).FullName,
                                                                    false,
                                                                    BindingFlags.CreateInstance | BindingFlags.Public | BindingFlags.Instance,
                                                                    null,
                                                                    new object[] { guid, processId, addInDomainSetup },
                                                                    null,
                                                                    null,
                                                                    null);

            host.WaitForExit();

            type.InvokeMember("Unmount", BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public, null, resolver, null);

            // if parent process (host) finishes, the current process must end
            Environment.Exit(0);
        }

See More Examples