Exemple #1
0
        public CommandResult Execute(string fileName, string args)
        {
            lock (_executingLock)
            {
                if (isDisposed)
                {
                    throw new ObjectDisposedException(nameof(HestExecutor));
                }

                //记录开始时间
                DateTime start = DateTime.Now;
                //开始进程
                commandProcedure = BasicBooter.CommandProcedureManager.OpenCommand(fileName, args);
                commandProcedure.OutputReceived += OnOutputReceived;

                //触发事件
                CommandExecuting?.Invoke(this, new CommandExecutingEventArgs(fileName, args));
                var cmdResult = commandProcedure.Execute();
                commandProcedure.Dispose();
                //记录结束时间
                DateTime end = DateTime.Now;

                //构造结果对象
                var result = new CommandResult(cmdResult.ExitCode, cmdResult.Output);

                //触发结束事件
                CommandExecuted?.Invoke(this, new CommandExecutedEventArgs(fileName, args, result, end - start));

                //返回结果
                return(result);
            };
        }
        public bool RunCommand(XTMFCommand command, ref string error)
        {
            lock (_SessionLock)
            {
                if (command.Do(ref error))
                {
                    HasChanged = true;
                    if (_InCombinedContext)
                    {
                        var list = _CombinedCommands;
                        list.Add(command);
                    }
                    else
                    {
                        if (command.CanUndo())
                        {
                            _UndoStack.Add(command);
                        }

                        CommandExecuted?.Invoke(this, new EventArgs());
                    }

                    // if we do something new, redo no long is available
                    _RedoStack.Clear();
                    return(true);
                }

                return(false);
            }
        }
        /// <summary>
        /// Data for commands to listen to on the Commands class.
        /// </summary>
        /// <param name="command">Command to listen to.</param>
        /// <param name="listen">Should this command be listened to?</param>
        /// <param name="getNameAndProfile">Should the player who executes this command have their player profile registered?</param>
        /// <param name="checkIfFriend">Should the player who executes this command be checked to see if they are a friend?</param>
        /// <param name="callback">Method to be executed when the command is executed.</param>
        public ListenTo(string command, bool listen, bool getNameAndProfile, bool checkIfFriend, CommandExecuted callback)
        {
            for (int c = 0; c < command.Length; c++)
            {
                bool characterFound = false;

                for (int l = 0; l < Commands.letters.Length; l++)
                {
                    if (command[c] == Commands.letters[l].Char)
                    {
                        characterFound = true;
                    }
                }

                if (!characterFound)
                {
                    throw new ArgumentException(string.Format("Letter '{0}' is not a valid letter to have in a command. The only valid letters is the uppercase english alphabet, numbers, and $.",
                                                              command[c].ToString()));
                }
            }

            Command           = command;
            Listen            = listen;
            GetNameAndProfile = getNameAndProfile;
            CheckIfFriend     = checkIfFriend;
            Callback          = callback;
        }
 /// <summary>
 /// 无锁的执行..不建议覆写
 /// </summary>
 /// <param name="fileName"></param>
 /// <param name="args"></param>
 /// <returns></returns>
 protected virtual Result ExecuteWithoutLock(string fileName, string args)
 {
     if (disposedValue)
     {
         throw new ObjectDisposedException(nameof(CommandExecutor));
     }
     int exitCode;
     ProcessStartInfo pStartInfo;
     outputBuilder.Clear();
     pStartInfo = GetStartInfo(fileName, args);
     DateTime start = DateTime.Now;
     currentProcess = Process.Start(pStartInfo);
     OnProcessStarted(currentProcess);
     try
     {
         CommandExecuting?.Invoke(this, new CommandExecutingEventArgs(fileName, args));
         ExecutingSource?.Invoke(this, new CommandExecutingEventArgs(fileName, args));
     }
     catch { }
     currentProcess.WaitForExit();
     DateTime end = DateTime.Now;
     exitCode = currentProcess.ExitCode;
     OnProcessExited(currentProcess);
     currentProcess = null;
     var result = new Result(outputBuilder.Result, exitCode);
     try
     {
         CommandExecuted?.Invoke(this, new CommandExecutedEventArgs(fileName, args, result, end - start));
         ExecutedSource?.Invoke(this, new CommandExecutedEventArgs(fileName, args, result, end - start));
     }
     catch { }
     return result;
 }
Exemple #5
0
 public virtual void Execute()
 {
     if (_executeParameterless != null)
     {
         _executeParameterless();
         CommandExecuted.Raise(this);
     }
 }
Exemple #6
0
 public override void Execute(object parameter)
 {
     base.Execute(parameter);
     CommandExecuted?.Invoke(new MediaCommandExecutedEventArgs()
     {
         Parameter = parameter
     });
 }
