Beispiel #1
0
 private void WriteOutput(object sender, DataReceivedEventArgs e)
 {
     if (OutputDataReceived != null)
     {
         OutputDataReceived.Invoke(sender, e);
     }
 }
Beispiel #2
0
 private void Cli_OutputDataReceived(object sender, DataReceivedEventArgs e)
 {
     if (e.Data != null)
     {
         OutputDataReceived?.Invoke(sender, e);
     }
 }
Beispiel #3
0
 private void Process_OutputDataReceived(object sender, DataReceivedEventArgs e)
 {
     if (e.Data != null)
     {
         OutputDataReceived?.Invoke(this, new EventArgs <string>(e.Data));
     }
 }
Beispiel #4
0
        private void TraceIbLauncherLogFile()
        {
            var ibLauncherLogFile = Path.Combine(_ibDirectory, "launcher.log");

            if (File.Exists(ibLauncherLogFile))
            {
                OutputDataReceived?.Invoke(this, new OutputDataReceivedEventArgs($"IB launcher log file: {ibLauncherLogFile}"));

                try
                {
                    using (var fileStream = new FileStream(ibLauncherLogFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    {
                        fileStream.Seek(0, SeekOrigin.Begin);

                        using (var reader = new StreamReader(fileStream))
                        {
                            string line;
                            while ((line = reader.ReadLine()) != null)
                            {
                                OutputDataReceived?.Invoke(this, new OutputDataReceivedEventArgs($"[IB Launcher] {line}"));
                            }
                        }
                    }
                }
                catch (Exception exception)
                {
                    OutputDataReceived?.Invoke(this, new OutputDataReceivedEventArgs($"Error reading IB launcher log file: {exception.Message}"));
                }
            }
        }
Beispiel #5
0
        public static void RunCommand(string command)
        {
            var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName               = "cmd.exe",
                    UseShellExecute        = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true,
                    CreateNoWindow         = true
                }
            };

            process.StartInfo.EnvironmentVariables["Path"] = EnvPath;
            string commandMode = "/C";

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                process.StartInfo.FileName = "/bin/bash";
                commandMode = "-c";
            }
            process.StartInfo.Arguments = $"{commandMode} {command}";
            process.OutputDataReceived += (s, e) => OutputDataReceived?.Invoke(e.Data);
            process.ErrorDataReceived  += (s, e) => ErrorDataReceived?.Invoke(e.Data);
            process.Start();
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();
            process.WaitForExit();
        }
Beispiel #6
0
        private void Print(bool fromBeginning, bool error, string message)
        {
            if (fromBeginning && ((message.Length == 0) || (message[0] != '\n')))
            {
                _lastFromBeginning = message;
                _logger.WriteLine("Buffered from-beginning message [{0}]", _lastFromBeginning);

                OutputDataReceived?.Invoke(this, null);
            }
            else
            {
                if (!string.IsNullOrEmpty(_lastFromBeginning))
                {
                    AddToOutput(_lastFromBeginning, false);
                    _lastFromBeginning = null;
                }

                if (fromBeginning && (message.Length > 0) && (message[0] == '\n'))
                {
                    AddToOutput("\n", false);
                    _lastFromBeginning = message.Substring(1);
                    _logger.WriteLine("Buffered from-beginning message [{0}]", _lastFromBeginning);
                }
                else
                {
                    AddToOutput(message, error);
                }
            }
        }
