private void IPCOnMessage(object sender, MessageReceivedEventArgs e) { var actionData = Action.FromJson(e.Message); switch (actionData?.Type) { case ActionTypes.Acknowledged: OnAcknowledged?.Invoke(this, new EventArgs()); break; case ActionTypes.ClearConsole: OnClearConsole?.Invoke(this, new EventArgs()); break; case ActionTypes.Output: OnOutput?.Invoke(this, new Events.Output(actionData.Body)); break; case ActionTypes.GetSettings: OnSettings?.Invoke(this, new Events.Settings(this, e.Message)); break; case ActionTypes.UpdateSettingFailed: OnUpdateSettingFailure?.Invoke(this, new Events.SettingUpdateFailed(actionData.Body)); break; } }
public IntcodeComputer(IEnumerable <long> code) { var instructions = code.Select((x, i) => (x, (long)i)).ToDictionary(x => x.Item2, x => x.x); Program = new Program(instructions, _input); Program.OnOutput += l => { OnOutput?.Invoke(l); }; }
/// <summary> /// Reads the process output from an handle /// </summary> private void ReadOutput(IntPtr readHandle) { // Buffer & read length byte[] buffer = new byte[ReadBufferSize]; uint dwRead = 0; // Read as long as the process is available (not closed..) while (ReadFile(readHandle, buffer, ReadBufferSize, ref dwRead, IntPtr.Zero)) { // For every buffer lines foreach (string line in Encoding.UTF8.GetString(buffer, 0, Convert.ToInt32(dwRead)).Split(Environment.NewLine)) { // If the line isn't empty if (!string.IsNullOrEmpty(line)) { // Trigger event OnOutput?.Invoke(this, line.Trim()); } } // Reset buffer buffer = new byte[ReadBufferSize]; } // Close read handle CloseHandle(readHandle); }
public ConsoleProcess(string cmd, string[] args, bool relativeToAssemblyDir = true, OnExit onExit = null, OnOutput onOutput = null, OnError onError = null) { if (!File.Exists(cmd)) { Error("The executable {0} could not be found.", cmd); return; } Process = new Process(); Cmd = relativeToAssemblyDir ? Path.Combine(AssemblyDirectory.FullName, cmd) : cmd; Args = args; OnExit = onExit; OnOutput = onOutput; OnError = onError; Process.StartInfo = new ProcessStartInfo(cmd, string.Join(" ", args)) { UseShellExecute = false, RedirectStandardError = true, RedirectStandardInput = false, RedirectStandardOutput = true }; Process.EnableRaisingEvents = true; Process.OutputDataReceived += Process_OutputDataReceived; Process.ErrorDataReceived += Process_ErrorDataReceived; Process.Exited += Process_Exited; Process.Disposed += Process_Disposed; Initialized = true; }
public async Task <Res> CmdAsync <Res>(CommandModel cmd) where Res : class { if (cmd.ResultType != CommandType.NoResult) { _operations.Add(cmd); } if (cmd.Cmd != DebuggerCommandEnum.custom) { _transport.Send($"{cmd.Cmd} {cmd.Arg}"); OnOutput?.Invoke($"<--{cmd.Cmd} {cmd.Arg}"); } else { _transport.Send(cmd.Arg); OnOutput?.Invoke($"<--{cmd.Arg}"); } _lasCommand = cmd.Cmd; if (cmd.ResultType != CommandType.NoResult) { cmd.Wait(); return(cmd.Result as Res); } return(null); }
private void PrintPriceBook(OrderCollection orders) { var sellPrices = new SortedDictionary <int, int>(new DescendingComparer <int>()); var buyPrices = new SortedDictionary <int, int>(new DescendingComparer <int>()); foreach (var order in orders.AsEnumerable()) { if (order.Type == OrderType.SELL) { AddToOrderSummary(order, sellPrices); } else if (order.Type == OrderType.BUY) { AddToOrderSummary(order, buyPrices); } } OnOutput?.Invoke("SELL:"); foreach (var item in sellPrices) { OnOutput?.Invoke($"{item.Key} {item.Value}"); } OnOutput?.Invoke("BUY:"); foreach (var item in buyPrices) { OnOutput?.Invoke($"{item.Key} {item.Value}"); } }
public void Post(int input) { _cpu.SetInput(input); bool ran = false; while (!_cpu.IsHalted) { ran = true; _cpu.RunOnce(); if (_cpu.Instruction.Op == OpCode.Read) { OnOutput?.Invoke(this, _cpu.CurrentOutputValue); break; } } if (ShouldPassMessageForward(ran)) // not a terminated E { _linkedTo?.Post(_cpu.CurrentOutputValue); } else if (_cpu.IsHalted) { OnOutput?.Invoke(this, _cpu.CurrentOutputValue); } }
public OUTPUT Process(INPUT input) { OnInput?.Invoke(input); var output = _innerStep.Process(input); OnOutput?.Invoke(output); return(output); }
public void Set(Action <Job, TSchema> action) { this._action = action; _actionDisposable = OnOutput.Subscribe(row => { _action?.Invoke(this.Job, row); }); }
private void ProcessOutput(bool saveOutput = false) { List <string> errorData = new List <string>(); List <string> outputData = new List <string>(); string errorLine; while (_errorData.TryDequeue(out errorLine)) { errorData.Add(errorLine); } string outputLine; while (_outputData.TryDequeue(out outputLine)) { outputData.Add(outputLine); } _outputProcessEvent.Reset(); if (errorData.Any()) { foreach (var item in errorData) { if (item == null) { continue; } OnOutput?.Invoke(this, item); if (saveOutput) { _output.AppendLine(item); } } } if (outputData.Any()) { foreach (var item in outputData) { if (item == null) { continue; } OnOutput?.Invoke(this, item); if (saveOutput) { _output.AppendLine(item); } } } }
protected AssetRequest(string url, int timeout = 60, int retryCount = 1) : base( $"{(url.StartsWith("http", StringComparison.OrdinalIgnoreCase) ? "" : (url.StartsWith("file:", StringComparison.OrdinalIgnoreCase) ? "" : "file://"))}{url}", timeout: timeout, retryCount: retryCount ) { base.OnFinished += (req) => OnOutput?.Invoke(Output); }
/// <summary> /// The process that invokes the step and optionally invokes pre and post actions /// </summary> /// <param name="input"></param> /// <returns></returns> public TOutput Process(TInput input) { OnInput?.Invoke(input); var output = _innerStep.Process(input); OnOutput?.Invoke(output); return(output); }
async void Output(string content) { await Helper.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { content.PrintDebug(); //ResultText.Text = content; }); OnOutput?.Invoke(content); }
/// <summary> /// Execute the process step /// </summary> /// <param name="input"></param> /// <returns></returns> public TOutput Process(TInput input) { OnInput?.Invoke(input); var output = ProcessStep(input); OnOutput?.Invoke(output); return(output); }
private void Process_OutputDataReceived(object sender, DataReceivedEventArgs e) { if (CancellationToken.IsCancellationRequested && !Process.HasExited) { Stop(); return; } if (!string.IsNullOrEmpty(e.Data)) { Debug(e.Data); OutputBuilder.AppendLine(e.Data); OnOutput?.Invoke(e.Data); } }
private void Output(IEnumerable <object> objects) { if (objects == null) { return; } foreach (var obj in objects) { if (obj != null) { OnOutput?.Invoke(this, obj); } } }
private async Task ResizeTask() { while (true) { TimeSpan delay; TerminalSize size = null; lock (_resizeLock) { if (_requestedSize?.EquivalentTo(_setSize) ?? true) { // Resize finished. Unblock output and exit. if (_outputBlockedBuffer != null) { OnOutput?.Invoke(this, _outputBlockedBuffer.ToArray()); _outputBlockedBuffer.Dispose(); _outputBlockedBuffer = null; } _resizeTask = null; break; } delay = _resizeScheduleTime.Subtract(DateTime.UtcNow); // To avoid sleeping for only few milliseconds we're introducing a threshold of 10 milliseconds if (delay.TotalMilliseconds < 10) { _setSize = size = _requestedSize; if (_outputBlockedBuffer == null) { _outputBlockedBuffer = new MemoryStream(); } } } if (size == null) { await Task.Delay(delay).ConfigureAwait(false); } else { await ViewModel.Terminal.SetSizeAsync(_requestedSize).ConfigureAwait(false); } } }
/// <summary> /// Triggered when we receive process output that needs to be forwarded to events /// </summary> private void ForwardOutput(string message) { // If message is a normal output if (message.Contains("[notice]")) { // Trigger event OnOutput?.Invoke(this, message); } else { // Trigger event OnErrorOutput?.Invoke(this, message); } }
private void ApplyTrades(OrderCollection orders) { Order firstOrder, secondOrder; while (FindNextTrade(orders, out firstOrder, out secondOrder)) { var tradedQuantity = Math.Min(firstOrder.Quantity, secondOrder.Quantity); orders.MergeOrders(firstOrder, secondOrder); OnTradeHappened?.Invoke(firstOrder.ID, firstOrder.Price, tradedQuantity, secondOrder.ID, secondOrder.Price, tradedQuantity); OnOutput?.Invoke($"{KW_TRADE} {firstOrder.TradeInfo(tradedQuantity)} {secondOrder.TradeInfo(tradedQuantity)}"); } }
private void createEditor(int depth, CR2WExportWrapper c) { try { if (ChunkEditors.ContainsKey(c)) { return; } var editor = GetEditor(c); editor.Chunk = c; editor.OnSelectChunk += editor_OnSelectChunk; editor.OnManualMove += editor_OnMove; editor.LocationChanged += editor_LocationChanged; editor.OriginalSize = editor.Size; Controls.Add(editor); ChunkEditors.Add(c, editor); if (depth > maxdepth) { maxdepth = depth; } if (!EditorLayout.ContainsKey(depth)) { EditorLayout.Add(depth, new List <ChunkEditor>()); } EditorLayout[depth].Add(editor); var conns = editor.GetConnections(); if (conns != null) { foreach (var conn in conns) { if (conn.Reference != null) { createEditor(depth + 1, conn.Reference); } } } } catch (Exception e) { OnOutput.Invoke(this, e.ToString()); } }
private void Terminal_OutputReceived(object sender, byte[] e) { if (_terminalClosed) { return; } lock (_resizeLock) { if (_outputBlockedBuffer != null) { _outputBlockedBuffer.Write(e, 0, e.Length); return; } } OnOutput?.Invoke(this, e); }
private void Terminal_OutputReceived(object sender, byte[] e) { if (_outputBlocked.IsSet) { // Output to the terminal is currently blocked. Hold on to the output. _outputBlockedBuffer.Write(e, 0, e.Length); } else { // Output to the terminal is not blocked. Send any previously // buffered output first, and then the output for the current // event. if (_outputBlockedBuffer.Length > 0) { OnOutput?.Invoke(this, _outputBlockedBuffer.ToArray()); _outputBlockedBuffer.SetLength(0); } OnOutput?.Invoke(this, e); } }
public Program(string command) { string fileName, argments; if (command[0] == '\"') { fileName = new string(command.Skip(1).TakeWhile(c => c != '\"').ToArray()); argments = new string(command.Skip(1).SkipWhile(c => c != '\"').Skip(1).ToArray()); } else { fileName = command.Split(' ').First(); argments = string.Join(" ", command.Split(' ').Skip(1)); } process = new Process() { StartInfo = new ProcessStartInfo() { FileName = fileName, Arguments = argments, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, }, EnableRaisingEvents = true, }; void OnOutputHandle(object sender, DataReceivedEventArgs e) { lock (outputs) { outputs.Add(e.Data); OnOutput?.Invoke(e.Data); } } process.OutputDataReceived += OnOutputHandle; process.ErrorDataReceived += OnOutputHandle; process.Exited += (_, e) => OnExit?.Invoke(); }
protected void RaiseOnOutput(T data) { RaiseOnData(data); OnOutput?.Invoke(data); }
private string runInternal(string command, string args, string workingDirectory, bool redirectOutput) { var output = new StringBuilder(); logger.LogInformation("Running {0} {1}", command, args); var process = new Process() { StartInfo = { FileName = command } }; if (args != null) { process.StartInfo.Arguments = args; } if (workingDirectory != null) { process.StartInfo.WorkingDirectory = workingDirectory; } process.StartInfo.RedirectStandardOutput = redirectOutput; process.StartInfo.RedirectStandardError = redirectOutput; process.StartInfo.UseShellExecute = false; process.OutputDataReceived += (sender, eventArgs) => { if (eventArgs.Data == null) { return; } output.AppendLine(eventArgs.Data); logger.LogInformation(" [O] {0}", eventArgs.Data); OnOutput?.Invoke(this, new OutputEventArg(eventArgs.Data)); }; process.ErrorDataReceived += (sender, eventArgs) => { if (eventArgs.Data == null) { return; } logger.LogInformation(" [E] {0}", eventArgs.Data); OnError?.Invoke(this, new OutputEventArg(eventArgs.Data)); }; process.Start(); EventHandler <ProcessIdEventArg> onProcessCreated = this.OnProcessCreated; onProcessCreated?.Invoke(this, new ProcessIdEventArg(process.Id)); if (redirectOutput) { process.BeginOutputReadLine(); } process.WaitForExit(); OnProcessTerminated?.Invoke(this, new TerminatedProcessEventArg(process.StartTime, process.ExitTime, process.ExitCode)); return(output.ToString()); }
void WriteLine(string line) { OnOutput?.Invoke(this, line); }
public override void Write(char value) { OnOutput?.Invoke(value); }
void IInternalGraphAccess.OutputExecuted(OutputNode p_node, NodeFlowData p_flowData) { OnOutput?.Invoke(p_node, p_flowData); }
private void Execute(Arguments args) { var memory = Memory; var ins = Instruction; switch (Instruction.Op) { case Add: memory[args.TargetIndex] = args.Arg1 + args.Arg2; CurrentOffset += OpCodeArgLength(ins.Op) + 1; break; case Mul: memory[args.TargetIndex] = args.Arg1 * args.Arg2; CurrentOffset += OpCodeArgLength(ins.Op) + 1; break; case Write: memory[args.TargetIndex] = Phase.GetValueOrDefault(nextInput); Phase = null; CurrentOffset += 2; break; case OpCode.Read: CurrentOutputValue = args.Arg1; CurrentOffset += OpCodeArgLength(ins.Op) + 1; OnOutput?.Invoke(this, CurrentOutputValue); break; case JumpIfTrue: if (args.Arg1 != 0) { CurrentOffset = args.Arg2; } else { CurrentOffset += OpCodeArgLength(ins.Op) + 1; } break; case JumpIfFalse: if (args.Arg1 == 0) { CurrentOffset = args.Arg2; } else { CurrentOffset += OpCodeArgLength(ins.Op) + 1; } break; case LT: memory[args.TargetIndex] = args.Arg1 < args.Arg2 ? 1 : 0; CurrentOffset += OpCodeArgLength(ins.Op) + 1; break; case E: memory[args.TargetIndex] = args.Arg1 == args.Arg2 ? 1 : 0; CurrentOffset += OpCodeArgLength(ins.Op) + 1; break; case AdjustRelativeBase: RelativeBaseOffset += args.Arg1; CurrentOffset += OpCodeArgLength(ins.Op) + 1; break; case OpCode.Halt: break; } }
public void Output(string output) => OnOutput?.Invoke(output);