public static async Task <BethesdaNetData> Login() { var game = Path.Combine(Game.SkyrimSpecialEdition.MetaData().GameLocation(), "SkyrimSE.exe"); var info = new ProcessStartInfo { FileName = @"Downloaders\BethesdaNet\bethnetlogin.exe", Arguments = $"\"{game}\" SkyrimSE.exe", RedirectStandardError = true, RedirectStandardInput = true, RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true }; var process = Process.Start(info); ChildProcessTracker.AddProcess(process); string last_line = ""; while (true) { var line = await process.StandardOutput.ReadLineAsync(); if (line == null) { break; } last_line = line; } var result = last_line.FromJSONString <BethesdaNetData>(); result.ToEcryptedJson(DataName); return(result); }
/// <summary> /// </summary> /// <param name="arguments"></param> /// <returns></returns> public string ExecuteGitCommand(params string[] arguments) { ProcessStartInfo StartInfo = new ProcessStartInfo(); StartInfo.FileName = "git"; StartInfo.WorkingDirectory = Root; StartInfo.Arguments = string.Join(" ", arguments); StartInfo.RedirectStandardOutput = true; StartInfo.RedirectStandardError = true; StartInfo.UseShellExecute = false; StartInfo.CreateNoWindow = true; Process process = Process.Start(StartInfo); ChildProcessTracker.AddProcess(process); string Output = ""; process.OutputDataReceived += delegate(object sender, DataReceivedEventArgs e) { Logger.Log(LogLevel.Verbose, LogCategory.Scm, "{0}", e.Data); Output += e.Data + "\n"; }; process.ErrorDataReceived += delegate(object sender, DataReceivedEventArgs e) { Logger.Log(LogLevel.Info, LogCategory.Scm, "{0}", e.Data); }; process.BeginErrorReadLine(); process.BeginOutputReadLine(); process.WaitForExit(); return(process.ExitCode == 0 ? Output : ""); }
public void StartProcess() { StopProcess(); logOutput = new List <string>(); this.process = new Process(); process.StartInfo = new ProcessStartInfo { FileName = exePath, CreateNoWindow = true, RedirectStandardError = true, RedirectStandardInput = true, RedirectStandardOutput = true, UseShellExecute = false, WindowStyle = ProcessWindowStyle.Hidden, }; process.Start(); Task.Run(() => { while (true) { var line = process.StandardOutput.ReadLine(); if (line == null) { break; } lock (logOutput) { logOutput.Add(line); } } }); Task.Run(() => { while (true) { var line = process.StandardError.ReadLine(); if (line == null) { break; } lock (logOutput) { logOutput.Add(line); } } }); ChildProcessTracker.AddProcess(process); shouldBeAlive = true; }
static void Main(string[] args) { p = Process.Start(new ProcessStartInfo() { FileName = @"G:\SteamLibrary\steamapps\common\RimWorld\RimWorldWin64.exe", Arguments = "network_launch" }); ChildProcessTracker.AddProcess(p); System.Threading.Thread.Sleep(5000); SetWindowText(p.MainWindowHandle, "Rimworld launched by 6opoDuJIo launcher to handle OBS mess!"); p.WaitForExit(); }
public async Task <int> Run() { _process.Start(); ChildProcessTracker.AddProcess(_process); if (_hookingOutput) { _process.BeginErrorReadLine(); _process.BeginOutputReadLine(); } return(await WatchComplete().ConfigureAwait(false)); }
public override void Run() { RaisePreviewRunEvent(AcsFilename); GameProcess = Process.Start(new ProcessStartInfo { FileName = AcsFilename, WorkingDirectory = _acRoot }); if (GameProcess != null && OptionTrackProcess) { ChildProcessTracker.AddProcess(GameProcess); } }
private void DumpRom_(IFile romFile) { var logger = Logging.Create <HackingToolkit9ds>(); logger.LogInformation($"Dumping ROM {romFile}..."); Files.RunInDirectory( ThreeDsToolsConstants.HACKING_TOOLKIT_9DS_DIRECTORY, () => { var processStartInfo = new ProcessStartInfo( $"\"{ThreeDsToolsConstants.HACKING_TOOLKIT_9DS_EXE.FullName}\"") { CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true, RedirectStandardInput = true, UseShellExecute = false, }; var process = Asserts.CastNonnull(Process.Start(processStartInfo)); ChildProcessTracker.AddProcess(process); var singleChar = new char[1]; var output = ""; while (!output.EndsWith("Write your choice:")) { process.StandardOutput.Read(singleChar, 0, 1); output += singleChar[0]; } process.StandardInput.WriteLine("CE"); // For some reason this is needed by HackingToolkit9DS. var romPathWithoutExtension = romFile.FullName.Substring(0, romFile.FullName.Length - ".cia".Length); process.StandardInput.WriteLine(romPathWithoutExtension); output = ""; while (!output.EndsWith("Extraction done!")) { process.StandardOutput.Read(singleChar, 0, 1); output += singleChar[0]; } process.Kill(true); }); }
public override void Run() { SteamRunningHelper.EnsureSteamIsRunning(RunSteamIfNeeded, false); CreateAppIdFile(); RaisePreviewRunEvent(AcsFilename); GameProcess = Process.Start(new ProcessStartInfo { FileName = AcsFilename, WorkingDirectory = AcRootDirectory.Instance.RequireValue }); if (GameProcess != null && OptionTrackProcess) { ChildProcessTracker.AddProcess(GameProcess); } }
public static async Task <BethesdaNetData?> Login(Game game) { var metadata = game.MetaData(); if (metadata.MainExecutable == null) { throw new NotImplementedException(); } var gamePath = metadata.GameLocation().Combine(metadata.MainExecutable); var info = new ProcessStartInfo { FileName = @"Downloaders\BethesdaNet\bethnetlogin.exe", Arguments = $"\"{gamePath}\" {metadata.MainExecutable}", RedirectStandardError = true, RedirectStandardInput = true, RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true }; var process = Process.Start(info); ChildProcessTracker.AddProcess(process); string last_line = ""; while (true) { var line = await process.StandardOutput.ReadLineAsync(); if (line == null) { break; } last_line = line; } try { var result = last_line.FromJsonString <BethesdaNetData>(); await result.ToEcryptedJson(DataName); return(result); } catch (Exception ex) { Utils.Error(ex, "Could not save Bethesda.NET login info"); return(null); } }
public static IWebDriver GetDriver() { if (_foundDriver == null || _foundDriver == DriverType.Chrome) { try { var service = ChromeDriverService.CreateDefaultService(); service.HideCommandPromptWindow = true; var options = new ChromeOptions(); options.AddArguments(new List <string>() { "--silent-launch", "--no-startup-window", "no-sandbox", "headless", }); var driver = new ChromeDriver(service, options); ChildProcessTracker.AddProcess(Process.GetProcesses().Single(p => p.Id == service.ProcessId)); _foundDriver = DriverType.Chrome; return(driver); } catch (Exception) { // ignored } } if (_foundDriver == null || _foundDriver == DriverType.InternetExplorer) { try { var driver = new InternetExplorerDriver(); _foundDriver = DriverType.InternetExplorer; return(driver); } catch (Exception) { // ignored } } return(null); }
private void StartServer(object parameter) { var parameters = (ProcessStartInfo)parameter; ServerProcess = new Process(); ServerProcess.StartInfo = parameters; ServerProcess.Start(); ChildProcessTracker.AddProcess(ServerProcess); ID = ServerProcess.Id; Logger.ConsoleLogger.Log(ServerProcess.ProcessName); ServerProcess.OutputDataReceived += (sender, e) => OutPutEvent?.Invoke(e); ServerProcess.BeginOutputReadLine(); ServerProcess.WaitForExit(); CloseEvent?.Invoke(); }
static void Main(string[] args) { //Application.EnableVisualStyles(); //Application.SetCompatibleTextRenderingDefault(false); Arguments = args; if (args.Length > 0 && args[0] == "securedesktop") { Process sDesktopProcess = BelowAverage.SecureDesktop.StartProcess(Application.ExecutablePath + " top"); ChildProcessTracker.AddProcess(sDesktopProcess); sDesktopProcess.WaitForExit(); } else { //Application.Run(new DisplayForm()); Application.Run(new BuildForm()); } }
private static bool StartProcess(int taskid, NodeTaskRuntimeInfo taskruntimeinfo, Process result) { taskruntimeinfo.Process = result; /* AppDomain.CurrentDomain.DomainUnload += (s, e) => * { * result.Kill(); * result.WaitForExit(); * }; * AppDomain.CurrentDomain.ProcessExit += (s, e) => * { * result.Kill(); * result.WaitForExit(); * }; * AppDomain.CurrentDomain.UnhandledException += (s, e) => * { * result.Kill(); * result.WaitForExit(); * }; */ // Task a = Task.Factory.StartNew(() => // { bool isStart = result.Start(); ChildProcessTracker.AddProcess(result); Task.Factory.StartNew(() => { while (!result.StandardOutput.EndOfStream) { string line = result.StandardOutput.ReadLine(); // do something with line LogHelper.AddTaskLog(line, taskid); } }); bool r = TaskPoolManager.CreateInstance().AddInstance(taskid.ToString(), taskruntimeinfo); return(r); }
private async Task RunAcServer(string serverExecutable, ICollection <string> log, IProgress <AsyncProgressEntry> progress, CancellationToken cancellation) { try { using (var process = new Process { StartInfo = { FileName = serverExecutable, Arguments = $"-c presets/{Id}/server_cfg.ini -e presets/{Id}/entry_list.ini", UseShellExecute = false, WorkingDirectory = Path.GetDirectoryName(serverExecutable) ?? "", RedirectStandardOutput = true, CreateNoWindow = true, RedirectStandardError = true, StandardOutputEncoding = Encoding.UTF8, StandardErrorEncoding = Encoding.UTF8, } }) { process.Start(); SetRunning(process); ChildProcessTracker.AddProcess(process); progress?.Report(AsyncProgressEntry.Finished); process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.OutputDataReceived += (sender, args) => ActionExtension.InvokeInMainThread(() => log.Add(args.Data)); process.ErrorDataReceived += (sender, args) => ActionExtension.InvokeInMainThread(() => log.Add($@"[color=#ff0000]{args.Data}[/color]")); await process.WaitForExitAsync(cancellation); if (!process.HasExitedSafe()) { process.Kill(); } log.Add($@"[CM] Stopped: {process.ExitCode}"); } } finally { SetRunning(null); } }
private async Task <bool> RunRhmAsync(bool keepVisible = false) { if (SettingsHolder.Drive.RhmLocation == null) { return(false); } try { _process = Process.Start(new ProcessStartInfo { FileName = SettingsHolder.Drive.RhmLocation, WorkingDirectory = Path.GetDirectoryName(SettingsHolder.Drive.RhmLocation) ?? "" }); if (_process == null) { throw new Exception(@"Process=NULL"); } } catch (Exception e) { NonfatalError.Notify(ToolsStrings.RhmService_CannotStart, e); return(false); } ChildProcessTracker.AddProcess(_process); if (keepVisible) { return(true); } for (var i = 0; i < 100; i++) { if (SetVisibility(false)) { return(true); } await Task.Delay(10); } NonfatalError.Notify("Can’t find app’s window"); EnsureStopped(); return(false); }
public static void DeleteDirectory(string path) { var info = new ProcessStartInfo { FileName = "cmd.exe", Arguments = $"/c del /f /q /s \"{path}\" && rmdir /q /s \"{path}\" ", RedirectStandardError = true, RedirectStandardInput = true, RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true }; var p = new Process { StartInfo = info }; p.Start(); ChildProcessTracker.AddProcess(p); try { p.PriorityClass = ProcessPriorityClass.BelowNormal; } catch (Exception) { } while (!p.HasExited) { var line = p.StandardOutput.ReadLine(); if (line == null) { break; } Utils.Status(line); } p.WaitForExit(); }
private void RunInner() { SteamRunningHelper.EnsureSteamIsRunning(RunSteamIfNeeded, false); new IniFile(AcPaths.GetRaceIniFilename()) { ["AUTOSPAWN"] = { ["ACTIVE"] = true, ["__CM_SERVICE"] = IniFile.Nothing } }.Save(); SetAcX86Param(); RaisePreviewRunEvent(AcsFilename); LauncherProcess = Process.Start(new ProcessStartInfo { FileName = LauncherFilename, WorkingDirectory = AcRootDirectory.Instance.RequireValue }); if (LauncherProcess != null && OptionTrackProcess) { ChildProcessTracker.AddProcess(LauncherProcess); } }
public override void Run() { var acRoot = AcRootDirectory.Instance.RequireValue; var addon = PluginsManager.Instance.GetById(AddonId); if (addon?.IsReady != true) { throw new Exception("Addon isn’t ready"); } _filename = addon.GetFilename(ConfigName); var target = PrepareExecutable(acRoot); var defaultConfig = addon.GetFilename("config.ini"); if (File.Exists(defaultConfig)) { new IniFile(defaultConfig) { ["Launcher"] = { ["Target"] = target, ["StartIn"] = acRoot, ["SteamClientPath"] = addon.GetFilename("sse86.dll"), ["SteamClientPath64"] = addon.GetFilename("sse64.dll") }, }.Save(_filename); } else { new IniFile { ["Launcher"] = { ["Target"] = target, ["StartIn"] = acRoot, ["InjectDll"] = false, ["SteamClientPath"] = addon.GetFilename("sse86.dll"), ["SteamClientPath64"] = addon.GetFilename("sse64.dll") }, ["Achievements"] = { ["UnlockAll"] = true }, ["Debug"] = { ["EnableLog"] = OptionLogging, ["Minidump"] = OptionLogging, }, ["SSEOverlay"] = { ["DisableOverlay"] = true, ["OnlineMode"] = false, }, ["SmartSteamEmu"] = { ["AppId"] = AcSteamId, ["SteamIdGeneration"] = "Manual", ["ManualSteamId"] = SteamIdHelper.Instance.Value, ["Offline"] = true, ["EnableOverlay"] = false, ["EnableHTTP"] = false, ["DisableGC"] = true, ["DisableLeaderboard"] = true, ["DisableFriendList"] = true, ["VR"] = true, } }.Save(_filename); } RaisePreviewRunEvent(AcsFilename); LauncherProcess = Process.Start(new ProcessStartInfo { FileName = addon.GetFilename("sse.exe"), WorkingDirectory = addon.Directory, Arguments = ConfigName }); if (LauncherProcess != null && OptionTrackProcess) { ChildProcessTracker.AddProcess(LauncherProcess); } }
private void Form1_Load(object sender, EventArgs e) { ManagementObjectSearcher objvide = new ManagementObjectSearcher("select * from Win32_VideoController"); Dictionary <String, Int32> gpus = new Dictionary <string, Int32>(); foreach (ManagementObject obj in objvide.Get()) { String gpuName = obj["Name"].ToString().Trim(); if (gpus.ContainsKey(gpuName)) { gpus[gpuName] = gpus[gpuName] + 1; } else { gpus[gpuName] = 1; } } List <Bundle> bundles = new List <Bundle>(); mainFrame = new MainFrame(this, bundles); GlobalMouseClick += (o, i) => { int x = 0; int y = 0; if (o.GetType() == typeof(PictureBox)) { PictureBox pic = o as PictureBox; x += pic.Location.X; y += pic.Location.Y; } x += i.X; y += i.Y; Graphics gfx = this.CreateGraphics(); mainFrame.Click(x, y, this, gfx); gfx.Dispose(); }; Random rnd = new Random(); ManagementObjectSearcher mos = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_Processor"); foreach (ManagementObject mo in mos.Get()) { String cpuName = mo["Name"].ToString().Trim(); double es = rnd.NextDouble() / 100f; bundles.Add(new Bundle(cpuName, new Gui.Bundles.Algo("CryptoNight", "h/s"), rnd.NextDouble() * 999, es, 0)); } foreach (KeyValuePair <string, Int32> entry in gpus) { String extra = ""; if (entry.Value != 1) { extra = entry.Value + "x "; } double es = rnd.NextDouble() / 100f; bundles.Add(new Bundle(extra + entry.Key, new Gui.Bundles.Algo("CryptoNight", "h/s"), rnd.NextDouble() * 999, es, 0)); } /*new Thread(delegate () * { * CryptoElectronMaster.Auth(this, bundles); * }).Start();*/ this.FireFrameEvent("BundlesLoaded", bundles); FrameForm s = this; Thread t = new Thread(delegate() { while (true) { try { Double est = 0; foreach (Bundle bundle in bundles) { if (bundle.IsMining()) { Double d = 0.99 + rnd.NextDouble() / 50f; bundle.Hashrate *= d; bundle.Estimates *= d; est += bundle.Estimates; } } s.Invoke((MethodInvoker)(() => { this.FireFrameEvent("DailyETHEarningChanged", est); })); s.Invoke((MethodInvoker)(() => { this.FireFrameEvent("ETHBalanceChanged", est / 50); })); s.Invoke((MethodInvoker)(() => { this.FireFrameEvent("BundleStatusChanged", bundles); })); Thread.Sleep(200); } catch (Exception) { } } }); t.Start(); s.FormClosed += (o, i) => { t.Abort(); }; /*String args = "--farm-recheck 200 -U -S lb.geo.pirlpool.eu:8002 -SP 1 -O 0xddd841483e6b42c35e40164278e684c7e6e2b271.1080Ti"; * String pathToEthminer = "C:\\Users\\aki\\Desktop\\mining\\ethminer\\ethminer.exe"; * MinerExecutable.Clear("Ethash"); * String pathToExecutable = MinerExecutable.Build("Ethash", pathToEthminer, args, false); * * //MessageBox.Show(); * Process p = new Process(); * p.StartInfo.UseShellExecute = false; * p.StartInfo.RedirectStandardOutput = true; * p.StartInfo.CreateNoWindow = true; * p.StartInfo.FileName = Path.GetFullPath(pathToExecutable); * p.Start(); * ChildProcessTracker.AddProcess(p);*/ String args = "--server"; String pathToEthminer = "C:\\Users\\aki\\Desktop\\mining\\ethminer\\ethminer.exe"; MinerExecutable.Clear("Ethash"); String pathToExecutable = MinerExecutable.Build("Ethash", pathToEthminer, args, false); //MessageBox.Show(); Process p = new Process(); p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.CreateNoWindow = true; p.StartInfo.FileName = Path.GetFullPath(pathToExecutable); p.Start(); ChildProcessTracker.AddProcess(p); /*new Thread(delegate () * { * MessageBox.Show("p"); * Thread.Sleep(1000); * KillProcessAndChildren(p.Id); * MessageBox.Show("killed"); * }).Start();*/ }
/// <summary> /// </summary> private bool InstallStep(string LocalFolder, ref string ResultMessage, BuildInstallStep Step) { string ExePath = BuildSettings.ExpandArguments(Step.Executable, Variables); if (!Path.IsPathRooted(ExePath)) { ExePath = Path.Combine(LocalFolder, ExePath); } string WorkingDir = BuildSettings.ExpandArguments(Step.WorkingDirectory, Variables); if (WorkingDir.Length == 0) { WorkingDir = Path.GetDirectoryName(ExePath); } else { if (!Path.IsPathRooted(WorkingDir)) { WorkingDir = Path.Combine(LocalFolder, WorkingDir); } } #if SHIPPING if (!File.Exists(ExePath)) { ResultMessage = "Could not find executable, expected to be located at: " + ExePath; return(false); } if (!Directory.Exists(WorkingDir)) { ResultMessage = "Could not find working directory, expected at: " + WorkingDir; return(false); } #endif string Arguments = BuildSettings.ExpandArguments(Step.Arguments, Variables); Logger.Log(LogLevel.Info, LogCategory.Main, "Executing: {0} {1}", ExePath, Arguments); try { ProcessStartInfo StartInfo = new ProcessStartInfo(); StartInfo.FileName = ExePath; StartInfo.WorkingDirectory = WorkingDir; StartInfo.Arguments = Arguments; StartInfo.RedirectStandardOutput = true; StartInfo.RedirectStandardError = true; StartInfo.UseShellExecute = false; StartInfo.CreateNoWindow = true; Process process = Process.Start(StartInfo); ChildProcessTracker.AddProcess(process); process.OutputDataReceived += delegate(object sender, DataReceivedEventArgs e) { Logger.Log(LogLevel.Info, LogCategory.Main, "{0}", e.Data); }; process.ErrorDataReceived += delegate(object sender, DataReceivedEventArgs e) { Logger.Log(LogLevel.Info, LogCategory.Main, "{0}", e.Data); }; process.BeginErrorReadLine(); process.BeginOutputReadLine(); process.WaitForExit(); if (process.ExitCode != 0 && !Step.IgnoreErrors) { ResultMessage = "Install process exited with error code " + process.ExitCode; return(false); } } catch (Exception Ex) { ResultMessage = "Install process exited with error: " + Ex.Message; return(false); } return(true); }
private async Task _PlayAsync(string deviceUniqueId, CancellationTokenSource cancellationTokenSource, int attempts = 0) { Device device = await FindDeviceAsync(deviceUniqueId); if (device == null) { await Task.FromException(new NullReferenceException("Couldn't get device with uniqueId " + deviceUniqueId)).ConfigureAwait(false); } else { int deviceInstanceId = SnapSettings.DetermineInstanceId(deviceUniqueId, device.Index); DeviceSettings deviceSettings = SnapSettings.GetDeviceSettings(deviceUniqueId); if (deviceInstanceId != -1) { // update device's last seen: deviceSettings.LastSeen = DateTime.Now; SnapSettings.SaveDeviceSettings(deviceUniqueId, deviceSettings); StringBuilder stdError = new StringBuilder(); string lastLine = ""; Action <string> stdOut = (line) => { lastLine = line; // we only care about the last line from the output - in case there's an error (snapclient should probably be sending these to stderr though) }; string resampleArg = ""; string hostIdArg = ""; CommandTask <CommandResult> task = null; if (deviceSettings.UseSnapClientNet == false) { // Launch native client: if (string.IsNullOrEmpty(deviceSettings.ResampleFormat) == false) { resampleArg = $"--sampleformat {deviceSettings.ResampleFormat}:0"; } if (string.IsNullOrWhiteSpace(deviceSettings.HostId) == false) { hostIdArg = $"--hostID \"{deviceSettings.HostId}\""; } string command = $"-h {SnapSettings.Server} -p {SnapSettings.PlayerPort} -s {device.Index} -i {deviceInstanceId} --sharingmode={deviceSettings.ShareMode.ToString().ToLower()} {resampleArg} {hostIdArg}"; Logger.Debug("Snapclient command: {0}", command); task = Cli.Wrap(_SnapClient()) .WithArguments(command) .WithStandardOutputPipe(PipeTarget.ToDelegate(stdOut)) .ExecuteAsync(cancellationTokenSource.Token); } else { // launch experimental .NET port of snapclient: string command = $"-h {SnapSettings.Server} -p {SnapSettings.PlayerPort} -s {device.Index} -i {deviceInstanceId}"; Logger.Debug("SnapClient.Net command: {0}", command); task = Cli.Wrap(_SnapClientDotNet()) .WithArguments(command) .WithStandardOutputPipe(PipeTarget.ToDelegate(stdOut)) .ExecuteAsync(cancellationTokenSource.Token); } Logger.Debug("Snapclient PID: {0}", task.ProcessId); ChildProcessTracker.AddProcess(Process.GetProcessById(task.ProcessId)); // this utility helps us make sure the player process doesn't keep going if our process is killed / crashes try { await task; } catch (CliWrap.Exceptions.CommandExecutionException e) { OnSnapClientErrored?.Invoke(); // add type to ShowNotification (level?), show notification with type and print log at type level Snapcast.Instance.ShowNotification("Snapclient error", _BuildErrorMessage(device, lastLine)); // todo: parse WASAPI error code here and provide human friendly output Logger.Error("Snapclient exited with non-zero exit code. Exception:"); Logger.Error(e.Message); DevicePlayStateChanged?.Invoke(deviceUniqueId, EState.Stopped); m_ActivePlayers.Remove(deviceUniqueId); // settings might have changed while we were playing - refetch them DeviceSettings nDeviceSettings = SnapSettings.GetDeviceSettings(deviceUniqueId); if (nDeviceSettings.AutoRestartOnFailure == true && (attempts <= nDeviceSettings.RestartAttempts || nDeviceSettings.RestartAttempts == 0)) { m_ActivePlayers.Add(deviceUniqueId, cancellationTokenSource); DevicePlayStateChanged?.Invoke(deviceUniqueId, EState.Playing); await _PlayAsync(deviceUniqueId, cancellationTokenSource, attempts + 1).ConfigureAwait(false); } } } } DevicePlayStateChanged?.Invoke(deviceUniqueId, EState.Stopped); m_ActivePlayers.Remove(deviceUniqueId); }
/// <summary> /// Start server (all stdout stuff will end up in RunningLog). /// </summary> /// <exception cref="InformativeException">For some predictable errors.</exception> /// <exception cref="Exception">Process starting might cause loads of problems.</exception> public async Task RunServer(IProgress <AsyncProgressEntry> progress = null, CancellationToken cancellation = default(CancellationToken)) { StopServer(); if (!Enabled) { throw new InformativeException("Can’t run server", "Preset is disabled."); } if (HasErrors) { throw new InformativeException("Can’t run server", "Preset has errors."); } if (TrackId == null) { throw new InformativeException("Can’t run server", "Track is not specified."); } var serverExecutable = GetServerExecutableFilename(); if (!File.Exists(serverExecutable)) { throw new InformativeException("Can’t run server", "Server’s executable not found."); } if (SettingsHolder.Online.ServerPresetsUpdateDataAutomatically) { await PrepareServer(progress, cancellation); } var log = new BetterObservableCollection <string>(); RunningLog = log; try { using (var process = new Process { StartInfo = { FileName = serverExecutable, Arguments = $"-c presets/{Id}/server_cfg.ini -e presets/{Id}/entry_list.ini", UseShellExecute = false, WorkingDirectory = Path.GetDirectoryName(serverExecutable) ?? "", RedirectStandardOutput = true, CreateNoWindow = true, RedirectStandardError = true, } }) { process.Start(); SetRunning(process); ChildProcessTracker.AddProcess(process); progress?.Report(AsyncProgressEntry.Finished); process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.OutputDataReceived += (sender, args) => ActionExtension.InvokeInMainThread(() => log.Add(args.Data)); process.ErrorDataReceived += (sender, args) => ActionExtension.InvokeInMainThread(() => log.Add($@"[color=#ff0000]{args.Data}[/color]")); await process.WaitForExitAsync(cancellation); if (!process.HasExitedSafe()) { process.Kill(); } log.Add($@"[CM] Stopped: {process.ExitCode}"); } } finally { SetRunning(null); } }
//-------------------------------------------------------------------------- // path can be relative to the dll location or absolute public void launchProcess(string executableFilename, string arguments, object environmentVariables, bool hidden, // kill process if our process ends bool killOnClose, Action <object> callback) { Task.Run(() => { try { Process process = new Process(); process.StartInfo.UseShellExecute = false; process.StartInfo.FileName = executableFilename; process.StartInfo.Arguments = arguments; process.StartInfo.CreateNoWindow = hidden; process.StartInfo.WindowStyle = hidden ? ProcessWindowStyle.Hidden : ProcessWindowStyle.Normal; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.RedirectStandardInput = true; process.StartInfo.StandardOutputEncoding = Encoding.UTF8; process.StartInfo.WorkingDirectory = new FileInfo(executableFilename).Directory.FullName; onDataReceivedEvent(new { data = process.StartInfo.WorkingDirectory }); if (environmentVariables != null) { try { var jsonObject = JObject.Parse(environmentVariables.ToString()); foreach (var item in jsonObject) { process.StartInfo.EnvironmentVariables[item.Key] = (string)item.Value; } } catch { callback(new { error = "can't set environment variables" }); return; } } process.ErrorDataReceived += (object sender, DataReceivedEventArgs e) => { if (!String.IsNullOrEmpty(e.Data)) { if (onDataReceivedEvent != null) { onDataReceivedEvent(new { error = e.Data }); } } }; process.OutputDataReceived += (object sender, DataReceivedEventArgs e) => { if (!String.IsNullOrEmpty(e.Data)) { if (onDataReceivedEvent != null) { onDataReceivedEvent(new { data = e.Data }); } } }; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); if (killOnClose) { ChildProcessTracker.AddProcess(process); } lock (this) { _runningProcess.Add(process.Id, new ProcessTrackingInfo() { process = process, track = killOnClose }); } process.EnableRaisingEvents = true; process.Exited += ProcessExited; callback(new { data = process.Id }); } catch (Exception ex) { callback(new { error = "unknown exception: " + ex.ToString() }); } }); }
public static Process Execute(ProcessSetup processSetup) { var exeFile = processSetup.ExeFile; Asserts.True( exeFile.Exists, $"Attempted to execute a program that doesn't exist: {exeFile}"); var args = processSetup.Args; var argString = ""; for (var i = 0; i < args.Length; ++i) { // TODO: Is this safe? var arg = args[i]; if (i > 0) { argString += " "; } argString += arg; } var processStartInfo = new ProcessStartInfo($"\"{exeFile.FullName}\"", argString) { CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true, RedirectStandardInput = true, UseShellExecute = false, }; var process = Asserts.CastNonnull(Process.Start(processStartInfo)); ChildProcessTracker.AddProcess(process); var logger = Logging.Create(exeFile.FullName); if (processSetup.WithLogging) { process.OutputDataReceived += (_, args) => { if (args.Data != null) { logger !.LogInformation(" " + args.Data); } }; process.ErrorDataReceived += (_, args) => { if (args.Data != null) { logger !.LogError(" " + args.Data); } }; } else { process.OutputDataReceived += (_, _) => {}; process.ErrorDataReceived += (_, _) => {}; } process.BeginOutputReadLine(); process.BeginErrorReadLine(); switch (processSetup.Method) { case ProcessExecutionMethod.MANUAL: { break; } case ProcessExecutionMethod.BLOCK: { process.WaitForExit(); break; } default: throw new NotImplementedException(); } // TODO: https://stackoverflow.com/questions/139593/processstartinfo-hanging-on-waitforexit-why /* * using var outputWaitHandle = new AutoResetEvent(false); * using var errorWaitHandle = new AutoResetEvent(false); * * process.OutputDataReceived += (sender, e) => { * if (e.Data == null) { * // ReSharper disable once AccessToDisposedClosure * outputWaitHandle.Set(); * } else { * logger.LogInformation(e.Data); * } * }; * process.ErrorDataReceived += (sender, e) => { * if (e.Data == null) { * // ReSharper disable once AccessToDisposedClosure * errorWaitHandle.Set(); * } else { * logger.LogError(e.Data); * } * }; * * process.Start(); * * process.BeginOutputReadLine(); * process.BeginErrorReadLine(); * * // TODO: Allow passing in timeouts * if (outputWaitHandle.WaitOne() && * errorWaitHandle.WaitOne()) { * process.WaitForExit(); * // Process completed. Check process.ExitCode here. * } else { * // Timed out. * }*/ return(process); }
private async Task RunWrapper(string serverExecutable, ICollection <string> log, IProgress <AsyncProgressEntry> progress, CancellationToken cancellation) { progress.Report(AsyncProgressEntry.FromStringIndetermitate("Loading wrapper…")); var wrapperFilename = await LoadWinWrapper(cancellation); if (cancellation.IsCancellationRequested) { return; } if (wrapperFilename == null) { throw new InformativeException("Can’t run server", "Can’t load server wrapper."); } try { using (var process = ProcessExtension.Start(wrapperFilename, new[] { "-e", serverExecutable, $"presets/{Id}" }, new ProcessStartInfo { UseShellExecute = false, WorkingDirectory = Path.GetDirectoryName(serverExecutable) ?? "", RedirectStandardOutput = true, CreateNoWindow = true, RedirectStandardError = true, StandardOutputEncoding = Encoding.UTF8, StandardErrorEncoding = Encoding.UTF8, })) { process.Start(); SetRunning(process); ChildProcessTracker.AddProcess(process); progress?.Report(AsyncProgressEntry.Finished); process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.OutputDataReceived += (sender, args) => { if (!string.IsNullOrWhiteSpace(args.Data)) { ActionExtension.InvokeInMainThread(() => log.Add(Regex.Replace(args.Data, @"\b(WARNING: .+)", @"[color=#ff8800]$1[/color]"))); } }; process.ErrorDataReceived += (sender, args) => { if (!string.IsNullOrWhiteSpace(args.Data)) { ActionExtension.InvokeInMainThread(() => log.Add($@"[color=#ff0000]{args.Data}[/color]")); } }; await process.WaitForExitAsync(cancellation); if (!process.HasExitedSafe()) { process.Kill(); } log.Add($@"[CM] Stopped: {process.ExitCode}"); } } finally { SetRunning(null); } }
/// <summary> /// Runs a process (executed via shell) with the given arguments and waits for it to finish. /// </summary> /// <param name="ExePath">Path to exe or command to run</param> /// <param name="WorkingDirectory">Directory to execute command within.</param> /// <param name="Arguments">Arguments to pass to command.</param> /// <returns>Exit code returned by the process. If process fails to start -1 is returned.</returns> public static int RunAndWait(string ExePath, string WorkingDirectory, string Arguments, ScriptBuildOutputCallbackDelegate OutputCallback = null) { Logger.Log(LogLevel.Info, LogCategory.Script, "Running (and waiting for result) '{0}' in '{1}' with arguments '{2}'.", ExePath, WorkingDirectory, Arguments); try { ProcessStartInfo StartInfo = new ProcessStartInfo(); StartInfo.FileName = ExePath; StartInfo.WorkingDirectory = WorkingDirectory; StartInfo.Arguments = Arguments; StartInfo.RedirectStandardOutput = true; StartInfo.RedirectStandardError = true; StartInfo.UseShellExecute = false; StartInfo.CreateNoWindow = true; Process process = Process.Start(StartInfo); ChildProcessTracker.AddProcess(process); /*process.OutputDataReceived += delegate (object sender, DataReceivedEventArgs e) * { * OutputLineBuilder.Add(e.Data); * while (true) * { * string Line = OutputLineBuilder.Read(); * if (Line == null) * { * break; * } * Logger.Log(LogLevel.Info, LogCategory.Main, "{0}", Line); * } * * OutputCallback?.Invoke(e.Data); * }; * process.ErrorDataReceived += delegate (object sender, DataReceivedEventArgs e) * { * while (true) * { * string Line = ErrorLineBuilder.Read(); * if (Line == null) * { * break; * } * Logger.Log(LogLevel.Info, LogCategory.Main, "{0}", Line); * } * * OutputCallback?.Invoke(e.Data); * }; * * //process.BeginErrorReadLine(); * //process.BeginOutputReadLine(); */ Func <StreamReader, ConcurrentQueue <string>, bool> QueueBuilder = (StreamReader Reader, ConcurrentQueue <string> Queue) => { int Char = Reader.Read(); if (Char < 0) { return(true); } string Value = new string((char)Char, 1); Queue.Enqueue(Value); return(false); }; Func <ConcurrentQueue <string>, LineBuilder, bool> Parser = (ConcurrentQueue <string> Queue, LineBuilder Builder) => { while (Queue.Count > 0) { string Value = ""; if (Queue.TryDequeue(out Value)) { Builder.Add(Value); while (true) { string Line = Builder.Read(); if (Line == null) { break; } Logger.Log(LogLevel.Info, LogCategory.Main, "{0}", Line); } OutputCallback?.Invoke(Value); } } return(true); }; Func <LineBuilder, bool> DrainBuilder = (LineBuilder Builder) => { Builder.End(); while (true) { string Line = Builder.Read(); if (Line == null) { break; } Logger.Log(LogLevel.Info, LogCategory.Main, "{0}", Line); } return(true); }; LineBuilder OutputLineBuilder = new LineBuilder(); LineBuilder ErrorLineBuilder = new LineBuilder(); // This is retarded, the blocking api for all of this in C# is s***e. ConcurrentQueue <string> OutputData = new ConcurrentQueue <string>(); ConcurrentQueue <string> ErrorData = new ConcurrentQueue <string>(); Task OutputTask = Task.Run(() => { while (!QueueBuilder(process.StandardOutput, OutputData)) { ; } }); Task ErrorTask = Task.Run(() => { while (!QueueBuilder(process.StandardError, ErrorData)) { ; } }); // Wait for process to exit. while (!OutputTask.IsCompleted || !ErrorTask.IsCompleted || OutputData.Count > 0 || ErrorData.Count > 0) { Parser(OutputData, OutputLineBuilder); Parser(ErrorData, ErrorLineBuilder); Thread.Sleep(1); } process.WaitForExit(); // Drain any output. DrainBuilder(OutputLineBuilder); DrainBuilder(ErrorLineBuilder); Logger.Log(LogLevel.Info, LogCategory.Script, "Finished running with exit code {0}.", process.ExitCode); return(process.ExitCode); } catch (Exception Ex) { Logger.Log(LogLevel.Error, LogCategory.Script, "Failed to run program with error: {0}", Ex.Message.ToString()); return(-1); } }
/// <summary> /// </summary> public bool Launch(string LocalFolder, ref string ResultMessage) { if (ScriptInstance != null) { CopyArgumentsToScript(); if (!ScriptInstance.Launch(MakeScriptBuild())) { ResultMessage = "Script failed to launch, check console output window for details."; return(false); } return(true); } else { // This is now done in launch dialog or manifest downloader. /*if (InstallSteps.Count != 0) * { * if (!Install(LocalFolder, ref ResultMessage)) * { * return false; * } * }*/ string ExePath = BuildSettings.ExpandArguments(Executable, Variables); if (!Path.IsPathRooted(ExePath)) { ExePath = Path.Combine(LocalFolder, ExePath); } string WorkingDir = BuildSettings.ExpandArguments(WorkingDirectory, Variables); if (WorkingDir.Length == 0) { WorkingDir = Path.GetDirectoryName(ExePath); } else { if (!Path.IsPathRooted(WorkingDir)) { WorkingDir = Path.Combine(LocalFolder, WorkingDir); } } #if SHIPPING if (!File.Exists(ExePath)) { ResultMessage = "Could not find executable, expected to be located at: " + ExePath; return(false); } if (!Directory.Exists(WorkingDir)) { ResultMessage = "Could not find working directory, expected at: " + WorkingDir; return(false); } #endif string CompiledArguments = ""; try { CompiledArguments = CompileArguments(); } catch (InvalidOperationException Ex) { ResultMessage = "Error encountered while evaluating launch settings:\n\n" + Ex.Message; return(false); } Logger.Log(LogLevel.Info, LogCategory.Main, "Executing: {0} {1}", ExePath, CompiledArguments); try { ProcessStartInfo StartInfo = new ProcessStartInfo(); StartInfo.FileName = ExePath; StartInfo.WorkingDirectory = WorkingDir; StartInfo.Arguments = CompiledArguments; //StartInfo.RedirectStandardOutput = true; //StartInfo.RedirectStandardError = true; StartInfo.UseShellExecute = false; StartInfo.CreateNoWindow = true; Process process = Process.Start(StartInfo); ChildProcessTracker.AddProcess(process); //process.WaitForExit(); /*process.OutputDataReceived += delegate (object sender, DataReceivedEventArgs e) * { * Logger.Log(LogLevel.Info, LogCategory.Main, "{0}", e.Data); * }; * * process.ErrorDataReceived += delegate (object sender, DataReceivedEventArgs e) * { * Logger.Log(LogLevel.Info, LogCategory.Main, "{0}", e.Data); * }; * * process.BeginErrorReadLine(); * process.BeginOutputReadLine();*/ } catch (Exception Ex) { ResultMessage = "Failed to start executable with error:\n\n" + Ex.Message; return(false); } } return(true); }
public void Add(IProcess process) => ChildProcessTracker.AddProcess(process.Unwrap());