public Task Should_Check_For_Correct_Command_Type()
            {
                return(Assert.ThrowsAnyAsync <ArgumentException>(async() =>
                {
                    var commandHandler = new TestCommandHandler(_testOutputHelper);

                    var registration = new CommandHandlerRegistration();
                    registration.Register(() => (ICommandHandler <DoSomethingCommand>)commandHandler);

                    CommandHandlerDelegate commandHandlerDelegate = registration.ResolveCommandHandler <DoSomethingCommand>();

                    Assert.NotNull(commandHandlerDelegate);

                    try
                    {
                        // This delegate handles DoSomethingCommand, but was passed in a DoSomethingWithCancellationCommand.
                        await commandHandlerDelegate.Invoke(new DoSomethingForSpecifiedDurationCommand(100));
                    }
                    catch (Exception ex)
                    {
                        _testOutputHelper.WriteLine(ex.ToString());
                        throw;
                    }
                }));
            }
        /// <summary>
        /// Get the registered command handler which handles the command of the specified type delegate from multiple sources.
        /// </summary>
        /// <typeparam name="TCommand">Type of command to be handled.</typeparam>
        /// <returns>Instance of <see cref="CommandHandlerDelegate"/> which executes the command handler processing.</returns>
        public CommandHandlerDelegate ResolveCommandHandler <TCommand>() where TCommand : class, ICommand
        {
            foreach (ICommandHandlerResolver resolver in _resolvers)
            {
                try
                {
                    CommandHandlerDelegate commandHandlerDelegate = resolver.ResolveCommandHandler <TCommand>();
                    if (commandHandlerDelegate != null)
                    {
                        return(commandHandlerDelegate);
                    }
                }
                catch (Exception ex)
                {
                    if (_exceptionHandler == null)
                    {
                        // No exception handler. Re-throw exception.
                        throw;
                    }

                    bool handled = _exceptionHandler.Invoke(ex);
                    if (!handled)
                    {
                        // Not handled. Re-throw exception.
                        throw;
                    }
                }
            }

            throw ExceptionBuilder.NoCommandHandlerResolvedException(typeof(TCommand));
        }
示例#3
0
 public CommandInfo(
     Type moduleType,
     CommandHandlerDelegate handler,
     Usage primaryUsage,
     IReadOnlyCollection <Usage> aliases,
     IReadOnlyCollection <GuildPermission> userPermissions,
     IReadOnlyCollection <GuildPermission> botPermissions,
     IReadOnlyCollection <ParameterInfo> parameters,
     string description,
     IReadOnlyCollection <string> examples,
     CommandFlags flags,
     string comment)
 {
     ModuleType      = moduleType ?? throw new ArgumentNullException(nameof(moduleType));
     Handler         = handler ?? throw new ArgumentNullException(nameof(handler));
     PrimaryUsage    = primaryUsage ?? throw new ArgumentNullException(nameof(primaryUsage));
     Aliases         = aliases ?? throw new ArgumentNullException(nameof(aliases));
     UserPermissions = userPermissions ?? throw new ArgumentNullException(nameof(userPermissions));
     BotPermissions  = botPermissions ?? throw new ArgumentNullException(nameof(botPermissions));
     Parameters      = parameters ?? throw new ArgumentNullException(nameof(parameters));
     Description     = description ?? throw new ArgumentNullException(nameof(description));
     Examples        = examples ?? throw new ArgumentNullException(nameof(examples));
     Flags           = flags;
     _comment        = comment;
 }
示例#4
0
        public async Task <TRepsonse> HandleAsync(TCommand command, CommandHandlerDelegate <TRepsonse> next)
        {
            TRepsonse response = await next().ConfigureAwait(false);

            await Task.WhenAll(_postProcessors.Select(p => p.ProcessAsync(command, response))).ConfigureAwait(false);

            return(response);
        }
示例#5
0
 public static void HandleChat(WorldSession session, ClientChat chat)
 {
     if (chat.Message.StartsWith("!"))
     {
         CommandManager.ParseCommand(chat.Message, out string command, out string[] parameters);
         CommandHandlerDelegate handler = CommandManager.GetCommandHandler(command);
         handler?.Invoke(session, parameters);
     }
 }
