Ejemplo n.º 1
0
 private void Process_ErrorDataReceived(object sender, DataReceivedEventArgs e)
 {
     if (e.Data != null)
     {
         ErrorDataReceived?.Invoke(this, new EventArgs <string>(e.Data));
     }
 }
Ejemplo n.º 2
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);
                }
            }
        }
Ejemplo n.º 3
0
 private void Cli_ErrorDataReceived(object sender, DataReceivedEventArgs e)
 {
     if (e.Data != null)
     {
         ErrorDataReceived?.Invoke(sender, e);
     }
 }
Ejemplo n.º 4
0
 private void OnErrorDataReceived(object sender, DataReceivedEventArgs e)
 {
     // at the end of the process, the event fires one last time with null
     if (e.Data != null)
     {
         ErrorDataReceived?.Invoke(sender, e);
     }
 }
Ejemplo n.º 5
0
 public void Terminate()
 {
     if (_stream != null)
     {
         _stream.Dispose();
     }
     ErrorDataReceived?.Invoke(this, null);
 }
Ejemplo n.º 6
0
 private void ProcessErrorData(object sender, DataReceivedEventArgs e)
 {
     ErrorDataReceived?.Invoke(sender, e);
     if (ForwardDataAndError && e.Data != null)
     {
         Console.Error.WriteLine(e.Data);
     }
 }
Ejemplo n.º 7
0
        private void RaiseErrorDataReceived(DataReceivedEventArgs e)
        {
            if (e == null)
            {
                return;
            }

            ErrorDataReceived.Raise(this, e);
            OnErrorDataReceived(e.Data);
        }
Ejemplo n.º 8
0
 private void Process_ErrorDataReceived(object sender, DataReceivedEventArgs e)
 {
     try
     {
         ErrorDataReceived?.Invoke(sender, e);
         Output(OutputProcessor?.ParseError(this, e.Data));
     }
     catch (Exception ex)
     {
         OnError?.Invoke(this, ex);
     }
 }
Ejemplo n.º 9
0
 private void Process_ErrorDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e)
 {
     if (!string.IsNullOrWhiteSpace(e.Data))
     {
         if (outputToConsole)
         {
             Console.WriteLine(e.Data);
         }
         ErrorDataReceived?.Invoke(this, new DataReceivedEventArgs(e.Data));
         errorLines.Add(e.Data);
     }
 }
Ejemplo n.º 10
0
 private void FireErrorDataReceived(object sender, TaskDataReceivedEventArgs e)
 {
     if (InvokeRequired)
     {
         FireErrorDataReceivedCallback d = new FireErrorDataReceivedCallback(FireErrorDataReceived);
         this?.Invoke(d, new object[] { sender, e });
     }
     else
     {
         ErrorDataReceived?.Invoke(sender, e);
     }
 }
Ejemplo n.º 11
0
        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();
            };
        }
Ejemplo n.º 12
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}"));
        }
Ejemplo n.º 13
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)));
        }
Ejemplo n.º 14
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);
            };
        }
Ejemplo n.º 15
0
        public Task <int> RunToExitAsync()
        {
            if (_expectedOutput != null)
            {
                foreach (string message in _expectedOutput)
                {
                    OutputDataReceived?.Invoke(null, new TextReceivedEventArgs(message));
                    if (_cancels)
                    {
                        _cancelable.When(t => t.ThrowIfCancellationRequested())
                        .Throw <OperationCanceledException>();
                        break;
                    }
                }
            }

            if (_errorMessage != null)
            {
                ErrorDataReceived?.Invoke(null, new TextReceivedEventArgs(_errorMessage));
            }

            return(Task.FromResult(0));
        }