Exemple #7
0
        private async Task ExecuteAndDispatchNext(CommandBase command)
        {
            await command.ExecuteAsync().ConfigureAwait(false);

            CommandExecuted?.Invoke(this, new CommandRunnerEvent(command));

            DispatchNext();
        }
        private void ExecuteCommand(IInfiniteCanvasCommand command)
        {
            _undoCommands.Push(command);
            _redoCommands.Clear();
            command.Execute();

            CommandExecuted?.Invoke(this, EventArgs.Empty);
        }
Exemple #9
0
 public void InvokeCommand(CmdlineCommand command, string args)
 {
     // We don't want to block this call because it causes issues if some sync operation that shuts down server is also called.
     // For example, mode switch or instance shutdown calls are stopping server,
     // which results in serviceHost.Close() timeout, since server would be still waiting for InvokeCommand to finish.
     Task.Run(async() =>
     {
         await Task.Delay(100);
         syncContext.Post(_ => CommandExecuted?.Invoke(this, new CommandExecutedEventArgs(command, args)), null);
     });
 }
Exemple #10
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="journalRecord"></param>
 /// <param name="isLocal"></param>
 /// <param name="events"></param>
 private void NotifyCommandExecuted(JournalRecord journalRecord, bool isLocal, IEnumerable <Event> events)
 {
     try
     {
         CommandExecuted.Invoke(journalRecord, isLocal, events);
     }
     catch
     {
         // Don't let external code crash the engine
     }
 }
        public void OnCommandExecuted(ICommandContext context, Task <IResult> task)
        {
            IResult result = task.Result;

            if (result is null)
            {
                return;
            }

            CommandExecuted?.Invoke(new Optional <CommandInfo>(), context, result);
        }
Exemple #12
0
 private void NotifyCommandExecuted(JournalRecord journalRecord, bool isLocal, IEnumerable <Event> events)
 {
     try
     {
         CommandExecuted.Invoke(journalRecord, isLocal, events);
     }
     catch (Exception exception)
     {
         _logger.LogError(exception, "Exception thrown in CommandExecuted handler.");
     }
 }
Exemple #13
0
        private void CommandExecutionLoop()
        {
            int commandNumber = 0;

            foreach (ICommand command in commands)
            {
                ExecuteCommand(command);
                commandNumber++;

                CommandExecuted?.Invoke(commandNumber);
            }
        }
Exemple #14
0
        /// <summary>
        /// 执行命令
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        public ICommandResult Execute(string fileName, string args)
        {
            lock (_executingLock)
            {
                if (isDisposed)
                {
                    throw new ObjectDisposedException(nameof(HestExecutor));
                }
                //输出构造器
                outputBuilder.Clear();
                //记录开始时间
                DateTime start = DateTime.Now;
                //开始进程
                currentProcess = Process.Start(GetStartInfo(fileName, args));

                //监听
                currentProcess.OutputDataReceived += (s, e) =>
                {
                    outputBuilder.AppendOut(e.Data);
                    OutputReceived?.Invoke(this, new OutputReceivedEventArgs(e, false));
                };
                currentProcess.ErrorDataReceived += (s, e) =>
                {
                    outputBuilder.AppendError(e.Data);
                    OutputReceived?.Invoke(this, new OutputReceivedEventArgs(e, true));
                };
                currentProcess.BeginOutputReadLine();
                currentProcess.BeginErrorReadLine();

                //触发事件
                CommandExecuting?.Invoke(this, new CommandExecutingEventArgs(fileName, args));

                //等待进程结束
                currentProcess.WaitForExit();
                currentProcess.CancelErrorRead();
                currentProcess.CancelOutputRead();

                //记录结束时间
                DateTime end = DateTime.Now;
                //构造结果对象
                var result = new HestExecutorResult()
                {
                    ExitCode = currentProcess.ExitCode, Output = outputBuilder.Result
                };
                //触发结束事件
                CommandExecuted?.Invoke(this, new CommandExecutedEventArgs(fileName, args, result, end - start));
                //返回结果
                return(result);
            };
        }
