Esempio n. 1
0
 private void OnCommandExecuted <TResult>(TCommand command, TResult result, AddonInvoker invoker)
 {
     if (ShouldLog(LogCategory.CommandExecuted))
     {
         WriteCommandExecuted(command, result, invoker);
     }
 }
Esempio n. 2
0
 private void LogCommand(TCommand command)
 {
     if (ShouldLog(LogCategory.CommandText))
     {
         WriteCommand(command);
     }
 }
Esempio n. 3
0
        // starting depth can be non-zero for nested behaviour trees
        internal BehaviourTree(BTNode root, int startingDepth)
        {
            this.root = root;
            data      = default;
            command   = default;

            allNodes = new List <BTNode>();
            GatherNodeInfoRecursively(root, startingDepth);

            tickedLastFrame = new bool[allNodes.Count];
            tickedThisFrame = new bool[allNodes.Count];
            lastTickResult  = new BTState[allNodes.Count];
            for (int i = 0; i < allNodes.Count; i++)
            {
                allNodes[i].index = i;
                allNodes[i].tree  = this;
                lastTickResult[i] = BTState.Failure;
            }

            void GatherNodeInfoRecursively(BTNode childNode, int depth)
            {
                allNodes.Add(childNode);
                childNode.debugDepth = depth;

                if (childNode is INodeWithChildren branch)
                {
                    foreach (var child in branch.Children())
                    {
                        GatherNodeInfoRecursively(child, depth + 1);
                    }
                }
            }
        }
Esempio n. 4
0
            /// <summary>
            /// Writes logging message for command executed.
            /// </summary>
            /// <typeparam name="TResult">Type of the command result.</typeparam>
            /// <param name="command">The command.</param>
            /// <param name="result">The command result.</param>
            /// <param name="invoker">The invoker.</param>
            protected virtual void WriteCommandExecuted <TResult>(TCommand command, TResult result, AddonInvoker invoker)
            {
                Debug.Assert(ShouldLog(LogCategory.CommandExecuted));
                var exception = invoker.Exception;

                if (exception != null)
                {
                    Write(LogCategory.CommandExecuted, DiagnosticMessages.DbLogger_CommandFailed(Stopwatch.ElapsedMilliseconds, exception.Message));
                }
                else if (invoker.TaskStatus.HasFlag(TaskStatus.Canceled))
                {
                    Write(LogCategory.CommandExecuted, DiagnosticMessages.DbLogger_CommandCanceled(Stopwatch.ElapsedMilliseconds));
                }
                else
                {
                    var resultString = (object)result == null
                        ? "null"
                        : (result is DbReader)
                            ? result.GetType().Name
                            : result.ToString();
                    Write(LogCategory.CommandExecuted, DiagnosticMessages.DbLogger_CommandComplete(Stopwatch.ElapsedMilliseconds, resultString));
                }
                Write(LogCategory.CommandExecuted, Environment.NewLine);
                Write(LogCategory.CommandExecuted, Environment.NewLine);
            }
        protected async Task <IActionResult> ExecuteCommand <TCommand, TResult>() where TCommand : class, ICommand <CommandResponse <TResult> >, new()
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            TCommand command = CreateCommand <TCommand>();
            CommandResponse <TResult> response;

            try
            {
                response = await Dispatcher.DispatchAsync(command);
            }
            catch (DispatcherException ex)
            {
                ex.AddToModelState(ModelState);
                return(BadRequest(ModelState));
            }

            if (response.IsSuccess)
            {
                return(Ok(response.Result));
            }
            response.AddToModelState(ModelState);
            return(BadRequest(ModelState));
        }
Esempio n. 6
0
        public void SendCommand <TCommand>() where TCommand : ICommand, new()
        {
            var command = new TCommand();

            command.SetArchitecture(this);
            command.Execute();
        }
Esempio n. 7
0
 /// <summary>
 /// Handles command handler exceptions.
 /// </summary>
 /// <param name="command">The command on which the exception occurred.</param>
 /// <param name="AContext">The context on which the exception happened.</param>
 /// <param name="exception">The exception.</param>
 protected virtual void CommandHandler_OnException(TCommand command, TContext AContext, Exception exception)
 {
     if (mOnCommandHandlersException != null)
     {
         mOnCommandHandlersException(command, AContext, exception);
     }
 }