Beispiel #7
0
        private void OnStart()
        {
            OnStartException = null;
            try
            {
                var processStartInfo = new ProcessStartInfo(_processPath)
                {
                    Arguments = _arguments,
                    RedirectStandardOutput = true,
                    RedirectStandardError  = _captureStdErr,
                    UseShellExecute        = false,
                    CreateNoWindow         = true,
                    WorkingDirectory       = _workingDirectory
                };

                // Copy over environment variables
                if (_environmentVariables != null)
                {
                    foreach (string key in _environmentVariables.Keys)
                    {
                        processStartInfo.EnvironmentVariables[key] = _environmentVariables[key];
                    }
                }

                // Start the process and capture it's output.
                _process = new Process
                {
                    StartInfo           = processStartInfo,
                    EnableRaisingEvents = true
                };
                _process.OutputDataReceived += (_, args) => OutputDataReceived?.Invoke(args.Data);
                if (_captureStdErr)
                {
                    _process.ErrorDataReceived += (_, args) => ErrorDataReceived?.Invoke(args.Data);
                }
                _process.Exited += (sender, args) =>
                {
                    lock (_lockObject)
                    {
                        _processStateMachine.FireAsync(Trigger.ProcessExit);
                    }
                }; // Multi-threaded access ?
                _process.Start();
                _process.BeginOutputReadLine();
                if (_captureStdErr)
                {
                    _process.BeginErrorReadLine();
                }

                ProcessInfo = new ProcessInfo(_process);
            }
            catch (Exception ex)
            {
                _logger.ErrorException("Failed to start process.", ex);
                lock (_lockObject)
                {
                    _processStateMachine.Fire(_startErrorTrigger, ex);
                }
            }
        }
Beispiel #8
0
 private void OnOutputDataReceived(object sender, DataReceivedEventArgs e)
 {
     // at the end of the process, the event fires one last time with null
     if (e.Data != null)
     {
         OutputDataReceived?.Invoke(sender, e);
     }
 }
Beispiel #9
0
 private void ProcessDataReceived(object sender, DataReceivedEventArgs e)
 {
     OutputDataReceived?.Invoke(sender, e);
     if (ForwardDataAndError && e.Data != null)
     {
         Console.WriteLine(e.Data);
     }
 }
Beispiel #10
0
 private void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
 {
     if (!String.IsNullOrEmpty(outLine.Data))
     {
         LastOutString = outLine.Data;
         waitData?.Enqueue(outLine.Data);
         OutputDataReceived?.Invoke(outLine.Data);
     }
 }
Beispiel #11
0
        private void RaiseOutputDataReceived(DataReceivedEventArgs e)
        {
            if (e == null)
            {
                return;
            }

            OutputDataReceived.Raise(this, e);
            OnOutputDataReceived(e.Data);
        }
Beispiel #12
0
        private void AddToOutput(string message, bool error)
        {
            string[] lines = (_incompleteLine + message).Split(new[] { '\n' });

            _incompleteLine = lines[lines.Length - 1];

            for (int i = 0; i < lines.Length - 1; ++i)
            {
                OutputDataReceived?.Invoke(this, new OutputDataReceivedEventArgs(lines[i], error));
            }
        }
Beispiel #13
0
 private void Process_OutputDataReceived(object sender, DataReceivedEventArgs e)
 {
     try
     {
         OutputDataReceived?.Invoke(sender, e);
         Output(OutputProcessor?.ParseOutput(this, e.Data));
     }
     catch (Exception ex)
     {
         OnError?.Invoke(this, ex);
     }
 }
Beispiel #14
0
 private void Process_OutputDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e)
 {
     if (!string.IsNullOrWhiteSpace(e.Data))
     {
         if (outputToConsole)
         {
             Console.Error.WriteLine(e.Data);
         }
         OutputDataReceived?.Invoke(this, new DataReceivedEventArgs(e.Data));
         outputLines.Add(e.Data);
     }
 }
Beispiel #15
0
 private void FireOutputDataReceived(object sender, TaskDataReceivedEventArgs e)
 {
     if (InvokeRequired)
     {
         FireOutputDataReceivedCallback d = new FireOutputDataReceivedCallback(FireOutputDataReceived);
         this?.Invoke(d, new object[] { sender, e });
     }
     else
     {
         OutputDataReceived?.Invoke(sender, e);
     }
 }