示例#6
0
        private static void Main()
        {
            Directory.SetCurrentDirectory(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location));

            Console.Title = Title;
            log.Info("Initialising...");

            ConfigurationManager <WorldServerConfiguration> .Initialise("WorldServer.json");

            DatabaseManager.Initialise(ConfigurationManager <WorldServerConfiguration> .Config.Database);

            GameTableManager.Initialise();

            EntityManager.Initialise();
            EntityCommandManager.Initialise();

            AssetManager.Initialise();
            ServerManager.Initialise();

            MessageManager.Initialise();
            CommandManager.Initialise();
            NetworkManager <WorldSession> .Initialise(ConfigurationManager <WorldServerConfiguration> .Config.Network);

            WorldManager.Initialise(lastTick =>
            {
                NetworkManager <WorldSession> .Update(lastTick);
                MapManager.Update(lastTick);
            });

            log.Info("Ready!");

            while (true)
            {
                Console.Write(">> ");
                string line = Console.ReadLine();
                CommandManager.ParseCommand(line, out string command, out string[] parameters);

                CommandHandlerDelegate handler = CommandManager.GetCommandHandler(command);
                if (handler != null)
                {
                    try
                    {
                        handler.Invoke(null, parameters);
                    }
                    catch (Exception exception)
                    {
                        log.Error(exception);
                    }
                }
                else
                {
                    Console.WriteLine("Invalid command!");
                }
            }
        }
        public Task SendAsync <TCommand>(TCommand command) where TCommand : ICommand
        {
            var handler = _serviceProvider.GetRequiredService <ICommandHandler <TCommand> >();

            var middlewares = _serviceProvider.GetServices <ICommandMiddleware <TCommand> >();
            CommandHandlerDelegate handlerDelegate = () => handler.HandleAsync(command);
            var resultDelegate = middlewares.Aggregate(handlerDelegate,
                                                       (next, middleware) => () => middleware.HandleAsync(command, next));

            return(resultDelegate());
        }
示例#8
0
        public void UnregisterHandler <T>(CommandHandlerDelegate <T> handler) where T : Command
        {
            var           t = typeof(T);
            List <object> list;

            if (!_handlers.TryGetValue(t, out list))
            {
                return;
            }
            lock (list)
                list.Remove(handler);
        }
示例#9
0
        private static Task <TResult> GetPipeline(TCommand command, CommandHandlerDelegate <TResult> invokeHandler,
                                                  MultiInstanceFactory factory)
        {
            var behaviors = factory(typeof(IPipelineBehavior <TCommand, TResult>))
                            .Cast <IPipelineBehavior <TCommand, TResult> >()
                            .Reverse();

            var aggregate =
                behaviors.Aggregate(invokeHandler, (next, pipeline) => () => pipeline.HandleAsync(command, next));

            return(aggregate());
        }
示例#10
0
        public void RegisterHandler <T>(CommandHandlerDelegate <T> handler) where T : Command
        {
            var           t = typeof(T);
            List <object> list;

            if (!_handlers.TryGetValue(t, out list))
            {
                list         = new List <object>();
                _handlers[t] = list;
            }
            lock (list)
                list.Add(handler);
        }
示例#11
0
 public static void HandleChat(WorldSession session, ClientChat chat)
 {
     if (chat.Message.StartsWith(CommandPrefix))
     {
         try
         {
             CommandManager.ParseCommand(chat.Message, out string command, out string[] parameters);
             CommandHandlerDelegate handler = CommandManager.GetCommandHandler(command);
             handler?.Invoke(session, parameters);
         }
         catch (Exception e)
         {
             log.Warn(e.Message);
         }
     }
 }
示例#12
0
        private void registerCommandHandlerMethod <TAttributed, TCommand>(Func <TAttributed> attributedObjectFactory, CommandHandlerAttributeMethod commandHandlerMethod)
            where TAttributed : class
            where TCommand : class, ICommand
        {
            Type commandType = typeof(TCommand);

            CommandHandlerDelegate handleCommandDelegate;

            if (_commandHandlerDelegatesByCommandType.TryGetValue(commandType, out handleCommandDelegate))
            {
                throw new InvalidOperationException($"Duplicate command handler registered for {commandType.Name}.");
            }

            CommandHandlerDelegate newHandleCommandDelegate = commandHandlerMethod.CreateDelegate <TAttributed, TCommand>(attributedObjectFactory);

            _commandHandlerDelegatesByCommandType.Add(commandType, newHandleCommandDelegate);
        }