Esempio n. 8
0
        public static List <TEntity> SelectEntity <TEntity, TCommand>() where TCommand : DbCommand, new()
        {
            List <TEntity> list = new List <TEntity>();

            using (TCommand command = new TCommand())
            {
                var TEntityAttribute = (TableManagerAttribute)typeof(TEntity).GetCustomAttributes(typeof(TableManagerAttribute), false).FirstOrDefault();
                command.Connection  = Connection.Conn ?? throw new NullReferenceException();
                command.CommandType = CommandType.Text;
                command.CommandText = $"SELECT * FROM {TEntityAttribute.SchemeName}{(TEntityAttribute.SchemeName == null ? "" : ".")}{TEntityAttribute.TableName ?? typeof(TEntity).Name}";
                Connection.Check();
                var reader = command.ExecuteReader() ?? throw new NullReferenceException();
                int count  = reader.FieldCount;
                var p0     = typeof(TEntity).GetProperties(BindingFlags.Public | BindingFlags.Instance);
                while (reader.Read())
                {
                    var ins = Activator.CreateInstance <TEntity>();
                    for (int i = 0; i < count; i++)
                    {
                        var p = p0.FirstOrDefault(x => x.Name.ToUpper() == reader.GetName(i).ToUpper());
                        p.SetValue(ins, Convert.ChangeType(Convert.ChangeType(reader.GetValue(i), p.PropertyType), p.PropertyType), null);
                    }
                    list.Add(ins);
                }
            }
            return(list);
        }
Esempio n. 9
0
            /// <summary>
            /// Writes command into logging.
            /// </summary>
            /// <param name="command">The command.</param>
            protected virtual void WriteCommand(TCommand command)
            {
                Debug.Assert(ShouldLog(LogCategory.CommandText));
                Debug.Assert(command != null);

                var commandText = command.CommandText ?? "<null>";

                if (commandText.EndsWith(Environment.NewLine, StringComparison.Ordinal))
                {
                    Write(LogCategory.CommandText, commandText);
                }
                else
                {
                    Write(LogCategory.CommandText, commandText);
                    Write(LogCategory.CommandText, Environment.NewLine);
                }

                if (command.Parameters != null)
                {
                    foreach (var parameter in command.Parameters.OfType <DbParameter>())
                    {
                        WriteParameter(parameter);
                    }
                }
                Write(LogCategory.CommandText, Environment.NewLine);
            }
Esempio n. 10
0
        public TCommand Build <TCommand>() where TCommand : ICommand, new()
        {
            TCommand command = new TCommand();

            OnNewCommand(command);

            return(command);
        }
Esempio n. 11
0
        public T ExecuteCommand <TCommand, T>() where TCommand : SqlCommand, new()
        {
            var command = new TCommand();

            command.SetUnitOfWork();

            return(command.Execute <T>());
        }
Esempio n. 12
0
        public TCommand Build <TCommand>() where TCommand : ICommand, new()
        {
            TCommand command = new TCommand();

            container.Inject(command);

            return(command);
        }
Esempio n. 13
0
 /// <summary>
 /// Writes logging message for command executing.
 /// </summary>
 /// <param name="command">The command.</param>
 /// <param name="invoker">The invoker.</param>
 protected virtual void WriteCommandExecuting(TCommand command, AddonInvoker invoker)
 {
     Debug.Assert(ShouldLog(LogCategory.CommandExecuting));
     Write(LogCategory.CommandExecuting, Environment.NewLine);
     LogCommand(command);
     Write(LogCategory.CommandExecuting, invoker.IsAsync ? DiagnosticMessages.DbLogger_CommandExecutingAsync(DateTimeOffset.Now) : DiagnosticMessages.DbLogger_CommandExecuting(DateTimeOffset.Now));
     Write(LogCategory.CommandExecuting, Environment.NewLine);
 }