Beispiel #16
0
        private void LogReaderTimerCallback(object _)
        {
            try
            {
                lock (_logLocker)
                {
                    if (string.IsNullOrWhiteSpace(_ibGatewayLogFileName) || !File.Exists(_ibGatewayLogFileName))
                    {
                        return;
                    }

                    using (var fileStream = new FileStream(_ibGatewayLogFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    {
                        fileStream.Seek(0, SeekOrigin.Begin);

                        using (var reader = new StreamReader(fileStream))
                        {
                            var    lines = new List <string>();
                            string line;
                            while ((line = reader.ReadLine()) != null)
                            {
                                lines.Add(line);
                            }

                            var totalLines = lines.Count;
                            if (totalLines < _logLinesRead)
                            {
                                // log file was rewritten by a restart of IBGateway
                                _logLinesRead = 0;
                            }

                            var newLinesCount = totalLines - _logLinesRead;
                            var newLines      = lines.Skip(_logLinesRead).Take(newLinesCount);
                            _logLinesRead = totalLines;

                            if (newLinesCount > 0)
                            {
                                foreach (var newLine in newLines)
                                {
                                    OnProcessOutputDataReceived(newLine);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                var message = $"IBAutomater error in timer - Message: {exception.Message}";
                OutputDataReceived?.Invoke(this, new OutputDataReceivedEventArgs(message));
            }
        }
        public CWrapper(string executable, WrapperSettings settings, BufferHandler bufferHandler)
        {
            Settings = settings ?? throw new ArgumentNullException(nameof(settings));

            _bufferHandler = bufferHandler;
            Executable     = executable;
            Settings.Lock();

            ProcessStartInfo startInfo = new ProcessStartInfo()
            {
                FileName               = Executable,
                UseShellExecute        = false,
                CreateNoWindow         = !Settings.ShowWindow,
                RedirectStandardError  = Settings.RedirectStandardError,
                RedirectStandardInput  = Settings.RedirectStandardInput,
                RedirectStandardOutput = Settings.RedirectStandardOutput,
                StandardOutputEncoding = Settings.EncodingSettings.StandardOutputEncoding,
                StandardErrorEncoding  = Settings.EncodingSettings.StandardErrorEncoding,
                WorkingDirectory       = Settings.WorkingDirectory
            };

            _wrappedProcess = new Process
            {
                StartInfo           = startInfo,
                EnableRaisingEvents = true
            };

            _wrappedProcess.OutputDataReceived += (s, e) =>
            {
                OutputDataReceived?.Invoke(s, e);
                if (_bufferHandler != null)
                {
                    _bufferHandler.OutputDataWriter.WriteLine(e.Data);
                }
                OutputDataMRE.Set();
            };
            _wrappedProcess.ErrorDataReceived += (s, e) =>
            {
                ErrorDataReceived?.Invoke(s, e);
                if (_bufferHandler != null)
                {
                    _bufferHandler.ErrorDataWriter.WriteLine(e.Data);
                }
                ErrorDataMRE.Set();
            };
            _wrappedProcess.Exited += (s, e) =>
            {
                Executing = false;
                Exited?.Invoke(s, DateTime.Now);
                ExitedMRE.Set();
            };
        }
Beispiel #18
0
        private void OnCompilerOutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(e?.Data))
            {
                return;
            }

            MatchErrors(e.Data);

            MatchWarnings(e.Data);

            OutputDataReceived?.Invoke(sender, e.Data);
        }
Beispiel #19
0
        public void Start()
        {
            if (IsRunning)
            {
                return;
            }

            Service = new Process();
            Service.StartInfo.FileName        = NodeJS.FullName;
            Service.StartInfo.Arguments       = Arguments;
            Service.StartInfo.UseShellExecute = false;
            Service.StartInfo.CreateNoWindow  = true;

            if (EnvironmentForProcess != null)
            {
                foreach (var entry in EnvironmentForProcess)
                {
                    Service.StartInfo.EnvironmentVariables[entry.Key] = entry.Value ?? string.Empty;
                }
            }

            Service.StartInfo.RedirectStandardOutput = true;
            Service.OutputDataReceived += (sender, e) => OutputDataReceived?.Invoke(this, e);

            bool   isLaunched = false;
            string msgTxt     =
                $"The local appium server has not been started. The given Node.js executable: {NodeJS.FullName} Arguments: {Arguments}. " +
                "\n";

            try
            {
                Service.Start();

                Service.BeginOutputReadLine();
            }
            catch (Exception e)
            {
                DestroyProcess();
                throw new AppiumServerHasNotBeenStartedLocallyException(msgTxt, e);
            }

            isLaunched = Ping(InitializationTimeout);
            if (!isLaunched)
            {
                DestroyProcess();
                throw new AppiumServerHasNotBeenStartedLocallyException(
                          msgTxt +
                          $"Time {InitializationTimeout.TotalMilliseconds} ms for the service starting has been expired!");
            }
        }
Beispiel #20
0
        private void UpdateIbGatewayConfiguration(string ibGatewayVersionPath, bool enableJavaAgent)
        {
            // update IBGateway configuration file with Java agent entry
            var ibGatewayConfigFile = $"{ibGatewayVersionPath}/ibgateway.vmoptions";

            OutputDataReceived?.Invoke(this, new OutputDataReceivedEventArgs($"Updating IBGateway configuration file: {ibGatewayConfigFile}"));

            var jarPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            var javaAgentConfigFileName = Path.Combine(jarPath, "IBAutomater.json");
            var javaAgentConfig         = $"-javaagent:{jarPath}/IBAutomater.jar={javaAgentConfigFileName}";

            var lines    = File.ReadAllLines(ibGatewayConfigFile).ToList();
            var existing = false;

            for (var i = 0; i < lines.Count; i++)
            {
                var line = lines[i];

                if (line.StartsWith("-javaagent:") && line.Contains("IBAutomater"))
                {
                    if (enableJavaAgent)
                    {
                        lines[i] = javaAgentConfig;
                    }
                    else
                    {
                        lines.RemoveAt(i--);
                    }

                    existing = true;
                }
            }

            if (enableJavaAgent && !existing)
            {
                lines.Add(javaAgentConfig);
            }

            File.WriteAllLines(ibGatewayConfigFile, lines);

            if (enableJavaAgent)
            {
                File.WriteAllText(javaAgentConfigFileName, $"{_userName}\n{_password}\n{_tradingMode}\n{_portNumber}\n{_exportIbGatewayLogs}");
            }
            else
            {
                File.Delete(javaAgentConfigFileName);
            }
        }
Beispiel #21
0
 public void ReadSync()
 {
     try
     {
         while (true)
         {
             string line = Reader.ReadLine();
             OutputDataReceived?.Invoke(line);
         }
     }
     catch (IOException exception)
     {
         CloseAndNotify();
     }
 }
Beispiel #22
0
        private void OnStart()
        {
            Exception = null;
            try
            {
                var processStartInfo = new ProcessStartInfo(_processPath)
                {
                    Arguments = _arguments,
                    RedirectStandardOutput = true,
                    UseShellExecute        = false,
                    CreateNoWindow         = true,
                    WorkingDirectory       = _workingDirectory
                };

                // Copy over environment variables
                if (_environmentVariables != null)
                {
                    foreach (string key in _environmentVariables.Keys)
                    {
                        processStartInfo.EnvironmentVariables.Add(key, _environmentVariables[key]);
                    }
                }

                if (_parentProcessId.HasValue)
                {
                    processStartInfo.EnvironmentVariables.Add(
                        Constants.ProcessIdEnvironmentVariable,
                        _parentProcessId.Value.ToString());
                }

                // Start the process and capture it's output.
                _process = new Process
                {
                    StartInfo           = processStartInfo,
                    EnableRaisingEvents = true
                };
                _process.OutputDataReceived += (_, args) => OutputDataReceived?.Invoke(args.Data);
                _process.Exited             += (sender, args) => _processStateMachine.Fire(Trigger.ProcessExit);
                _process.Start();
                _process.BeginOutputReadLine();
                ProcessInfo = new ProcessInfo(_process);
            }
            catch (Exception ex)
            {
                _logger.ErrorException("Failed to start process.", ex);
                _processStateMachine.Fire(_startErrorTrigger, ex);
            }
        }
Beispiel #23
0
        private void LoadIbServerInformation()
        {
            // After a successful login, IBGateway saves the connected/redirected host name to the Peer key in the jts.ini file.
            var iniFileName = Path.Combine(_ibDirectory, "jts.ini");

            // Note: Attempting to connect to a different server via jts.ini will not change anything.
            // IB will route you back to the server they have set for you on their server side.
            // You need to request a server change and only then will your system connect to the changed server address.

            if (File.Exists(iniFileName))
            {
                const string key = "Peer=";
                foreach (var line in File.ReadLines(iniFileName))
                {
                    if (line.StartsWith(key))
                    {
                        var value = line.Substring(key.Length);
                        _ibServerName = value.Substring(0, value.IndexOf(':'));

                        if (!_ibServerMap.TryGetValue(_ibServerName, out _ibServerRegion))
                        {
                            _ibServerRegion = Region.America;

                            ErrorDataReceived?.Invoke(this, new ErrorDataReceivedEventArgs(
                                                          $"LoadIbServerInformation(): Unknown server name: {_ibServerName}, region set to {_ibServerRegion}"));
                        }

                        // known server name and region
                        OutputDataReceived?.Invoke(this, new OutputDataReceivedEventArgs(
                                                       $"LoadIbServerInformation(): ServerName: {_ibServerName}, ServerRegion: {_ibServerRegion}"));
                        return;
                    }
                }

                _ibServerRegion = Region.America;

                ErrorDataReceived?.Invoke(this, new ErrorDataReceivedEventArgs(
                                              $"LoadIbServerInformation(): Unable to find the server name in the IB ini file: {iniFileName}, region set to {_ibServerRegion}"));
            }
            else
            {
                ErrorDataReceived?.Invoke(this, new ErrorDataReceivedEventArgs(
                                              $"LoadIbServerInformation(): IB ini file not found: {iniFileName}"));
            }

            OutputDataReceived?.Invoke(this, new OutputDataReceivedEventArgs(
                                           $"LoadIbServerInformation(): ServerName: {_ibServerName}, ServerRegion: {_ibServerRegion}"));
        }
Beispiel #24
0
        private async Task <CommandResult> ExecuteAsyncInternal(string executable, string args)
        {
            var output = new List <string>();

            CurrentProcess = CreateProcess(executable, args);
            CurrentProcess.ErrorDataReceived += (s, e) =>
            {
                if (e.Data == null)
                {
                    return;
                }

                output.Add($"[{_label}] {e.Data}");
                Console.WriteLine($"[{_label}] {e.Data}");
                ErrorDataReceived?.Invoke(s, e);
            };

            CurrentProcess.OutputDataReceived += (s, e) =>
            {
                if (e.Data == null)
                {
                    return;
                }

                output.Add($"[{_label}] {e.Data}");
                Console.WriteLine($"[{_label}] {e.Data}");
                OutputDataReceived?.Invoke(s, e);
            };

            var completionTask = CurrentProcess.StartAndWaitForExitAsync();

            CurrentProcess.BeginOutputReadLine();
            CurrentProcess.BeginErrorReadLine();
            await completionTask;

            CurrentProcess.WaitForExit();
            RemoveNullTerminator(output);

            return(new CommandResult(
                       CurrentProcess.StartInfo,
                       CurrentProcess.ExitCode,
                       string.Join(System.Environment.NewLine, output)));
        }
Beispiel #25
0
        public ProcessWrapper()
        {
            _process = new Process()
            {
                EnableRaisingEvents = true
            };

            _process.Exited            += (sender, e) => Exited?.Invoke();
            _process.ErrorDataReceived += (sender, e) =>
            {
                Trace.WriteLine($"[stderr] {e?.Data}");
                ErrorDataReceived?.Invoke(e?.Data);
            };
            _process.OutputDataReceived += (sender, e) =>
            {
                Trace.WriteLine($"[stdout] {e?.Data}");
                OutputDataReceived?.Invoke(e?.Data);
            };
        }
Beispiel #26
0
        private void Process_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            var data = e.Data;

            Trace.WriteLine($"npm console: {data}");
            OutputDataReceived?.Invoke(this, e);

            switch (_State)
            {
            case State.Initializing:
                TryParsePort(data);
                break;

            case State.Closing:
                TryParseKey(data);
                break;
            }
            ;
        }
        public void Start()
        {
            if (this.IsRunning)
            {
                return;
            }

            this.Service = new Process();
            this.Service.StartInfo.FileName        = FileName.FullName;
            this.Service.StartInfo.Arguments       = Arguments;
            this.Service.StartInfo.UseShellExecute = false;
            this.Service.StartInfo.CreateNoWindow  = true;

            this.Service.StartInfo.RedirectStandardOutput = true;
            this.Service.OutputDataReceived += (sender, e) => OutputDataReceived?.Invoke(this, e);

            bool   isLaunched = false;
            string msgTxt     =
                $"The local WinAppDriver server has not been started: {this.FileName.FullName} Arguments: {this.Arguments}. " +
                "\n";

            try
            {
                Service.Start();

                Service.BeginOutputReadLine();
            }
            catch (Exception e)
            {
                DestroyProcess();
                throw new Exception(msgTxt, e);
            }

            isLaunched = Ping();
            if (!isLaunched)
            {
                DestroyProcess();
                throw new Exception(
                          msgTxt +
                          $"Time {InitializationTimeout.TotalMilliseconds} ms for the service starting has been expired!");
            }
        }
Beispiel #28
0
        public void ReadSync(int clientId)
        {
            ClientData clientData = Clients[clientId];

            try
            {
                while (true)
                {
                    string line = clientData.Reader.ReadLine();
                    OutputDataReceived?.Invoke(this, new OutputDataReceivedArgs
                    {
                        ClientId = (int)clientData.ClientSocket.Handle,
                        Line     = line
                    });
                }
            }
            catch (IOException exception)
            {
                CloseAndNotify(clientData);
            }
        }
Beispiel #29
0
        private void Channel_DataReceived(object sender, ChannelDataEventArgs e)
        {
            if (OutputStream != null)
            {
                OutputStream.Write(e.Data, 0, e.Data.Length);
                OutputStream.Flush();
            }

            if (OutputDataReceived != null)
            {
                OutputDataReceived.Invoke(e.Data, _encoding);
            }

            if (_asyncResult != null)
            {
                lock (_asyncResult)
                {
                    _asyncResult.BytesReceived += e.Data.Length;
                }
            }
        }
        internal LocalWebServerReportingService(IReportingBinary binary, string cwd = null, Configuration configuration = null)
        {
            _binaryProcess = new BinaryProcess(binary, cwd, configuration);

            _binaryProcess.Configuration.HttpPort = _binaryProcess.Configuration.HttpPort ?? 5488;
            LocalServerUri    = "http://localhost:" + _binaryProcess.Configuration.HttpPort;
            _reportingService = new ReportingService(LocalServerUri, _binaryProcess?.Configuration?.Authentication?.Admin?.Username,
                                                     _binaryProcess?.Configuration?.Authentication?.Admin?.Password);
            StartTimeout = new TimeSpan(0, 0, 0, 20);
            StopTimeout  = new TimeSpan(0, 0, 0, 3);
            _binaryProcess.OutputDataReceived += (s, e) => {
                _startOutputLogs += e.Data;
                OutputDataReceived?.Invoke(s, e);
            };
            _binaryProcess.ErrorDataReceived += (s, e) => {
                _startErrorLogs += e.Data;
                OutputDataReceived?.Invoke(s, e);
            };

            AppDomain.CurrentDomain.DomainUnload += DomainUnloadOrProcessExit;
            AppDomain.CurrentDomain.ProcessExit  += DomainUnloadOrProcessExit;
        }