/// <summary>Loads the last saved targets.</summary> public void LoadTargets() { TargetProcesses = settings.Targets; TargetProcesses.CollectionChanged += TargetProcesses_Changed; RunningProcesses.SetArmed(TargetProcesses); OnPropertyChanged(nameof(TargetProcesses)); }
/// <summary> /// Starts running the specified application. /// </summary> /// <param name="appid">Application ID</param> /// <param name="packageName">The name of the application package.</param> /// <returns>Process identifier for the application instance.</returns> public async Task <uint> LaunchApplicationAsync( string appid, string packageName) { string payload = string.Format( "appid={0}&package={1}", Utilities.Hex64Encode(appid), Utilities.Hex64Encode(packageName)); await this.PostAsync( TaskManagerApi, payload); RunningProcesses runningApps = await this.GetRunningProcessesAsync(); uint processId = 0; foreach (DeviceProcessInfo process in runningApps.Processes) { if (string.Compare(process.PackageFullName, packageName) == 0) { processId = process.ProcessId; break; } } return(processId); }
public void GetRunningProcessesWebSocketTest_XboxOne_1608() { TestHelpers.MockHttpResponder.AddMockResponse(DevicePortal.RunningProcessApi, this.PlatformType, this.FriendlyOperatingSystemVersion, HttpMethods.WebSocket); ManualResetEvent runningProcessesReceived = new ManualResetEvent(false); RunningProcesses runningProcesses = null; WindowsDevicePortal.WebSocketMessageReceivedEventHandler <RunningProcesses> runningProcessesReceivedHandler = delegate(DevicePortal sender, WebSocketMessageReceivedEventArgs <RunningProcesses> args) { if (args.Message != null) { runningProcesses = args.Message; runningProcessesReceived.Set(); } }; TestHelpers.Portal.RunningProcessesMessageReceived += runningProcessesReceivedHandler; Task startListeningForProcessesTask = TestHelpers.Portal.StartListeningForRunningProcessesAsync(); startListeningForProcessesTask.Wait(); Assert.AreEqual(TaskStatus.RanToCompletion, startListeningForProcessesTask.Status); runningProcessesReceived.WaitOne(); Task stopListeningForProcessesTask = TestHelpers.Portal.StopListeningForRunningProcessesAsync(); stopListeningForProcessesTask.Wait(); Assert.AreEqual(TaskStatus.RanToCompletion, stopListeningForProcessesTask.Status); TestHelpers.Portal.RunningProcessesMessageReceived -= runningProcessesReceivedHandler; ValidateRunningProcessesAsync(runningProcesses); }
public void StopPool() { lock (_updateLock) { _failedStartupProcesses = 0; PoolRunning = false; foreach (var process in RunningProcesses.ToArray()) { process.ForceStop("Pool shutdown"); } } }
/// <summary> /// Monitors running processes and when the specified id is no longer running, update's the status message ui. /// </summary> /// <param name="processId">The process identifier to watch.</param> /// <param name="appName">The name of the application associated with the process identifier.</param> /// <param name="waitSeconds">Time, in seconds, to wait between checking on the processes.</param> /// <returns>Task object used for tracking method completion.</returns> private async Task WatchProcess( int processId, string appName, float waitSeconds) { ManualResetEvent resetEvent = new ManualResetEvent(false); int waitTime = (int)(waitSeconds * 1000.0f); Timer timer = new Timer( WatchProcessCallback, resetEvent, Timeout.Infinite, Timeout.Infinite); RunningProcesses runningProcesses = null; bool processIsRunning = false; try { do { MarshalStatusMessageUpdate(string.Format( "Waiting for {0} to exit", appName)); resetEvent.Reset(); timer.Change(0, waitTime); resetEvent.WaitOne(waitTime * 2); // Wait no longer than twice the specified time. runningProcesses = await this.holoLensMonitor.GetRunningProcessesAsync(); processIsRunning = runningProcesses.Contains(processId); }while(processIsRunning); MarshalStatusMessageUpdate(string.Format( "{0} has exited", appName)); } catch (Exception e) { MarshalStatusMessageUpdate(string.Format( "Cannot determine the execution state of {0} - {1}", appName, e.Message)); } timer.Change( Timeout.Infinite, Timeout.Infinite); timer.Dispose(); timer = null; }
/// <summary> /// Starts the recording process. /// </summary> private void StartProcess() { var processController = new ProcessController { Arguments = string.Format(StartParameters, OutputPath), CmdLine = Executable, // Verb = "runas", UseShellExecute = true }; processController.Start(); _lastRecordingStartDateTimeStamp = DateTime.Now; RunningProcesses.Add(processController); }
/// <summary> /// Validate the <see cref="RunningProcesses" /> returned from the tests. /// </summary> /// <param name="runningProcesses">The <see cref="RunningProcesses" /> to validate.</param> private static void ValidateRunningProcessesAsync(RunningProcesses runningProcesses) { List <DeviceProcessInfo> processes = runningProcesses.Processes; // Check some known things about this response. Assert.AreEqual(75, processes.Count); DeviceProcessInfo systemIdleprocess = processes[0]; Assert.IsNull(systemIdleprocess.AppName); Assert.AreEqual(systemIdleprocess.CpuUsage, 0); Assert.IsFalse(systemIdleprocess.IsRunning); Assert.IsFalse(systemIdleprocess.IsXAP); Assert.AreEqual(systemIdleprocess.Name, "System Idle Process"); Assert.IsNull(systemIdleprocess.PackageFullName); Assert.AreEqual(systemIdleprocess.PageFile, 0U); Assert.AreEqual(systemIdleprocess.PrivateWorkingSet, 4096U); Assert.AreEqual(systemIdleprocess.ProcessId, 0U); Assert.IsNull(systemIdleprocess.Publisher); Assert.AreEqual(systemIdleprocess.SessionId, 0U); Assert.AreEqual(systemIdleprocess.TotalCommit, 0U); Assert.AreEqual(systemIdleprocess.UserName, "NT AUTHORITY\\SYSTEM"); Assert.IsNull(systemIdleprocess.Version); Assert.AreEqual(systemIdleprocess.VirtualSize, 65536U); Assert.AreEqual(systemIdleprocess.WorkingSet, 4096U); DeviceProcessInfo devHomeProcess = processes[56]; Assert.AreEqual(devHomeProcess.AppName, "Dev Home"); Assert.AreEqual(devHomeProcess.CpuUsage, 0); Assert.IsFalse(devHomeProcess.IsRunning); Assert.IsFalse(devHomeProcess.IsXAP); Assert.AreEqual(devHomeProcess.Name, "WWAHost.exe"); Assert.AreEqual(devHomeProcess.PackageFullName, "Microsoft.Xbox.DevHome_100.1607.9000.0_x64__8wekyb3d8bbwe"); Assert.AreEqual(devHomeProcess.PageFile, 47067136U); Assert.AreEqual(devHomeProcess.PrivateWorkingSet, 32796672U); Assert.AreEqual(devHomeProcess.ProcessId, 3424U); Assert.AreEqual(devHomeProcess.Publisher, "CN=Microsoft Corporation, O=Microsoft Corporation, L=Redmond, S=Washington, C=US"); Assert.AreEqual(devHomeProcess.SessionId, 0U); Assert.AreEqual(devHomeProcess.TotalCommit, 49213440U); Assert.AreEqual(devHomeProcess.UserName, "TESTXBOX\\DefaultAccount"); Assert.AreEqual(devHomeProcess.Version.Build, 9000U); Assert.AreEqual(devHomeProcess.Version.Major, 100U); Assert.AreEqual(devHomeProcess.Version.Minor, 1607U); Assert.AreEqual(devHomeProcess.Version.Revision, 0U); Assert.AreEqual(devHomeProcess.VirtualSize, 2234032066560U); Assert.AreEqual(devHomeProcess.WorkingSet, 79466496U); }
private void UpdateProcesses(object o) { lock (_updateLock) { if (_updateProcessesRunning) { return; } _updateProcessesRunning = true; var processesToRemove = new List <IVstHostProcess>(); foreach (var process in RunningProcesses) { if (process.CurrentProcessState == ProcessState.EXITED) { UnwatchProcess(process); processesToRemove.Add(process); OldProcesses.Add(process); } } foreach (var process in processesToRemove) { RunningProcesses.Remove(process); } if (PoolRunning) { if (RunningProcesses.Count < _maxProcesses) { var process = new VstHostProcess(_maxStartTimeout); process.ProcessStateUpdated += ProcessOnProcessStateUpdated; process.Start(); RunningProcesses.Add(process); _totalStartedProcesses++; } } NumRunningProcesses = (from process in RunningProcesses where process.CurrentProcessState == ProcessState.RUNNING select process).Count(); NumTotalProcesses = RunningProcesses.Count; _updateProcessesRunning = false; } }
public static void ProgressingComplete(string key) { lock (_keys) { if (_keys.Contains(key)) { _keys.Remove(key); } if ((_form != null) && (_keys.Count == 0)) { _form.Close(); _form = null; } } }
void startWatcher_EventArrived(object sender, EventArrivedEventArgs e) { lock (lockProcesses) { var process = GetProcessDetails(e.NewEvent); if (AddProcess != null) { AddProcess(process); } if (process != null) { RunningProcesses.Add(process); } } }
public static string ProgressingStarted(string text, bool topMost, int timeout) { var key = Guid.NewGuid().ToString(); lock (_keys) { _keys.Add(key); if (_form == null) { _form = new RunningProcesses(); _form.Update(text, topMost, timeout); _form.Show(); System.Windows.Forms.Application.DoEvents(); } } return(key); }
/// <summary> /// Validate the <see cref="RunningProcesses" /> returned from the tests. /// </summary> /// <param name="runningProcesses">The <see cref="RunningProcesses" /> to validate.</param> private static void ValidateRunningProcesses(RunningProcesses runningProcesses) { List <DeviceProcessInfo> processes = new List <DeviceProcessInfo>(runningProcesses.Processes); // Check some known things about this response. Assert.AreEqual(2, processes.Count); DeviceProcessInfo systemIdleprocess = processes[0]; Assert.IsNull(systemIdleprocess.AppName); Assert.AreEqual(systemIdleprocess.CpuUsage, 0); Assert.IsFalse(systemIdleprocess.IsRunning); Assert.IsFalse(systemIdleprocess.IsXAP); Assert.AreEqual(systemIdleprocess.Name, "System Idle Process"); Assert.IsNull(systemIdleprocess.PackageFullName); Assert.AreEqual(systemIdleprocess.PageFile, 0U); Assert.AreEqual(systemIdleprocess.PrivateWorkingSet, 4096); Assert.AreEqual(systemIdleprocess.ProcessId, 0); Assert.IsNull(systemIdleprocess.Publisher); Assert.AreEqual(systemIdleprocess.SessionId, 0U); Assert.AreEqual(systemIdleprocess.TotalCommit, 0); Assert.AreEqual(systemIdleprocess.UserName, "NT AUTHORITY\\SYSTEM"); Assert.IsNull(systemIdleprocess.Version); Assert.AreEqual(systemIdleprocess.VirtualSize, 65536); Assert.AreEqual(systemIdleprocess.WorkingSet, 4096U); DeviceProcessInfo devHomeProcess = processes[1]; Assert.IsNull(devHomeProcess.AppName); Assert.AreEqual(devHomeProcess.CpuUsage, 0); Assert.IsFalse(devHomeProcess.IsRunning); Assert.IsFalse(devHomeProcess.IsXAP); Assert.AreEqual(devHomeProcess.Name, "svchost.exe"); Assert.IsNull(devHomeProcess.PackageFullName); Assert.AreEqual(devHomeProcess.PageFile, 5472256U); Assert.AreEqual(devHomeProcess.PrivateWorkingSet, 4755456); Assert.AreEqual(devHomeProcess.ProcessId, 892); Assert.IsNull(devHomeProcess.Publisher); Assert.AreEqual(devHomeProcess.SessionId, 0U); Assert.AreEqual(devHomeProcess.TotalCommit, 5914624); Assert.AreEqual(devHomeProcess.UserName, "NT AUTHORITY\\SYSTEM"); Assert.IsNull(devHomeProcess.Version); Assert.AreEqual(devHomeProcess.VirtualSize, 2203387539456); Assert.AreEqual(devHomeProcess.WorkingSet, 17285120U); }
public void Invoke(string script, RunningProcesses runningProcesses) { Process process = new Process(); try { process.StartInfo = new ProcessStartInfo() { FileName = $"{Environment.SystemDirectory}\\{ScriptConstants.kPowerShellPath}", RedirectStandardError = true, RedirectStandardOutput = true, CreateNoWindow = true, UseShellExecute = false, Arguments = script, }; process.StartInfo.EnvironmentVariables["Path"] = CreatePathEnvironmentVariable(); process.EnableRaisingEvents = true; process.ErrorDataReceived += DataErrorHandler; process.OutputDataReceived += DataHandler; process.Exited += ExitedHandler; process.Disposed += ExitedHandler; runningProcesses.Add(process); process.Start(); process.BeginErrorReadLine(); process.BeginOutputReadLine(); process.WaitForExit(); } catch (Exception e) { process.EnableRaisingEvents = false; process.ErrorDataReceived -= DataErrorHandler; process.OutputDataReceived -= DataHandler; process.Exited -= ExitedHandler; process.Disposed -= ExitedHandler; process.Close(); throw e; } }
/// <summary> /// Stops all running applications on this HoloLens. /// </summary> /// <returns>Task object used for tracking method completion.</returns> public async Task TerminateAllApplicationsAsync() { RunningProcesses runningApps = await this.GetRunningProcessesAsync(); foreach (DeviceProcessInfo processInfo in runningApps.Processes) { // Do not terminate the shell. if (ShellApp.ToLower() == processInfo.Name.ToLower()) { continue; } if (!string.IsNullOrWhiteSpace(processInfo.PackageFullName)) { await this.TerminateApplicationAsync(processInfo.PackageFullName); } } }
/// <summary> /// Main entry point for handling listing processes /// </summary> /// <param name="portal">DevicePortal reference for communicating with the device.</param> /// <param name="parameters">Parsed command line parameters.</param> public static void HandleOperation(DevicePortal portal, ParameterHelper parameters) { RunningProcesses runningProcesses = null; if (parameters.HasFlag(ParameterHelper.Listen)) { ManualResetEvent runningProcessesReceived = new ManualResetEvent(false); WebSocketMessageReceivedEventHandler <RunningProcesses> runningProcessesReceivedHandler = delegate(DevicePortal sender, WebSocketMessageReceivedEventArgs <RunningProcesses> runningProccesesArgs) { if (runningProccesesArgs.Message != null) { runningProcesses = runningProccesesArgs.Message; runningProcessesReceived.Set(); } }; portal.RunningProcessesMessageReceived += runningProcessesReceivedHandler; Task startListeningForProcessesTask = portal.StartListeningForRunningProcesses(); startListeningForProcessesTask.Wait(); runningProcessesReceived.WaitOne(); Task stopListeningForProcessesTask = portal.StopListeningForRunningProcesses(); stopListeningForProcessesTask.Wait(); portal.RunningProcessesMessageReceived -= runningProcessesReceivedHandler; } else { Task <DevicePortal.RunningProcesses> getRunningProcessesTask = portal.GetRunningProcesses(); runningProcesses = getRunningProcessesTask.Result; } foreach (DeviceProcessInfo process in runningProcesses.Processes) { if (!string.IsNullOrEmpty(process.Name)) { Console.WriteLine(process.Name); } } }
/// <summary> /// Stops the recording process. /// </summary> /// <exception cref="System.Exception">No processes exit to stop.</exception> private void StopProcess() { //2013.08.26: Ashley Lewis for bug 10196: This process stops the recording using stop params TODO refactor to ProcessController var startInfo = new ProcessStartInfo(Executable, StopParameters) { UseShellExecute = true, ErrorDialog = false, }; var stopRecordingProcess = new Process { StartInfo = startInfo }; // // This check is to prevent stop from being called to soon after pse.exe has been started. // Otherwise the /stop paramater on the stop call is ignored and the process which was originally // started just continues to run until manually closed. // It isn't very pretty but psr.exe doesn't provide a mechanism to check if it has finished initializing, // and there is no standard in .net to tell if a process that has been started is 'ready'. // if ((DateTime.Now - _lastRecordingStartDateTimeStamp).TotalMilliseconds < 500) { Thread.Sleep(500); } try { stopRecordingProcess.Start(); } catch (Exception e) { Console.WriteLine(@"Start Info : " + startInfo); Console.WriteLine(@"Stacktrace : " + e.StackTrace); throw; } RunningProcesses.Add(new ProcessController(stopRecordingProcess)); WaitForProcessesToEnd(RunningProcesses.ToArray()); RunningProcesses.Clear(); }
/// <summary> /// Implementation of the referesh running applications command. /// </summary> /// <returns>Task object used for tracking method completion.</returns> private async Task RefreshRunningAppsAsync() { RunningProcesses runningApps = await this.deviceMonitor.GetRunningProcessesAsync(); List <string> appNames = new List <string>(); foreach (DeviceProcessInfo processInfo in runningApps.Processes) { if (!string.IsNullOrWhiteSpace(processInfo.PackageFullName)) { appNames.Add(string.Format( "{0} ({1})", processInfo.AppName, processInfo.PackageFullName)); } } appNames.Sort(); this.UpdateRunningApps(appNames); }
/// <summary> /// Stops all running applications on this device. /// </summary> /// <returns>Task object used for tracking method completion.</returns> public async Task TerminateAllApplicationsAsync() { RunningProcesses runningApps = await this.GetRunningProcessesAsync(); List <string> doNotClose = new List <string>(); doNotClose.AddRange(DoNotCloseApps); foreach (DeviceProcessInfo processInfo in runningApps.Processes) { // Skip applications that should not be closed. if (doNotClose.Contains( processInfo.Name, StringComparer.OrdinalIgnoreCase)) { continue; } if (!string.IsNullOrWhiteSpace(processInfo.PackageFullName)) { await this.TerminateApplicationAsync(processInfo.PackageFullName); } } }
public void Remove(int id) { RunningProcesses.RemoveAll(p => p.Id == id); }
void RefreshProcessList() { ObservableCollection <RunningProcess> list = new ObservableCollection <RunningProcess>(); Process currentProcess = Process.GetCurrentProcess(); foreach (Process process in Process.GetProcesses()) { try { // Prevent slow exceptions by filtering out processes we can't access using (var fh = OpenProcess(PROCESS_ALL_ACCESS, false, process.Id)) { if (fh.IsInvalid) { continue; } } bool isWow64Process; if (IsWow64Process(process.Handle, out isWow64Process)) { if (IntPtr.Size == 4 && !isWow64Process) { continue; } } if (process.HasExited) { continue; } // Prevent attaching to our own process. if (currentProcess.Id != process.Id) { bool managed = false; try { var modules = process.Modules.Cast <ProcessModule>().Where(IsNetModule); managed = modules.Count() > 0; } catch { } if (managed) { list.Add(new RunningProcess { ProcessId = process.Id, ProcessName = Path.GetFileName(process.MainModule.FileName), FileName = process.MainModule.FileName, WindowTitle = process.MainWindowTitle, Managed = "Managed", Process = process }); } } } catch (Win32Exception) { // Do nothing. } } RunningProcesses.ItemsSource = list; if (list.Count > 0) { RunningProcesses.SelectedIndex = 0; RunningProcesses.Focus(); // We must wait a little bit for it to create the ListViewItem Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => { var item = RunningProcesses.ItemContainerGenerator.ContainerFromIndex(0) as ListViewItem; if (item != null) { item.Focus(); } })); } }
public override void StartWatching() { var actualPath = Path.GetDirectoryName(Path.GetFullPath(Watch.Path)); var binPath = CsprojHelper.GetBinaryPath(actualPath); var outputDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()) + "\\"; // Run Process Delegate WaitCallback runProcess = (o) => { var process = new ProcessStartInfo() { CreateNoWindow = false, WorkingDirectory = actualPath, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardInput = true, RedirectStandardError = true }; if (Path.GetExtension(binPath) == ".exe") { process.FileName = Path.Combine(outputDir, Path.GetFileName(binPath)); } else { process.FileName = "dotnet"; process.Arguments = Path.Combine(outputDir, Path.GetFileName(binPath)); } foreach (var env in Watch.Environment) { process.Environment[env.Key] = env.Value; } if (!string.IsNullOrWhiteSpace(Watch.Args)) { process.Arguments = string.Join(" ", process.Arguments, Watch.Args); } var proc = Process.Start(process); proc.EnableRaisingEvents = true; RunningProcesses.GetOrAdd(Watch, proc); DisplayUpdate?.Invoke(); proc.WaitForExit(); RunningProcesses.TryRemove(Watch, out proc); if (Directory.Exists(outputDir)) { Directory.Delete(outputDir, true); } DisplayUpdate?.Invoke(); }; Watcher = new FileSystemWatcher(Path.GetDirectoryName(binPath), Path.GetFileName(binPath)) { NotifyFilter = NotifyFilters.LastWrite }; Watcher.Changed += (sender, e) => { if (ShouldSkip?.Invoke() ?? false) { return; } InvokeCallback?.Invoke(); if (RunningProcesses.ContainsKey(Watch)) { RunningProcesses[Watch].Kill(); } Thread.Sleep(500); Extensions.CloneDirectory(Path.GetDirectoryName(binPath), outputDir); ThreadPool.QueueUserWorkItem(runProcess); }; Watcher.EnableRaisingEvents = true; if (!RunningProcesses.ContainsKey(Watch)) { // Initial Run - we want to run at startup Extensions.CloneDirectory(Path.GetDirectoryName(binPath), outputDir); ThreadPool.QueueUserWorkItem(runProcess); } }
/// <summary>Updates armed statuses when target processes are changed.</summary> private void TargetProcesses_Changed(object sender, NotifyCollectionChangedEventArgs e) { RunningProcesses.SetArmed(TargetProcesses); OnPropertyChanged(nameof(TargetProcesses)); OnPropertyChanged(nameof(ArmedRunningProcessCount)); }