示例#13
0
        /// <summary>
        /// Dispatch the command to the registered command handler asynchronously.
        /// </summary>
        /// <typeparam name="TCommand">Type of command to dispatch.</typeparam>
        /// <param name="command">Command to dispatch.</param>
        /// <param name="cancellationToken">Optional cancellation token to support cancellation in command handlers.</param>
        /// <returns>Asynchronous task which completes after the command handler has processed the command.</returns>
        public Task DispatchAsync <TCommand>(TCommand command, CancellationToken cancellationToken = default(CancellationToken)) where TCommand : class, ICommand
        {
            if (command == null)
            {
                throw new ArgumentNullException(nameof(command));
            }

            CommandHandlerDelegate commandHandlerDelegate = _resolver.ResolveCommandHandler <TCommand>();

            if (commandHandlerDelegate == null)
            {
                Type commandType = typeof(TCommand);
                throw new NoCommandHandlerResolvedException($"No command handler is registered to handle command of type: {commandType.Name}.", commandType);
            }

            return(commandHandlerDelegate.Invoke(command, cancellationToken));
        }
            public void Should_Register_All_Command_Handlers()
            {
                var commandHandler = new TestCommandHandler(_testOutputHelper);

                var registration = new CommandHandlerRegistration();

                registration.Register(() => (ICommandHandler <DoSomethingCommand>)commandHandler);

                CommandHandlerDelegate commandHandlerDelegate = registration.ResolveCommandHandler <DoSomethingCommand>();

                Assert.NotNull(commandHandlerDelegate);

                // Delegate should invoke the actual command handler - TestCommandHandler.
                commandHandlerDelegate.Invoke(new DoSomethingCommand());

                Assert.Equal(1, commandHandler.HandledCommands.Count);
                Assert.Contains(commandHandler.HandledCommands, c => c is DoSomethingCommand);
            }
            public async Task Should_Invoke_The_Actual_Registered_Command_Handler()
            {
                var commandHandler = new TestCommandHandler(_testOutputHelper);

                var registration = new CommandHandlerRegistration();

                registration.Register(() => (ICommandHandler <DoSomethingCommand>)commandHandler);

                CommandHandlerDelegate commandHandlerDelegate = registration.ResolveCommandHandler <DoSomethingCommand>();

                Assert.NotNull(commandHandlerDelegate);

                // Invoke.
                await commandHandlerDelegate.Invoke(new DoSomethingCommand());

                // Check if actual command handler instance was invoked.
                Assert.Equal(1, commandHandler.HandledCommands.Count);
                Assert.Contains(commandHandler.HandledCommands, c => c is DoSomethingCommand);
            }
示例#16
0
            public void Should_Register_All_Command_Handlers()
            {
                var container = new Container();

                container.Register <ICommandHandler <DoSomethingCommand> >(() => new TestCommandHandler(_testOutputHelper), Lifestyle.Singleton);

                var containerAdapter = new SimpleInjectorContainerAdapter(container);
                var resolver         = new ContainerCommandHandlerResolver(containerAdapter);

                CommandHandlerDelegate commandHandlerDelegate = resolver.ResolveCommandHandler <DoSomethingCommand>();

                // Delegate should invoke the actual command handler - TestCommandHandler.
                commandHandlerDelegate.Invoke(new DoSomethingCommand());

                // Get instance from container to see if it was invoked.
                var registeredCommandHandler = (TestCommandHandler)container.GetInstance <ICommandHandler <DoSomethingCommand> >();

                Assert.Equal(1, registeredCommandHandler.HandledCommands.Count);
                Assert.Contains(registeredCommandHandler.HandledCommands, c => c is DoSomethingCommand);
            }
        /// <summary>
        /// Register command async handler.
        /// </summary>
        /// <typeparam name="TCommand">Type of command to be handled.</typeparam>
        /// <param name="commandAsyncHandlerFactory">Factory which will provide an instance of a command handler that handles the specified <typeparamref name="TCommand"/> command.</param>
        public void Register <TCommand>(Func <ICommandAsyncHandler <TCommand> > commandAsyncHandlerFactory) where TCommand : class, ICommand
        {
            if (commandAsyncHandlerFactory == null)
            {
                throw new ArgumentNullException(nameof(commandAsyncHandlerFactory));
            }

            Type commandType = typeof(TCommand);

            CommandHandlerDelegate handleCommandDelegate;

            if (_commandHandlerDelegatesByCommandType.TryGetValue(commandType, out handleCommandDelegate))
            {
                throw new InvalidOperationException($"Duplicate command async handler registered for {commandType.Name}.");
            }

            // Create delegate.
            CommandHandlerDelegate newHandleCommandDelegate = CommandHandlerDelegateBuilder.FromFactory(commandAsyncHandlerFactory);

            _commandHandlerDelegatesByCommandType.Add(commandType, newHandleCommandDelegate);
        }