Esempio n. 14
0
        public static TCommand Execute <TCommand>(params object[] args)
            where TCommand : MonoCommand, new()
        {
            GameObject mgGameObject = MonoSingleton.GetMGGameObject();

            object[] attibutes = typeof(TCommand).GetCustomAttributes(true);

            bool         oneItemOnScene = false;
            CommandScope scope          = CommandScope.Application;

            foreach (Attribute eachAttribute in attibutes)
            {
                if (eachAttribute is SingletoneAttribute)
                {
                    oneItemOnScene = true;
                }
                else if (eachAttribute is MonoCommandScopeAttribute)
                {
                    MonoCommandScopeAttribute monoCommandScopeAttribute = (MonoCommandScopeAttribute)eachAttribute;

                    scope = monoCommandScopeAttribute.IsApplication ? CommandScope.Application : CommandScope.Scene;
                }
            }

            if (oneItemOnScene)
            {
                TCommand command = (TCommand)UnityEngine.Object.FindObjectOfType(typeof(TCommand));

                if (command != null)
                {
                    MonoLog.Log(MonoLogChannel.Core, "Found existing command " + command);

                    return(command);
                }
            }

            GameObject target = null;

            if (scope == CommandScope.Application)
            {
                target = new GameObject(typeof(TCommand).Name);
                target.transform.parent = mgGameObject.transform;

                UnityEngine.Object.DontDestroyOnLoad(target);
            }
            else
            {
                target = UIManager.CurrentSceneController.gameObject;
            }

            TCommand result = ExecuteOn <TCommand>(target, args);

            result.Scope = scope;

            return(result);
        }
        protected async Task <IActionResult> ExecuteCommand <TCommand>() where TCommand : class, ICommand <CommandResponse>, new()
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            TCommand command = CreateCommand <TCommand>();

            return(await ExecuteCommand(command));
        }
Esempio n. 16
0
        public TCommand Build <TCommand>(params object[] args) where TCommand : ICommand, new()
        {
            Type commandClass = typeof(TCommand);

            TCommand command = (TCommand)Activator.CreateInstance(commandClass, args);

            container.Inject(command);

            return(command);
        }
Esempio n. 17
0
        private TCommand CreateCommand <TCommand>() where TCommand : class, new()
        {
            TCommand command = new TCommand();

            if (command is IUserContextCommand userContextCommand)
            {
                userContextCommand.AuthenticatedUserId = this.GetUserId();
            }
            return(command);
        }
Esempio n. 18
0
            public Closure(CommandBehaviours <TCommand> context, TCommand command, CancellationToken cancellationToken)
            {
                _context           = context;
                _command           = command;
                _cancellationToken = cancellationToken;

                _next = Execute;

                _position = 0;
            }
Esempio n. 19
0
        protected async Task <IActionResult> ExecuteCommand <TCommand, TResult>() where TCommand : class, ICommand <CommandResponse <TResult> >, new()
        {
            TCommand command = CreateCommand <TCommand>();
            CommandResponse <TResult> response = await Dispatcher.DispatchAsync(command);

            if (response.IsSuccess)
            {
                return(Ok(response.Result));
            }
            return(BadRequest(response.ErrorMessage));
        }
Esempio n. 20
0
            public Task Execute(TCommand command, CancellationToken cancellationToken)
            {
                Closure closure = _closure ?? new Closure(this);

                _closure = null;

                closure.CancellationToken = cancellationToken;
                closure.Command           = command;

                return(closure.Execute());
            }
Esempio n. 21
0
 private void LogCommandExecuting(TCommand command, AddonInvoker invoker)
 {
     if (ShouldLog(LogCategory.CommandExecuting))
     {
         WriteCommandExecuting(command, invoker);
     }
     else
     {
         LogCommand(command);
     }
 }
Esempio n. 22
0
        public TCommand Build <TCommand>(params object[] args) where TCommand : ICommand
        {
            Type commandClass = typeof(TCommand);

            TCommand command = (TCommand)Activator.CreateInstance(commandClass, args);

            _commandPool.AddCommand(command);

            OnNewCommand(command);

            return(command);
        }