Ejemplo n.º 16
0
 private void Process_ErrorDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e)
 {
     lock (_locker)
     {
         _taskData.DebugData.DateLastSignal = DateTime.Now;
         if (!string.IsNullOrEmpty(e.Data))
         {
             _hasErrorMessage = true;
         }
         if (_hasErrorMessage)
         {
             string message = ToErrorMessage(e.Data);
             _taskData.DebugData.Output += message;
             ErrorDataReceived?.Invoke(this, new TaskDataReceivedEventArgs(message, _taskData.Id));
             _taskData.DebugData.TaskStatus = ETaskStatus.RunningWithErrors;
             _taskStatus = _taskData.DebugData.TaskStatus;
             StatusChanged?.Invoke(this, new TaskStatusChangedEventArgs(_taskStatus, _taskData.Id));
             const string notificationMessageTemplate = "Task \"{0}\" sent error message:\r\n\t {1}.";
             string       notificationMessage         = string.Format(notificationMessageTemplate, _taskData.Name, e.Data);
             TaskNotification?.Invoke(this, new TaskNotificationEventArgs(notificationMessage, _taskData.Id, _taskData.Name, ENotificationType.TaskError));
         }
     }
 }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="scriptPath"></param>
        /// <param name="arguments">Arguments separated by a space character</param>
        public void ExecuteScript(string scriptPath, IScriptArguments arguments)
        {
            try
            {
                var process = new System.Diagnostics.Process();
                var startInfo = new System.Diagnostics.ProcessStartInfo
                {
                    WindowStyle = System.Diagnostics.ProcessWindowStyle.Maximized,
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    FileName = GetFilePath(),
                    Arguments = $"{scriptPath} {arguments.ToString()}"
                };

                EnsureTargetFolderExist(arguments.TargetPath);

                //* Set your output and error (asynchronous) handlers
                process.OutputDataReceived += new DataReceivedEventHandler(HandleOutputData);
                process.ErrorDataReceived += (sender, args) => ErrorDataReceived?.Invoke(this, new BrowserResponseEventArgs(args.Data));

                _logger.LogDebug($"Calling executable: {startInfo.FileName} {startInfo.Arguments}");

                process.StartInfo = startInfo;
                process.Start();

                process.BeginOutputReadLine();
                process.BeginErrorReadLine();
                process.WaitForExit();
            }
            catch (Exception ex)
            {
                _logger.LogError("Error when calling phantomjs", ex);
                throw;
            }

        }
Ejemplo n.º 18
0
        private void ExecuteProcessAndWaitForExit(string fileName, string arguments)
        {
            var p = new Process
            {
                StartInfo = new ProcessStartInfo(fileName, arguments)
                {
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true,
                    UseShellExecute        = false,
                    WindowStyle            = ProcessWindowStyle.Hidden,
                    CreateNoWindow         = true
                },
                EnableRaisingEvents = true
            };

            p.OutputDataReceived += (sender, e) =>
            {
                if (e.Data != null)
                {
                    OutputDataReceived?.Invoke(this, new OutputDataReceivedEventArgs($"{fileName}: {e.Data}"));
                }
            };
            p.ErrorDataReceived += (sender, e) =>
            {
                if (e.Data != null)
                {
                    ErrorDataReceived?.Invoke(this, new ErrorDataReceivedEventArgs($"{fileName}: {e.Data}"));
                }
            };

            p.Start();
            p.BeginErrorReadLine();
            p.BeginOutputReadLine();
            p.WaitForExit();

            OutputDataReceived?.Invoke(this, new OutputDataReceivedEventArgs($"{fileName} {arguments}: process exit code: {p.ExitCode}"));
        }
Ejemplo n.º 19
0
            public bool Start(ProcessStartInfo startInfo)
            {
                if (startInfo == null)
                {
                    throw new ArgumentNullException();
                }

                if (startInfo.FileName != EXE_FILE_NAME)
                {
                    throw new InvalidOperationException();
                }

                Task.Run(() =>
                {
                    var output = string.Empty;
                    var errors = string.Empty;

                    switch (startInfo.Arguments)
                    {
                    case ARGS_1:
                        output = OUTPUT;
                        errors = ERRORS;
                        break;

                    case ARGS_2:
                        Thread.Sleep(TIMEOUT_MS + 5);
                        break;
                    }

                    if (!startInfo.UseShellExecute)
                    {
                        using (var outputReader = new StringReader(output))
                        {
                            using (var errorReader = new StringReader(errors))
                            {
                                string outputLine = null;
                                string errorLine  = null;

                                do
                                {
                                    Thread.Sleep(5);

                                    outputLine = outputReader.ReadLine();
                                    errorLine  = errorReader.ReadLine();

                                    if (startInfo.RedirectStandardOutput && !string.IsNullOrEmpty(outputLine))
                                    {
                                        OutputDataReceived?.Invoke(outputLine);
                                    }

                                    if (startInfo.RedirectStandardError && !string.IsNullOrEmpty(errorLine))
                                    {
                                        ErrorDataReceived?.Invoke(errorLine);
                                    }
                                } while ((outputLine != null) || (errorLine != null));
                            }
                        }
                    }

                    ExitCode  = 0;
                    HasExited = true;
                    Exited?.Invoke();
                    _completion.Set();
                });

                return(true);
            }