示例#18
0
        private void Run(string[] args)
        {
            var argc = args.Length + 1;                 // args + executable path
            var argv = new string[args.Length + 2];     // args + executable path + null

            argv[0] = ProgramFile;
            args.CopyTo(argv, 1);
            ParseArgumentsC(argc, argv);

            using (_context = new Context())
            {
                _commandHandlerRef = CommandHandler;
                _context.RegisterSubsystem(new Script(_context));
                _context.GetSubsystem <Script>().RegisterCommandHandler(
                    (int)ScriptRuntimeCommand.LoadRuntime, (int)ScriptRuntimeCommand.VerifyAssembly,
                    Marshal.GetFunctionPointerForDelegate(_commandHandlerRef));

                using (var editor = Application.wrap(CreateApplication(Context.getCPtr(_context).Handle), true))
                {
                    Environment.ExitCode = editor.Run();
                }
            }
        }
示例#19
0
 public Command(string text, CommandHandlerDelegate action)
 {
     this.text = text;
     this.action = action;
 }
        public async Task HandleAsync(TRequest request, CommandHandlerDelegate next)
        {
            await CheckOrderAsync(request);

            await next();
        }
示例#21
0
        public async Task Handle(TMessage message, IMessageHandlerContext messageHandlerContext, CommandHandlerDelegate next)
        {
            await next();

            _logger.LogTrace($"Processing outbox messages via {nameof(OutboxProcessingBehavior<TMessage>)}.");
            if (messageHandlerContext.Container.TryGet <TransactionContext>(out var transactionContext))
            {
                transactionContext.Container.TryGet <Guid>("CurrentTransactionId", out var persistanceTransactionId);
                _logger.LogTrace($"Retrieved transaction id '{persistanceTransactionId}' from {nameof(TransactionContext)}.");
                await _outboxProcessor.ProcessBatch(persistanceTransactionId);
            }
            else
            {
                _logger.LogTrace($"No {nameof(TransactionContext)} found. Unable to process outbox messages.");
            }
        }
示例#22
0
        public Task Handle(TMessage message, IMessageHandlerContext messageHandlerContext, CommandHandlerDelegate next)
        {
            _logger.LogDebug($"Entering {nameof(InboxBehavior<TMessage>)}");
            if (messageHandlerContext is IMessageBrokerContext messageBrokerContext)
            {
                return(_brokeredMessageInbox.ReceiveViaInbox(message, messageBrokerContext, () => next()));
            }

            return(next());
        }
示例#23
0
        public async Task Handle(TMessage message, IMessageHandlerContext messageHandlerContext, CommandHandlerDelegate next)
        {
            _logger.LogInformation($"Executed '{this.GetType().Name}'. Pre-delegate.");
            await next();

            _logger.LogInformation($"Executed '{this.GetType().Name}'. Post-delegate.");
        }
            public async Task Handle(ICommand message, IMessageHandlerContext messageHandlerContext, CommandHandlerDelegate next)
            {
                _logger.Log.Add($"behavior one before");
                await next();

                _logger.Log.Add($"behavior one after");
            }
示例#25
0
        public async Task Handle(TMessage message, IMessageHandlerContext messageHandlerContext, CommandHandlerDelegate next)
        {
            if (messageHandlerContext is IMessageBrokerContext messageBrokerContext)
            {
                messageBrokerContext.Container.TryGet <TransactionContext>(out var transactionContext);

                if (!(transactionContext is null))
                {
                    using var scope = new TransactionScope(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled);
                    await next();

                    scope.Complete();
                    return;
                }
            }

            await next();
        }