Esempio n. 23
0
        /// <inheritdoc />
        public TCommand GetCommand <TCommand>() where TCommand : CompositeCommand, new()
        {
            lock (commands)
            {
                if (!commands.ContainsKey(typeof(TCommand)))
                {
                    commands[typeof(TCommand)] = new TCommand();
                }

                return((TCommand)commands[typeof(TCommand)]);
            }
        }
Esempio n. 24
0
 public TCommand CreateCommand <TCommand>() where TCommand : CommandBase
 {
     try
     {
         TCommand command = this.unityContainer.Resolve <TCommand>();
         return(command);
     }
     catch (Exception ex)
     {
         this.logger.Fatal($"Error while creating the command {typeof(TCommand).Name}.", ex);
         throw;
     }
 }
Esempio n. 25
0
        public virtual TBaseCommand CreateInstance <TBaseCommand, TCommand>() where TCommand : TBaseCommand, IDataEngineCommand, new()
        {
            if (this.DataStorage == null)
            {
                throw new InvalidOperationException(ExceptionText);
            }

            var command = new TCommand();

            command.Initialize(this.DataStorage);

            return(command);
        }
Esempio n. 26
0
        private TCommand getOrCreate <TCommand>()
            where TCommand : ButtonCommand, new()
        {
            ButtonCommand command;

            if (_commands.TryGetValue(typeof(TCommand), out command))
            {
                return((TCommand)command);
            }

            command                     = new TCommand();
            command.Application         = _application;
            _commands[typeof(TCommand)] = command;
            return((TCommand)command);
        }
Esempio n. 27
0
        private void RunBadRequestFromCommandTest <TCommand>()
            where TCommand : BaseCommand <string>, ITestCommand
        {
            TCommand command = Activator.CreateInstance <TCommand>();

            command.ExceptionToThrow = new BadRequestException("test", "Bad Request");

            CommandResult <string> result = this.Execute(command).Result;

            result.IsSuccessful.Should().BeFalse();
            result.Exception.Should().NotBeNull();
            result.Exception.Should().BeOfType <BadRequestException>();

            result.Events.Should().HaveCount(1);
            result.Events.Single().ShouldBeEquivalentTo(CommandExecutionEventType.BadRequest);
        }
Esempio n. 28
0
        public static Boolean RegisterCommandType <TCommand>() where TCommand : INetCommand, new()
        {
            var   inst = new TCommand();
            Type  type = inst.GetType();
            Int32 hash = GetNetworkCoreHash(type);

            if (netCommands.ContainsKey(hash))
            {
                Log.Error("Tried to register a command type with a duplicate hash");
                return(false);
            }
            else
            {
                netCommands[hash] = inst;
                return(true);
            }
        }
Esempio n. 29
0
        private void RunExecuteCommandWithSuccessfulResultTest <TCommand>()
            where TCommand : BaseCommand <string>, ITestCommand
        {
            TCommand     command = Activator.CreateInstance <TCommand>();
            const string value   = "test value";

            command.Response = value;

            CommandResult <string> result = this.Execute(command).Result;

            result.IsSuccessful.Should().BeTrue();
            result.Response.ShouldBeEquivalentTo(value);
            result.Exception.Should().BeNull();

            result.Events.Should().HaveCount(1);
            result.Events.Single().ShouldBeEquivalentTo(CommandExecutionEventType.Success);
        }
Esempio n. 30
0
        /// <summary>
        ///     Gets or creates an instance of a command by type.
        /// </summary>
        /// <typeparam name = "TCommand">The type of command to get or create.</typeparam>
        /// <returns>An instance of <typeparamref name = "TCommand" />.</returns>
        public static ICommand GetCommandInstance <TCommand>() where TCommand : ICommand, new()
        {
            ICommand cmd;

            if (CommandCache.ContainsKey(typeof(TCommand)))
            {
                cmd = CommandCache[typeof(TCommand)];
            }
            else
            {
                cmd          = new TCommand();
                cmd.Services = ApplicationServices.Instance;
                cmd.Settings = ApplicationServices.Instance.Settings;
                CommandCache[typeof(TCommand)] = cmd;
            }

            return(cmd);
        }