Exemple #15
0
        public void Install_bundler_dependencies()
        {
            // arrange
            FullPathToCommandExecuted = Path.GetFullPath(Path.Combine(".",
                                                                      COMMAND_EXECUTED_TXT));

            // act
            RubyProcess.InstallBundlerDependencies();

            // assert
            CommandExecuted
            .Should()
            .Be("install");
        }
        public void ExecuteCombinedCommands(string name, Action combinedCommandContext)
        {
            lock (_SessionLock)
            {
                _InCombinedContext = true;
                var list = _CombinedCommands = new List <XTMFCommand>();
                combinedCommandContext();
                // only add to the undo list if a command was added successfully
                if (list.Count > 0)
                {
                    // create a command to undo everything in a single shot [do is empty]
                    _UndoStack.Add(XTMFCommand.CreateCommand(name, (ref string error) => { return(true); },
                                                             (ref string error) =>
                    {
                        foreach (var command in ((IEnumerable <XTMFCommand>)list).Reverse())
                        {
                            if (command.CanUndo())
                            {
                                if (!command.Undo(ref error))
                                {
                                    return(false);
                                }
                            }
                        }

                        return(true);
                    },
                                                             (ref string error) =>
                    {
                        foreach (var command in list)
                        {
                            if (command.CanUndo())
                            {
                                if (!command.Redo(ref error))
                                {
                                    return(false);
                                }
                            }
                        }

                        return(true);
                    }));
                    CommandExecuted?.Invoke(this, new EventArgs());
                }

                _InCombinedContext = false;
                _CombinedCommands  = null;
            }
        }
Exemple #17
0
        /// <summary>
        /// Actual command execution
        /// </summary>
        public object Execute(Command command)
        {
            EnsureNotDisposed();
            EnsureAuthorized(command);
            FireExecutingEvent(command);

            lock (_commandSequenceLock)
            {
                var  ctx             = ExecutionContext.Begin();
                bool exceptionThrown = false;
                _executionTimer.Restart();
                _config.Isolation.Commands.Apply(ref command);

                ulong lastEntryId = (_config.PersistenceMode == PersistenceMode.Journaling)
                    ? _journalAppender.Append(command)
                    : 0;

                try
                {
                    return(_kernel.ExecuteCommand(command));
                }
                catch (Exception ex)
                {
                    exceptionThrown = true;
                    if (_config.PersistenceMode == PersistenceMode.Journaling)
                    {
                        _journalAppender.AppendRollbackMarker();
                    }
                    if (!(ex is CommandAbortedException))
                    {
                        Rollback();
                        ex = new CommandFailedException("Command failed with rollback, see inner exception for details", ex);
                    }
                    throw ex;
                }
                finally
                {
                    _synchronizer.Exit();
                    if (!exceptionThrown)
                    {
                        var args = new CommandExecutedEventArgs(lastEntryId, command, ctx.Timestamp, _executionTimer.Elapsed, ctx.Events);
                        CommandExecuted.Invoke(this, args);
                    }
                    ExecutionContext.Current = null;
                }
            }
        }
        public void Execute(Command cmd)
        {
            if (cmd is null)
            {
                throw new ArgumentNullException(nameof(cmd));
            }

            if (BeginExecute(cmd) == false)
            {
                return;
            }
            CommandExecutedEventArg cmmdExecutedEventArg =
                new CommandExecutedEventArg(cmd.UpdateEntity.Entity);

            try
            {
                var history = _historyRepositoryFactory.GetRepository(cmd);
                IEntityRepository entityRepository = _entityRepositoryFactory.GetRepository(cmd);

                var lastUpdatedEntity = entityRepository.LastUpdated;

                if (lastUpdatedEntity != null)
                {
                    CheckData(cmd, entityRepository, lastUpdatedEntity);
                }

                if (history != null)
                {
                    history.Record(lastUpdatedEntity, cmd.UpdateEntity.Entity);
                }

                entityRepository.Save();

                cmd.UpdateEntity.Entity.LastUpdateDateTime = cmd.CurrentUpdateDateTime;
                cmd.UpdateEntity.Entity.LastUpdatedUser    = cmd.CurrentUpdateUser;
            }
            catch (Exception exp)
                when(exp is DataUpdateConflictException || exp is ReferenceObsoleteException)
                {
                    cmmdExecutedEventArg.IsSuccess    = false;
                    cmmdExecutedEventArg.ErrorMessage = exp.Message;
                }

            CommandExecuted?.Invoke(this, cmmdExecutedEventArg);
        }
Exemple #19
0
        public void Start_ruby_process()
        {
            // arrange
            const string workingDirectory = @"..\..\workingdir";

            FullPathToCommandExecuted = Path.GetFullPath(Path.Combine(workingDirectory,
                                                                      COMMAND_EXECUTED_TXT));
            var process = new RubyProcess(workingDirectory: workingDirectory);

            // act
            process.StartRubyProcess("shutdownscript script args");
            process.RubyProc.WaitForExit();

            // assert
            CommandExecuted
            .Should()
            .Be("script  args");
        }