Ejemplo n.º 20
0
 public Process()
 {
     _process = new System.Diagnostics.Process();
     _process.ErrorDataReceived  += (sender, args) => ErrorDataReceived.Invoke(sender, args);
     _process.OutputDataReceived += (sender, args) => OutputDataReceived.Invoke(sender, args);
 }
Ejemplo n.º 21
0
 private void ProcessErrorDataReceived(object sender, DataReceivedEventArgs e)
 {
     ErrorDataReceived?.Invoke(sender, e, this);
 }
Ejemplo n.º 22
0
 void  process_ErrorDataReceived(object sender, DataReceivedEventArgs e)
 {
     sbErr.AppendLine(e.Data);
     ErrorDataReceived?.Invoke(this, e);
 }
Ejemplo n.º 23
0
 private void _currentProcess_ErrorDataReceived(object sender, DataReceivedEventArgs e)
 {
     ErrorDataReceived?.Invoke(sender, e);
 }
Ejemplo n.º 24
0
        private async Task <ProcessOutput> InnerExecute(string cmd, bool waitForExit = true)
        {
            var logs   = "";
            var worker = new Process()
            {
                StartInfo = new ProcessStartInfo(_exePath)
                {
                    Arguments              = cmd,
                    WorkingDirectory       = _workingPath,
                    UseShellExecute        = false,
                    CreateNoWindow         = true,
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true,
                }
            };

            worker.StartInfo.EnvironmentVariables.Remove("COMPLUS_Version");
            worker.StartInfo.EnvironmentVariables.Remove("COMPLUS_InstallRoot");

            if (Configuration != null)
            {
                foreach (var e in SerializerHelper.SerializeConfigToDictionary(Configuration))
                {
                    worker.StartInfo.EnvironmentVariables.Add(e.Key, e.Value);
                }
            }

            var vars = worker.StartInfo.EnvironmentVariables;

            worker.OutputDataReceived += (sender, e) =>
            {
                if (!string.IsNullOrEmpty(e.Data))
                {
                    logs += e.Data;

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

            worker.ErrorDataReceived += (sender, e) =>
            {
                if (!string.IsNullOrEmpty(e.Data))
                {
                    logs += e.Data;

                    if (ErrorDataReceived != null)
                    {
                        ErrorDataReceived.Invoke(sender, e);
                    }
                }
            };

            worker.Start();

            worker.BeginOutputReadLine();
            worker.BeginErrorReadLine();

            if (waitForExit)
            {
                await worker.WaitForExitAsync().ConfigureAwait(false);

                return(new ProcessOutput(worker, !worker.HasExited || worker.ExitCode != 0, _exePath + cmd, logs));
            }

            return(new ProcessOutput(worker, false, _exePath + cmd, logs));
        }
Ejemplo n.º 25
0
 private void _minerCli_ErrorDataReceived(object sender, DataReceivedEventArgs e)
 {
     ErrorDataReceived?.Invoke(sender, e);
 }
Ejemplo n.º 26
0
 private void OnErrorDataReceived(object sender, DataReceivedEventArgs e)
 {
     ErrorDataReceived?.Invoke(this, e);
 }
Ejemplo n.º 27
0
 protected virtual void OnErrorDataReceived(string e)
 {
     ErrorDataReceived?.Invoke(this, e);
 }
Ejemplo n.º 28
0
 /// <summary>
 /// Raises the <see cref="ErrorDataReceived"/> event.
 /// </summary>
 /// <param name="eventArgs">
 /// <see cref="EventArgs"/> object that provides the arguments for the event.
 /// </param>
 /// <remarks>
 /// <strong>Notes to Inheritors:</strong> <br/>
 /// When overriding <see cref="OnErrorDataReceived(DataReceivedEventArgs)"/> in a derived class,
 /// be sure to call the base class's <see cref="OnErrorDataReceived(DataReceivedEventArgs)"/> 
 /// method so that registered delegates receive the event.
 /// </remarks>
 protected virtual void OnErrorDataReceived(DataReceivedEventArgs eventArgs)
 {
     ErrorDataReceived?.Invoke(this, eventArgs);
 }
Ejemplo n.º 29
0
        /// <summary>
        /// Starts the IB Gateway
        /// </summary>
        /// <param name="waitForExit">true if it should wait for the IB Gateway process to exit</param>
        /// <remarks>The IB Gateway application will be launched</remarks>
        public StartResult Start(bool waitForExit)
        {
            lock (_locker)
            {
                if (_lastStartResult.HasError)
                {
                    // IBAutomater errors are unrecoverable
                    return(_lastStartResult);
                }

                if (IsRunning())
                {
                    return(StartResult.Success);
                }

                _process = null;
                _ibAutomaterInitializeEvent.Reset();

                if (IsLinux)
                {
                    // need permission for execution
                    OutputDataReceived?.Invoke(this, new OutputDataReceivedEventArgs("Setting execute permissions on IBAutomater.sh"));
                    ExecuteProcessAndWaitForExit("chmod", "+x IBAutomater.sh");
                }

                OutputDataReceived?.Invoke(this, new OutputDataReceivedEventArgs($"Loading IBGateway version: {_ibVersion}"));

                var fileName  = IsWindows ? "IBAutomater.bat" : "IBAutomater.sh";
                var arguments = $"{_ibDirectory} {_ibVersion} {_userName} {_password} {_tradingMode} {_portNumber}";

                var process = new Process
                {
                    StartInfo = new ProcessStartInfo(fileName, arguments)
                    {
                        RedirectStandardOutput = true,
                        RedirectStandardError  = true,
                        UseShellExecute        = false,
                        WindowStyle            = ProcessWindowStyle.Hidden,
                        CreateNoWindow         = true
                    },
                    EnableRaisingEvents = true
                };

                process.OutputDataReceived += (sender, e) =>
                {
                    if (e.Data != null)
                    {
                        OutputDataReceived?.Invoke(this, new OutputDataReceivedEventArgs(e.Data));

                        // login failed
                        if (e.Data.Contains("Login failed"))
                        {
                            _lastStartResult = new StartResult(ErrorCode.LoginFailed);
                            _ibAutomaterInitializeEvent.Set();
                        }

                        // an existing session was detected
                        else if (e.Data.Contains("Existing session detected"))
                        {
                            _lastStartResult = new StartResult(ErrorCode.ExistingSessionDetected);
                            _ibAutomaterInitializeEvent.Set();
                        }

                        // a security dialog (2FA) was detected by IBAutomater
                        else if (e.Data.Contains("Second Factor Authentication"))
                        {
                            if (e.Data.Contains("[WINDOW_OPENED]"))
                            {
                                // waiting for 2FA confirmation on IBKR mobile app
                                const string message = "Waiting for 2FA confirmation on IBKR mobile app (to be confirmed within 3 minutes).";
                                OutputDataReceived?.Invoke(this, new OutputDataReceivedEventArgs(message));

                                _twoFactorConfirmationPending = true;
                            }
                        }

                        // a security dialog (code card) was detected by IBAutomater
                        else if (e.Data.Contains("Security Code Card Authentication") ||
                                 e.Data.Contains("Enter security code"))
                        {
                            _lastStartResult = new StartResult(ErrorCode.SecurityDialogDetected);
                            _ibAutomaterInitializeEvent.Set();
                        }

                        // initialization completed
                        else if (e.Data.Contains("Configuration settings updated"))
                        {
                            _ibAutomaterInitializeEvent.Set();
                        }
                    }
                };

                process.ErrorDataReceived += (sender, e) =>
                {
                    if (e.Data != null)
                    {
                        ErrorDataReceived?.Invoke(this, new ErrorDataReceivedEventArgs(e.Data));
                    }
                };

                process.Exited += (sender, e) =>
                {
                    Exited?.Invoke(this, new ExitedEventArgs(process.ExitCode));
                };

                try
                {
                    var started = process.Start();
                    if (!started)
                    {
                        return(new StartResult(ErrorCode.ProcessStartFailed));
                    }
                }
                catch (Exception exception)
                {
                    return(new StartResult(ErrorCode.ProcessStartFailed, exception.Message));
                }

                OutputDataReceived?.Invoke(this, new OutputDataReceivedEventArgs($"IBAutomater process started - Id:{process.Id}"));

                _process = process;

                process.BeginErrorReadLine();
                process.BeginOutputReadLine();

                if (waitForExit)
                {
                    process.WaitForExit();
                }
                else
                {
                    // wait for completion of IBGateway login and configuration
                    string message;
                    if (_ibAutomaterInitializeEvent.WaitOne(TimeSpan.FromSeconds(60)))
                    {
                        message = "IB Automater initialized.";
                    }
                    else
                    {
                        if (_twoFactorConfirmationPending)
                        {
                            // wait for completion of two-factor authentication
                            if (!_ibAutomaterInitializeEvent.WaitOne(TimeSpan.FromMinutes(3)))
                            {
                                _lastStartResult = new StartResult(ErrorCode.TwoFactorConfirmationTimeout);
                                message          = "IB Automater 2FA timeout.";
                            }
                            else
                            {
                                // 2FA confirmation successful
                                message = "IB Automater initialized.";
                            }
                        }
                        else
                        {
                            message = "IB Automater initialization timeout.";
                        }
                    }

                    OutputDataReceived?.Invoke(this, new OutputDataReceivedEventArgs(message));

                    // reset the flag, this method is called multiple times
                    _twoFactorConfirmationPending = false;

                    if (_lastStartResult.HasError)
                    {
                        message = $"IBAutomater error - Code: {_lastStartResult.ErrorCode} Message: {_lastStartResult.ErrorMessage}";
                        OutputDataReceived?.Invoke(this, new OutputDataReceivedEventArgs(message));

                        return(_lastStartResult);
                    }
                }
            }

            return(StartResult.Success);
        }
Ejemplo n.º 30
0
        private async Task <string> RunAsync(string command, params object[] args)
        {
            using (var p = new Process())
            {
                var OutputMessage = string.Empty;
                p.OutputDataReceived += (s, e) => {
                    if (string.IsNullOrWhiteSpace(e.Data))
                    {
                        return;
                    }
                    OutputMessage += e.Data + Environment.NewLine;
                    if (!OVERRIDE_ONREPORTEVENT)
                    {
                        OutputDataReceived?.Invoke(e.Data);
                    }
                };

                var ErrorMessage = string.Empty;
                p.ErrorDataReceived += (s, e) => {
                    if (string.IsNullOrWhiteSpace(e.Data))
                    {
                        return;
                    }
                    ErrorMessage += e.Data + Environment.NewLine;
                    if (!OVERRIDE_ONREPORTEVENT)
                    {
                        ErrorDataReceived?.Invoke(e.Data);
                    }
                };

                p.StartInfo = new ProcessStartInfo()
                {
                    UseShellExecute        = false,
                    CreateNoWindow         = true,
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true,
                    WindowStyle            = ProcessWindowStyle.Hidden,
                    FileName  = Path.Combine("Lib", "adb.exe"),
                    Arguments = string.Format(command, args)
                };

                p.Start();

                Debug.Print("Adb.Command: adb {0}", string.Format(command, args));

                if (!OVERRIDE_ONPROCESSEVENT)
                {
                    OnProcess?.Invoke(true);
                }

                p.BeginOutputReadLine();
                p.BeginErrorReadLine();

                await Task.Run(() => p.WaitForExit());

                if (!OVERRIDE_ONPROCESSEVENT)
                {
                    OnProcess?.Invoke(false);
                }

                if (p.ExitCode != 0)
                {
                    throw new Exception(ErrorMessage);
                }

                Debug.Print("Adb.Output: {0}", OutputMessage);
                return(OutputMessage);
            };
        }