示例#26
0
        public Task Handle(TMessage message, IMessageHandlerContext messageHandlerContext, CommandHandlerDelegate next)
        {
            if (messageHandlerContext is IMessageBrokerContext messageBrokerContext)
            {
                return(_brokeredMessageInbox.ReceiveViaInbox(message, messageBrokerContext, () => next()));
            }

            return(next());
        }
        public async Task <TResponse> HandleAsync(TCommand request, CommandHandlerDelegate <TResponse> next)
        {
            await Task.WhenAll(_preProcessors.Select(p => p.ProcessAsync(request))).ConfigureAwait(false);

            return(await next().ConfigureAwait(false));
        }
示例#28
0
文件: WsnBase.cs 项目: yguo89/RTOS
        // ===== Methods =========================================

        //
        // Call back function when there is a message in serial port
        //      the raw message is deciphor here.
        //
        private void Connection_ReceivedData(object sender, Packet e)
        {
            object obj = new object();
            CommandHandlerDelegate CommandHandler = new CommandHandlerDelegate(ReturnToUIHandler);

            string[] ParameterDelimeter = { "[", "]" };

            string[] parameters = e.Message.Split(ParameterDelimeter, StringSplitOptions.RemoveEmptyEntries);
            switch (parameters[Commands.CommandOffset])
            {
                case Commands.ReceiveData:
                    {
                        SensorData data = new SensorData("Default",
                                                        DateTime.Now,
                                                        parameters[Commands.SensorDataOffset]);
                        SensorNodeComponentUpdate update = new SensorNodeComponentUpdate(Convert.ToInt16(parameters[Commands.NodeIdOffset]),
                                                                                         Convert.ToInt16(parameters[Commands.PortIdOffset]),
                                                                                         0,
                                                                                         data);
                        if (this.Nodes[update.Node].Ports[update.Port].Sensor.Id == (int)SensorType.SensorId.TiltSensorId)
                        {
                            if (update.Data.Measurement == 0)
                            {
                                update.Data.Unit = "Landscape";
                            }
                            else
                            {
                                update.Data.Unit = "Portait";
                            }
                        }
                        else if (this.Nodes[update.Node].Ports[update.Port].Sensor.Id == (int)SensorType.SensorId.TouchPadSensorId)
                        {
                            if (update.Data.Measurement < 0x10000)  // only one action
                            {
                                update.Data.Unit = update.Data.FindTouchPadKey();
                            }
                            else
                            {
                                int restore_measurement = update.Data.Measurement;
                                string unit = "";
                                update.Data.Measurement /= 0x10000;                     // first action
                                unit = update.Data.FindTouchPadKey();
                                update.Data.Measurement = restore_measurement & 0xFFFF; // second action
                                unit += update.Data.FindTouchPadKey();
                                update.Data.Measurement = restore_measurement;
                                update.Data.Unit = unit;
                            }
                        }
                        else
                        {
                        }

                        obj = update;
                        CommandHandler = ReceiveDataCmdHandler;
                        break;
                    }
                case Commands.FlushData:
                    {
                        break;
                    }
                case Commands.SetNodeSleep:
                    {
                        break;
                    }
                case Commands.SetSampleRate:
                    {
                        break;
                    }
                case Commands.SensorStart:
                    {
                        break;
                    }
                case Commands.SensorStop:
                    {
                        break;
                    }
                case Commands.NewNode:
                    {
                        obj = parameters[Commands.NodeIdOffset];
                        CommandHandler = NewNodeCmdHandler;
                        break;
                    }
                case Commands.DeadNode:
                    {
                        obj = parameters[Commands.NodeIdOffset];
                        CommandHandler = DeadNodeCmdHandler;
                        break;
                    }
                case Commands.UpdateSensor:
                    {
                        SensorNodeComponentUpdate update = new SensorNodeComponentUpdate(Convert.ToInt16(parameters[Commands.NodeIdOffset]),
                                                                                         Convert.ToInt16(parameters[Commands.PortIdOffset]),
                                                                                         Convert.ToInt16(parameters[Commands.SensorDataOffset]),
                                                                                         null);
                        obj = update;
                        CommandHandler = UpdateSensorCmdHandler;
                        break;
                    }
                default:
                    {

                        MessageBox.Show("ERROR: Undefined Command!");
                        break;
                    }
            }

            MyDispatch.Invoke(
            (Action)(() =>
            {
                CommandHandler(obj);
            })
            );
        }
示例#29
0
 public Task Handle(TMessage message, IMessageHandlerContext messageHandlerContext, CommandHandlerDelegate next) => throw new NotImplementedException();