private void RefreshProcessList() { try { RefreshButton.Enabled = false; if (Process.GetProcessesByName("WoW-64").Length > 0) { MessageBox.Show(nManager.Translate.Get(nManager.Translate.Id.WoW_Client_64bit), nManager.Translate.Get(nManager.Translate.Id.Title_WoW_Client_64bit), MessageBoxButtons.OK, MessageBoxIcon.Warning); } SessionList.Items.Clear(); SessionList.SelectedIndex = -1; var usedProcess = new List <string>(); var listWowProcess = new List <string> { "Wow", "WowT", "WowB", "WowTR" }; foreach (string s in listWowProcess) { Application.DoEvents(); for (int i = nManager.Wow.MemoryClass.Process.ListeProcessIdByName(s).Length - 1; i >= 0; i--) { Application.DoEvents(); if (SessionList.SelectedIndex == -1 && !Hook.WowIsUsed(nManager.Wow.MemoryClass.Process.ListeProcessIdByName(s)[i].Id)) { SessionList.Items.Add(nManager.Wow.MemoryClass.Process.ListeProcessIdByName(s)[i].Id + " - " + Hook.PlayerName(nManager.Wow.MemoryClass.Process.ListeProcessIdByName(s)[i].Id)); SessionList.SelectedIndex = 0; } else { string used = ""; if (Hook.WowIsUsed(nManager.Wow.MemoryClass.Process.ListeProcessIdByName(s)[i].Id)) { used = " - " + nManager.Translate.Get(nManager.Translate.Id.In_use) + "."; } usedProcess.Add(nManager.Wow.MemoryClass.Process.ListeProcessIdByName(s)[i].Id + " - " + Hook.PlayerName(nManager.Wow.MemoryClass.Process.ListeProcessIdByName(s)[i].Id) + used); } } } foreach (string v in usedProcess) { Application.DoEvents(); SessionList.Items.Add(v); } if (SessionList.Items.Count == 0) { SessionList.Items.Add(nManager.Translate.Get(nManager.Translate.Id.Please_connect_to_the_game)); } RefreshButton.Enabled = true; } catch (Exception ex) { Logging.WriteError("RefreshProcessList(): " + ex); RefreshButton.Enabled = true; } }
private void CloseAllInstancesOf(string p) { try { foreach (Process proc in Process.GetProcessesByName(p)) { proc.Kill(); } System.Threading.Thread.Sleep(500); } catch (Exception ex) { if (ex is InvalidOperationException) { return; // the process is already exited } if (ex is System.ComponentModel.Win32Exception) { Debug.WriteLog(ex); Debug.WriteLog("The process is terminating / could not be terminated"); return; } Debug.WriteLog(ex); throw; } }
public static async Task KillExplorer() { //return; //TEST RegistryKey ourKey = null; try { ourKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon", true); ourKey?.SetValue("AutoRestartShell", 0); } catch (Exception ex) { ex.Log("Ошибка при попытке влезть в реестр и убить explorer"); } var explorer = ProcessSD.GetProcessesByName("explorer"); await Task.Delay(500); foreach (var item in explorer) { Ex.Try(() => { item.Kill(); item.WaitForExit(); }); } //await Task.Delay(1000); //ourKey?.SetValue("AutoRestartShell", 1); }
private static Process FindOrCreateProcess(string application, IEnumerable <string> args, bool suspended) { var processes = Process.GetProcessesByName(application); if (processes.Length > 0) { return(processes[0]); } var startupInfo = new StartupInfo(); var arguments = args.Select(arg => arg.Contains(" ") ? $"\"{arg}\"" : arg); Kernel32.CreateProcess( $"{application}.exe", $"{application}.exe {string.Join(" ", arguments)}", IntPtr.Zero, IntPtr.Zero, false, suspended ? ProcessCreationFlags.CreateSuspended : ProcessCreationFlags.None, IntPtr.Zero, null, ref startupInfo, out var processInformation ); return(Process.GetProcessById(processInformation.dwProcessId)); }
/// <summary> /// Creates an instance of ReloadedProcess from a supplied process name. /// </summary> /// <param name="processName">The process name to find obtain Reloaded process from.</param> public static ReloadedProcess GetProcessByName(string processName) { try { // Create new ReloadedProcess ReloadedProcess reloadedProcess = new ReloadedProcess(); // Get Process by Name var process = SystemProcess.GetProcessesByName(processName)[0]; // Set Process ID reloadedProcess.ProcessId = (IntPtr)process.Id; // Get Process Handle reloadedProcess.ProcessHandle = Native.Native.OpenProcess(Native.Native.PROCESS_ALL_ACCESS, false, (int)reloadedProcess.ProcessId); // Set thread id and handle to be that of first thread. reloadedProcess.ThreadId = (IntPtr)process.Threads[0].Id; // Set thread handle to be that of the first thread. reloadedProcess.ThreadHandle = Native.Native.OpenThread(Native.Native.THREAD_ALL_ACCESS, false, (int)reloadedProcess.ThreadId); // Retrun Reloaded Process return(reloadedProcess); } catch { return(null); } }
public static void AttachVisualStudioToProcess(_DTE instanceSolution, string ProcessName) { Process[] prss = Process.GetProcessesByName(ProcessName); if (prss.Length <= 0) { MessageBox.Show("Failed to find w3wp.exe process! Make sure you opened the page first!", "Quick Attach", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } DTEProcess processToAttachTo = instanceSolution.Debugger.LocalProcesses.Cast <DTEProcess>().FirstOrDefault(process => process.ProcessID == prss[0].Id); try { if (processToAttachTo != null) { processToAttachTo.Attach(); } else { MessageBox.Show("Failed to attach process to solution!", "Quick Attach", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } catch (SecurityException) { MessageBox.Show("Admin Permissions are required to attach the process", "Quick Attach", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } }
public static async Task StartMEAsync() { if (!Process.GetProcessesByName("Xpand.XAF.ModelEditor.Win").Any()) { var readyFile = $"{MESettingsPath}\\Xpand.XAF.ModelEditor.Win\\Ready.txt"; if (File.Exists(readyFile)) { File.Delete(readyFile); } var readyPath = $"{Path.GetDirectoryName(readyFile)}\\Ready.txt"; if (File.Exists(readyPath)) { File.Delete(readyPath); Thread.Sleep(200); } var watcher = new FileSystemWatcher(Path.GetDirectoryName(readyPath) !); watcher.EnableRaisingEvents = true; var tsc = new TaskCompletionSource <bool>(); void CreatedHandler(object s, FileSystemEventArgs e) { if (e.Name == Path.GetFileName(readyPath)) { tsc.SetResult(true); watcher.Created -= CreatedHandler; } } watcher.Created += CreatedHandler; Process.Start($"{MESettingsPath}\\Xpand.XAF.ModelEditor.Win\\Xpand.XAF.ModelEditor.Win.exe"); await tsc.Task; } }
private static bool IsRunning(string processName) { if (processName == SRANIPAL) { return(false); } else { return(Process.GetProcessesByName(processName).Length > 0); } }
private void EndToEndTest( string templateName, string moduleName, string textInResponse, string pythonVersion, string packageName = null ) { EndToEndLog("Starting {0} {1}", templateName, pythonVersion); using (var app = new VisualStudioApp()) { var pyProj = app.CreateProject( PythonVisualStudioApp.TemplateLanguageName, templateName, TestData.GetTempPath(), TestContext.TestName ).GetPythonProject(); EndToEndLog("Created project {0}", pyProj.ProjectFile); Assert.IsInstanceOfType(pyProj.GetLauncher(), typeof(PythonWebLauncher)); var factory = CreateVirtualEnvironment(pythonVersion, app, pyProj); EndToEndLog("Created virtual environment {0}", factory.Description); InstallWebFramework(app, moduleName, packageName ?? moduleName, factory); EndToEndLog("Installed framework {0}", moduleName); // Abort analysis so we don't have too many python.exe processes // floating around. foreach (var p in Process.GetProcessesByName("Microsoft.PythonTools.Analyzer")) { p.Kill(); } EndToEndLog("Aborted analysis"); app.ServiceProvider.GetUIThread().Invoke(() => { pyProj.SetProjectProperty("WebBrowserPort", "23457"); }); EndToEndLog("Set WebBrowserPort to 23457"); LaunchAndVerifyNoDebug(app, 23457, textInResponse); EndToEndLog("Verified without debugging"); app.ServiceProvider.GetUIThread().Invoke(() => { pyProj.SetProjectProperty("WebBrowserPort", "23456"); }); EndToEndLog("Set WebBrowserPort to 23456"); LaunchAndVerifyDebug(app, 23456, textInResponse); EndToEndLog("Verified with debugging"); } }
public static SystemProcess FromName(string name) { var firstOrDefault = SystemProcess.GetProcessesByName(name); var process = firstOrDefault.FirstOrDefault(); if (process == null) { throw new ArgumentNullException(nameof(process)); } return(process); }
/// <summary> /// Gets the first process found matching the process name. /// </summary> /// <param name="processName">Name of the process.</param> /// <returns>IntPtr.</returns> /// <exception cref="ArgumentNullException"></exception> public static IntPtr GetMainWindowHandle(string processName) { var firstOrDefault = SystemProcess.GetProcessesByName(processName); var process = firstOrDefault.FirstOrDefault(); if (process == null) { throw new ArgumentNullException(nameof(process)); } return(process.MainWindowHandle); }
/// <summary> /// Ensures that jsreport server is running for current project /// </summary> public RemoteTask <int> EnsureStartedAsync() { if (_isRunning && Process.GetProcessesByName("node").Any(p => GetMainModuleFilePath(p.Id).Contains(_currentShadowBinFolder))) { return(RemoteTask.ServerStart((cts) => Task.FromResult(1))); } _isRunning = true; return(RemoteTask.ServerStart <int>(async cts => { await StartAsync().ConfigureAwait(false); return 0; })); }
private static DTE GetDebuggerHostDte() { var currentProcessId = Process.GetCurrentProcess().Id; foreach (var process in Process.GetProcessesByName("devenv")) { var dte = IntegrationHelper.TryLocateDteForProcess(process); if (dte?.Debugger?.DebuggedProcesses?.OfType <EnvDTE.Process>().Any(p => p.ProcessID == currentProcessId) ?? false) { return(dte); } } return(null); }
/// <summary>Determines whether this instance this instance can be started.</summary> /// <returns><c>true</c> if this instance can be started; otherwise <c>false</c>.</returns> private static bool CanStartThisInstance() { // check for the "newinstance" argument var forceNewInstance = false; foreach (var arg in Program.Arguments) { if (arg == ValidArgs.NewInstance) { forceNewInstance = true; } else if (arg.StartsWith(ValidArgs.ParentProcId)) { var id = int.Parse(arg.Replace(ValidArgs.ParentProcId, "").Trim()); _parentProc = Process.GetProcessById(id); _isChildProc = true; } } if (forceNewInstance) { return(true); // force starting process } // check for a previous instance var appExeFile = new System.IO.FileInfo(AppPath).Name; appExeFile = appExeFile.Remove(appExeFile.LastIndexOf('.')); // remove the extension var procs = Process.GetProcessesByName(appExeFile); var thisProc = Process.GetCurrentProcess(); debuggerAttached = System.Diagnostics.Debugger.IsAttached; /* * Conditions for starting this instance: * 1. This is the only process * 2. More than one process and one of the existing processes is this one's parent * 3. A debugger is attached to this process */ return((procs.Length == 1 && procs[0].Id == thisProc.Id) || // condition 1 (procs.Length > 1 && _parentProc != null && procs.Select(p => p.Id).Contains(_parentProc.Id)) || // condition 2 debuggerAttached); // condition 3 }
public IProcess[] GetProcessesByName(string processName) { NativeProcess[] processes; try { processes = NativeProcess.GetProcessesByName(processName); } catch { return(new Process[] { }); } return(processes.Select(x => new Process { Id = x.Id, MainWindowTitle = x.MainWindowTitle, ProcessName = x.ProcessName }).ToArray()); }
private IEnumerable <Process> EnumerateVisualStudioProcesses() { var process = Process.GetCurrentProcess(); if (process.ProcessName.ToLower().Contains(_visualStudioProcessName)) { // We're being compiled directly by Visual Studio yield return(process); } // We're being compiled by other tool (e.g. MSBuild) called from a Visual Studio instance // therefore, some Visual Studio instance is our parent process. // Because of nodeReuse, we can't guarantee that the parent process of our current process is the "right" Visual Studio // so we just have to go through them all, and try to find our project in one of the Visual Studio's that are open foreach (var visualStudioProcess in Process.GetProcessesByName(_visualStudioProcessName)) { yield return(visualStudioProcess); } }
public static void Init(string[] args) { AppDomain.CurrentDomain.UnhandledException += (object sender, UnhandledExceptionEventArgs e) => { ShowError(e.ExceptionObject as Exception); }; //check single open bool single; if (bool.TryParse(ConfigurationManager.AppSettings["single"], out single) && single) { var procName = Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().Location); var procList = Process.GetProcessesByName(procName); if (procList.Length > 1) { return; } } try { Application.Init(); UnhandledExceptionHandler h = new UnhandledExceptionHandler(OnError); ExceptionManager.UnhandledException += h; mainForm = new MainForm(); bool autoopen; if (bool.TryParse(ConfigurationManager.AppSettings["autoopen"], out autoopen) && autoopen) { mainForm.OnRecentProject(mainForm, EventArgs.Empty); } Application.Run(); } catch (Exception ex) { ShowError(ex); } }
private static int ExtractME() { if (!Directory.Exists(MESettingsPath)) { Directory.CreateDirectory(MESettingsPath); } var assembly = typeof(XpandModelEditor).Assembly; using var memoryStream = new MemoryStream(); var resourceName = assembly.GetManifestResourceNames().First(s => s.EndsWith(".zip")); var resourceStream = assembly.GetManifestResourceStream(resourceName) ?? throw new InvalidOperationException("packageVersion"); var fileName = Path.GetFileNameWithoutExtension(resourceName); var version = Regex.Match(fileName, @"\.[\d]*\.[\d]*\.[\d]*\.[\d]*").Value.Trim('.'); var zipPath = $"{MESettingsPath}\\Xpand.XAF.ModelEditor.Win.{version}.zip"; if (!File.Exists(zipPath)) { SaveToFile(resourceStream, zipPath); var meDir = $"{MESettingsPath}\\Xpand.XAF.ModelEditor.Win"; if (Directory.Exists(meDir)) { foreach (var process in Directory.GetFiles(meDir, "*.exe") .SelectMany(s => Process.GetProcessesByName(Path.GetFileNameWithoutExtension(s)))) { process.Kill(); Thread.Sleep(300); } Directory.Delete(meDir, true); } Directory.CreateDirectory(meDir); ZipFile.ExtractToDirectory(zipPath, meDir); return(1); } return(0); }
private void HandleVisualStudioShutDown() { try { Log.Write("OnBeginShutdown"); _mPackageDteEvents.OnBeginShutdown -= HandleVisualStudioShutDown; _dteEvents = null; _mPackageDteEvents = null; //Check if there's only one instance of VS running. if it's so then remove from Microsoft.Common.Target //Any reference of LINQBridgeVs if (Process.GetProcessesByName(VisualStudioProcessName).Length > 1) { return; } //This simulate an uninstall. if it's the last instance of VS running disable LINQBridgeVs PackageConfigurator.IsLinqBridgeEnabled = false; } catch (Exception e) { Log.Write(e, "OnBeginShutdown Error..."); } }
void Kill(string processName) { Proc[] procs = Proc.GetProcessesByName(processName); foreach (var p in procs) { try { if (!p.HasExited) { p.Kill(); p.WaitForExit(); } } catch (Exception ex) { logger.Debug("Unable to kill process '{0}' (pid: {2}). {1}", processName, p.Id, ex.Message); } finally { p.Close(); } } }
/// <summary> /// Gets the DTE object from any devenv process. /// </summary> /// <returns> /// Retrieved DTE object or /// <see langword="null"> /// if not found. /// </see> /// </returns> private static DTE GetDte() { object runningObject = null; IBindCtx bindCtx = null; IRunningObjectTable rot = null; IEnumMoniker enumMonikers = null; try { Process process = Process.GetProcessesByName("devenv").SingleOrDefault(); Marshal.ThrowExceptionForHR(CreateBindCtx(0, out bindCtx)); bindCtx.GetRunningObjectTable(out rot); rot.EnumRunning(out enumMonikers); IMoniker[] moniker = new IMoniker[1]; IntPtr numberFetched = IntPtr.Zero; while (enumMonikers.Next(1, moniker, numberFetched) == 0) { IMoniker runningObjectMoniker = moniker[0]; string name = null; try { runningObjectMoniker?.GetDisplayName(bindCtx, null, out name); } catch (UnauthorizedAccessException) { // Do nothing, there is something in the ROT that we do not have access to. } Regex monikerRegex = new Regex(@"!VisualStudio.DTE\.\d+\.\d+\:" + process.Id, RegexOptions.IgnoreCase); if (!string.IsNullOrEmpty(name) && monikerRegex.IsMatch(name)) { Marshal.ThrowExceptionForHR(rot.GetObject(runningObjectMoniker, out runningObject)); break; } } } finally { if (enumMonikers != null) { Marshal.ReleaseComObject(enumMonikers); } if (rot != null) { Marshal.ReleaseComObject(rot); } if (bindCtx != null) { Marshal.ReleaseComObject(bindCtx); } } return(runningObject as DTE); }
static void Main(string[] args) { string strName = DateTime.Now.ToString("yyyyMMddhhmmss"); string filePath = @"E:\" + strName + @".txt"; StreamWriter writer = new StreamWriter(filePath); Process[] processArray = Process.GetProcesses(); writer.WriteLine("----" + "进程数目:" + processArray.Length + "----"); writer.WriteLine(Environment.NewLine); Console.WriteLine("----" + "进程数目:" + processArray.Length + "----"); /* * string processName = processArray[0].ProcessName; * string userName = GetProcessUserName(processArray[0].Id); * * Console.WriteLine("进程名称:"+processName); * Console.WriteLine("用户名"+userName); * * //Path * Process[] processArray1 = Process.GetProcessesByName(processName);//数组长度为1 * //Console.WriteLine("数组长度:"+processArray1.Length); * for (int i = 0; i < processArray1.Length; i++) { * // Console.WriteLine("1 "+processArray1[i]); * // Console.WriteLine("2 " + processArray1[i].MainModule); * * Console.WriteLine("路径 "+processArray1[i].MainModule.FileName);//包含exe文件 * } * string path = System.IO.Path.GetDirectoryName(Process.GetProcessesByName(processName)[0].MainModule.FileName); * System.Diagnostics.FileVersionInfo info = System.Diagnostics.FileVersionInfo.GetVersionInfo(processArray1[0].MainModule.FileName); */ // Console.WriteLine("文件名称=" + info.FileName); // Console.WriteLine("产品名称=" + info.ProductName); // Console.WriteLine("公司名称=" + info.CompanyName); // Console.WriteLine("文件版本=" + info.FileVersion); // Console.WriteLine("产品版本=" + info.ProductVersion); // 通常版本号显示为「主版本号.次版本号.生成号.专用部件号」 // Console.WriteLine("系统显示文件版本:" + info.ProductMajorPart + '.' + info.ProductMinorPart + '.' + info.ProductBuildPart + '.' + info.ProductPrivatePart); //Console.WriteLine("描述:" + info.FileDescription); //Console.WriteLine("文件语言=" + info.Language); //Console.WriteLine("原始文件名称=" + info.OriginalFilename); //Console.WriteLine("文件版权=" + info.LegalCopyright); //Console.WriteLine("文件大小=" + System.Math.Ceiling(fileInfo.Length / 1024.0) + " KB"); //string description = processArray[1].MainModule.FileVersionInfo.FileDescription; //Console.WriteLine("4 " + path);//不包含exe文件 // Console.WriteLine(description); for (int i = 0; i < processArray.Length; i++) { int j = i + 1; string processName = processArray[i].ProcessName; string userName = GetProcessUserName(processArray[i].Id); Console.WriteLine("NO:" + j); writer.WriteLine("NO:" + j); Console.WriteLine("进程:" + processName); writer.WriteLine("进程:" + processName); Console.WriteLine("用户:" + userName); writer.WriteLine("用户:" + userName); string path = null; System.Diagnostics.FileVersionInfo info = null; Process[] processArray1 = Process.GetProcessesByName(processName); try { path = processArray1[0].MainModule.FileName; info = System.Diagnostics.FileVersionInfo.GetVersionInfo(path); } catch { path = "未获取到"; } writer.WriteLine("路径:" + path); Console.WriteLine("路径:" + path); if (info != null) { writer.WriteLine("描述:" + info.FileDescription); Console.WriteLine("描述:" + info.FileDescription); } else { writer.WriteLine("描述:未获取到"); Console.WriteLine("描述:未获取到"); } writer.WriteLine("--------------------------------------------------------"); Console.WriteLine("--------------------------------------------------------"); } writer.Flush(); writer.Close(); Console.ReadLine(); }
public static void Main(string[] sargs) { Thread.CurrentThread.CurrentUICulture = Culture; CommandArgs args = new CommandArgs(sargs); if (args.styles) { Application.EnableVisualStyles(); } // Damn .NET text rendering Application.SetCompatibleTextRenderingDefault(false); Directory.SetCurrentDirectory(System.IO.Path.GetDirectoryName(Application.ExecutablePath)); Localizations = new LocalizationInterface(); try { string[] langfiles = Directory.GetFiles("MGE3", "*.lng"); foreach (string langfile in langfiles) { Localizations.Add(langfile); } } catch { } string language = "English (default)"; bool autoLanguage = true; try { INIFile MGEini = new INIFile(fn_inifile, new INIFile.INIVariableDef [] { INIFile.iniDefEmpty, MainForm.iniLanguage, MainForm.iniAutoLang }); language = MGEini.getKeyString("Language"); autoLanguage = (MGEini.getKeyValue("AutoLang") == 1); } catch { } Localizations.Current = language; Localizations.ApplyStrings("", strings); if (args.mutex && !MutexCheck.PerformCheck()) { MessageBox.Show(strings["MGEguiRunning"], strings["Error"]); return; } Process[] morrowind = Process.GetProcessesByName("Morrowind"); foreach (Process p in morrowind) { MessageBox.Show(strings["MWRunning"], strings["Error"]); return; } if (!File.Exists("./morrowind.exe") || !File.Exists("./morrowind.ini") || !Directory.Exists("data files")) { MessageBox.Show(strings["NotMWDir"], strings["Error"]); return; } if (!Directory.Exists("MGE3") || !File.Exists("./MGE3/MGEfuncs.dll") || !File.Exists("./d3d8.dll") || !File.Exists("./dinput8.dll")) { MessageBox.Show(strings["MGEMissing"], strings["Error"]); return; } // Morrowind version info try { FileVersionInfo MorrowVersion = FileVersionInfo.GetVersionInfo("Morrowind.exe"); if (MorrowVersion.FileMajorPart != 1 || MorrowVersion.FileMinorPart < 6) { MessageBox.Show(strings["MWIncompat"], strings["Error"]); return; } } catch { MessageBox.Show(strings["MWCorrupt"], strings["Error"]); return; } runDir = System.Windows.Forms.Application.StartupPath; // Create some structures for (int i = 0; i < MACROS; i++) { Macros[i] = new Macro(); } for (int i = 0; i < TRIGGERS; i++) { Triggers[i] = new Trigger(); } DXMain.GetDeviceCaps(); mf = new MainForm(autoLanguage); Application.Run(mf); }
private bool CheckIfHunterPieOpen() { // Block new instances of HunterPie if there's one already running return(Process.GetProcessesByName("HunterPie").Length > 1); }
public static List <SystemProcess> FindProcessesByName(string name) { var processes = new List <SystemProcess>(SystemProcess.GetProcessesByName(name)); return(processes.Where(process => Kernel32.Is32BitProcess(process.Handle)).ToList()); }
public override async Task Run() { if (String.IsNullOrWhiteSpace(RabbitMqEnvironmentVariables.RabbitMqPluginsDir)) { RabbitMqEnvironmentVariables.RabbitMqPluginsDir = Path.Combine(BinaryPathHelper.RabbitMqRoot, "plugins"); } foreach (var valuePair in typeof(IRabbitMqEnvironmentVariables) .GetProperties() .Where(property => property.CanRead && property.PropertyType == typeof(string)) .Select(property => new { NameAtt = property.GetCustomAttribute <DisplayNameAttribute>(), Property = property }) .Where(property => property.NameAtt != null) .Select(property => new { IoPath = property.Property.GetCustomAttribute <IoPathAttribute>(), Name = property.NameAtt.DisplayName, Value = (string)property.Property.GetValue(RabbitMqEnvironmentVariables) }) .Where(valuePair => !String.IsNullOrEmpty(valuePair.Value))) { EnvironmentVariables[valuePair.Name] = valuePair.IoPath == null ? valuePair.Value : valuePair.IoPath.IsDirectory ? String.Format("{0}\\{1}", valuePair.Value.MakePathForCmd(), Path.DirectorySeparatorChar) : String.Format("{0}", valuePair.Value.MakePathForCmd()); } EnvironmentVariables["ERLANG_HOME"] = String.Format("{0}\\{1}", BinaryPathHelper.ErlangRoot.MakePathForCmd(), Path.DirectorySeparatorChar); Exe = Path.Combine(BinaryPathHelper.RabbitMqRoot, "sbin", "rabbitmq-server.bat"); try { await base.Run(); erlang = WindowsProcess.GetProcessesByName("erl"); if (RabbitMqEnvironmentVariables.EnableManagement) { using (var managementProcess = new rabbitMqManagementProcess { Arguments = "enable rabbitmq_management", EnvironmentVariables = EnvironmentVariables, Exe = Path.Combine(BinaryPathHelper.RabbitMqRoot, "sbin", "rabbitmq-plugins.bat") }) { await managementProcess.Run(); } } } catch { foreach (var erl in WindowsProcess.GetProcessesByName("erl")) { using (erl) erl.Kill(); } throw; } foreach (var process in erlang) { process.TieLifecycleToParentProcess(); } }
public TreeNode CreateVirtualEnvironment(EnvDTE.Project project, out string envName, out string envPath) { var environmentsNode = OpenSolutionExplorer().FindChildOfProject( project, SR.GetString(SR.Environments) ); environmentsNode.Select(); var alreadyRunning = new HashSet <int>(Process.GetProcessesByName("python").Select(p => p.Id)); using (var createVenv = AutomationDialog.FromDte(this, "Python.AddVirtualEnvironment")) { envPath = new TextBox(createVenv.FindByAutomationId("VirtualEnvPath")).GetValue(); var baseInterp = new ComboBox(createVenv.FindByAutomationId("BaseInterpreter")).GetSelectedItemName(); envName = string.Format("{0} ({1})", envPath, baseInterp); Console.WriteLine("Expecting environment named: {0}", envName); // Force a wait for the view to be updated. var wnd = (DialogWindowVersioningWorkaround)HwndSource.FromHwnd( new IntPtr(createVenv.Element.Current.NativeWindowHandle) ).RootVisual; wnd.Dispatcher.Invoke(() => { var view = (AddVirtualEnvironmentView)wnd.DataContext; return(view.UpdateInterpreter(view.BaseInterpreter)); }).Wait(); createVenv.ClickButtonByAutomationId("Create"); createVenv.ClickButtonAndClose("Close", nameIsAutomationId: true); } List <Process> nowRunning = null; for (int retries = 100; retries > 0 && (nowRunning == null || !nowRunning.Any()); --retries) { System.Threading.Thread.Sleep(100); nowRunning = Process.GetProcessesByName("python").Where(p => !alreadyRunning.Contains(p.Id)).ToList(); } if (nowRunning == null || !nowRunning.Any()) { Assert.Fail("Failed to see python process start to create virtualenv"); } foreach (var p in nowRunning) { if (p.HasExited) { continue; } try { p.WaitForExit(30000); } catch (Win32Exception ex) { Console.WriteLine("Error waiting for process ID {0}\n{1}", p.Id, ex); } } return(OpenSolutionExplorer().WaitForChildOfProject( project, SR.GetString(SR.Environments), envName )); }
private static void CheckUpdateThread() { try { // ReSharper disable ConditionIsAlwaysTrueOrFalse if (Others.EncrypterMD5(Information.Version) == "5006678f64f53edfaa26f2587c559d1e") { // ReSharper restore ConditionIsAlwaysTrueOrFalse return; } #pragma warning disable 162 // ReSharper disable HeuristicUnreachableCode string resultReq = Others.GetRequest(Others.GetUpdateScriptLink, "null=null"); Application.DoEvents(); if (resultReq != null) { if (resultReq.Count() < 100 && resultReq.Any()) { if (resultReq != Information.Version) { string resultDesc = Others.GetRequest(Others.GetUpdateScriptLink, "show=desc"); string resultLog = Others.GetRequest(Others.GetUpdateScriptLink, "show=changelog"); DialogResult dr = MessageBox.Show( string.Format("{0}{1}{4}{4}{2}{4}{3}{4}{5}", Translate.Get(Translate.Id.LatestUpdateVersion), resultReq, Translate.Get(Translate.Id.LatestUpdateDescription), resultDesc, Environment.NewLine, Translate.Get(Translate.Id.ConfirmUpdate)), Translate.Get(Translate.Id.LatestUpdateTitle), MessageBoxButtons.YesNo, MessageBoxIcon.Question); switch (dr) { case DialogResult.Yes: Others.OpenWebBrowserOrApplication(resultLog); Others.OpenWebBrowserOrApplication("http://thenoobbot.com/downloads/latest.php"); try { foreach ( Process process in Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName)) { if (process.Id != Process.GetCurrentProcess().Id) { process.Kill(); } } } catch { } EndInformation(); break; case DialogResult.No: break; } } } } // ReSharper restore HeuristicUnreachableCode #pragma warning restore 162 } catch /*(Exception e)*/ { //Logging.WriteError("LoginServer > CheckUpdateThread(): " + e); } }