Exemple #20
0
        public void No_ssl_start()
        {
            // arrange
            var thin = new ThinServerProcess(thinPort: 1224,
                                             workingDirectory: ".");

            _tcpListener = new TcpListener(IPAddress.Any,
                                           1224);
            _tcpListener.Start();

            // act
            thin.StartThinServer();
            thin.RubyProc.WaitForExit();

            // assert
            CommandExecuted
            .Should()
            .Be(@".\thin  start -R config.ru -p 1224 -V");
        }
Exemple #21
0
        /// <summary>Executes the supplied command</summary>
        /// <param name="command">The command to execute.</param>
        /// <param name="context">The context passed to the command</param>
        public virtual void Execute(CommandBase <CommandContext> command, CommandContext context)
        {
            var args = new CommandProcessEventArgs {
                Command = command, Context = context
            };

            if (CommandExecuting != null)
            {
                CommandExecuting.Invoke(this, args);
            }

            logger.Info(args.Command.Name + " processing " + args.Context);
            using (var tx = persister.Repository.BeginTransaction())
            {
                try
                {
                    args.Command.Process(args.Context);
                    Utility.FindEmpty(args.Context.Content);
                    tx.Commit();

                    if (CommandExecuted != null)
                    {
                        CommandExecuted.Invoke(this, args);
                    }
                }
                catch (StopExecutionException)
                {
                    tx.Rollback();
                }
                catch (Exception ex)
                {
                    tx.Rollback();
                    logger.Error(ex);
                    throw;
                }
                finally
                {
                    logger.Info(" -> " + args.Context);
                }
            }
        }
Exemple #22
0
        public void Ssl_start()
        {
            // arrange
            var thin = new ThinServerProcess(thinPort: 1224,
                                             workingDirectory: ".")
            {
                ThinSslCertFile = "certfile",
                ThinSslKeyFile  = "keyfile"
            };

            _tcpListener = new TcpListener(IPAddress.Any,
                                           1224);
            _tcpListener.Start();

            // act
            thin.StartThinServer();
            thin.RubyProc.WaitForExit();

            // assert
            CommandExecuted
            .Should()
            .Be(@".\thin  start -R config.ru -p 1224 -V --ssl --ssl-key-file keyfile --ssl-cert-file certfile");
        }
        /// <summary>
        ///     Redo the last undone command
        /// </summary>
        /// <param name="error">The reason why it failed</param>
        public bool Redo(ref string error)
        {
            lock (_SessionLock)
            {
                if (_RedoStack.TryPop(out var command))
                {
                    if (command != null)
                    {
                        if (command.Redo(ref error))
                        {
                            HasChanged = true;
                            _UndoStack.Add(command);
                            CommandExecuted?.Invoke(this, new EventArgs());
                            return(true);
                        }

                        return(false);
                    }
                }

                error = "There was nothing to redo.";
                return(false);
            }
        }
 public void RaiseCommandExecuted(DbCommand command, int?rowsAffected)
 {
     CommandExecuted?.Invoke(this, new CommandExecutedEventArgs(command, rowsAffected));
 }
 private void OnCommandExecuted(DbCommand command)
 {
     CommandExecuted?.Invoke(this, command);
 }
 public void AddCommandExecutedCallback(CommandExecuted callback)
 {
     commandExecutedCallback += callback;
 }
 public void command_is_not_executed()
 {
     CommandExecuted.ShouldBeFalse();
 }
 public void command_is_executed()
 {
     CommandExecuted.ShouldBeTrue();
 }
 /// <summary>
 /// Data for commands to listen to on the Commands class.
 /// </summary>
 /// <param name="command">Command to listen to.</param>
 /// <param name="callback">Method to be executed when the command is executed.</param>
 public ListenTo(string command, CommandExecuted callback) : this(command, true, false, false, callback)
 {
 }
 /// <summary>
 /// The trigger function for <see cref="CommandExecuted"/> event.
 /// </summary>
 /// <param name="commandText">The <see cref="FbCommand.CommandText"/> of the executed SQL command.</param>
 /// <param name="dataReader">The <see cref="FbDataReader"/> instance with the returned data. If the
 /// command executed is not meant to return data (ex: UPDATE, INSERT...) this parameter must be
 /// setled to <b>null</b>.</param>
 /// <param name="rowsAffected">The rows that were affected by the executed SQL command. If the executed
 /// command is not meant to return this kind of information (ex: SELECT) this parameter must
 /// be setled to <b>-1</b>.</param>
 private void OnCommandExecuted(FbDataReader dataReader, string commandText, SqlStatementType statementType, int rowsAffected)
 {
     CommandExecuted?.Invoke(this, new CommandExecutedEventArgs(dataReader, commandText, statementType, rowsAffected));
 }
Exemple #31
0
 public void InvokeCommand(CmdlineCommand command, string args)
 {
     CommandExecuted?.Invoke(this, new CommandExecutedEventArgs(command, args));
 }