예제 #1
0
 public HelpCommand(IHelpCommandDisplayer display, ICommandContainer commands)
 {
     Name = "?";
     this.commands = commands;
     this.display = display;
     Description = "Causes help.";
 }
예제 #2
0
        public async Task Command_should_be_produced_by_valid_ingestion_service()
        {
            var messagesCollectorMock = new Mock <IAsyncCollector <EventData> >();
            var loggerMock            = new Mock <ILogger>();

            messagesCollectorMock
            .Setup(x => x.AddAsync(It.IsAny <EventData>(), default))
            .Returns(
                Task.CompletedTask
                );

            var command = new DefaultCommand
            {
                Header = new MessageHeader(Guid.NewGuid().ToString(), nameof(DefaultCommand), nameof(Sources.Orchestrator)),
            };

            Producer       producer = new Producer(messagesCollectorMock.Object, loggerMock.Object);
            ProducerResult result   = await producer.ProduceCommandWithRetryAsync(command);

            ICommandContainer commandContainer = DeserializeEventData(result.Message);
            MessageHeader     header           = GetCommandHeader(commandContainer);

            Assert.True(result.Valid);
            Assert.NotEqual(header.MessageId, command.Header.MessageId);
            Assert.NotEqual(header.CreationDate, command.Header.CreationDate);
            Assert.Equal(header.TransactionId, command.Header.TransactionId);
            Assert.Equal(header.MessageType, command.Header.MessageType);
            Assert.Equal(header.Source, command.Header.Source);
        }
예제 #3
0
 public HelpCommand(IHelpCommandDisplayer display, ICommandContainer commands)
 {
     Name          = "?";
     this.commands = commands;
     this.display  = display;
     Description   = "Causes help.";
 }
 public void Register(ICommandContainer container)
 {
     container.Register(Command.For("sampleA").WithDescription("Sample command registration with delegate.").WithHelp("Help for sample command registration delegate").AddAction(() =>
     {
         Console.WriteLine("Sample command execution");
     }));
 }
 public void Register(ICommandContainer container)
 {
     container.Register(Command.For("sampleA").WithDescription("Sample command registration with delegate.").WithHelp("Help for sample command registration delegate").AddAction(() =>
     {
         Console.WriteLine("Sample command execution");
     }));
 }
예제 #6
0
 public CommandContainerManager(ILifetimeScope scope, ICommandContainer container, ILogger <CommandContainerManager> logger)
 {
     CommandContainer     = container;
     CommandContainerType = container.GetType();
     Logger       = logger;
     CurrentScope = scope;
 }
 private async Task DispatchCommandAsync(ICommandContainer commandContainer, string commandType)
 {
     if (processors.ContainsKey(commandType))
     {
         await processors[commandType].ProcessAsync(commandContainer);
     }
 }
예제 #8
0
        /// <summary>
        /// Launch the workitem
        /// </summary>
        public async Task <IObservable <WorkitemEventArgs> > Run()
        {
            // WorkitemID must be set before any operation takes place
            WorkItemID  = Guid.NewGuid().ToString();
            Disposables = new List <IDisposable>();

            var channel = new WorkitemCommunicationChannel();

            communicationChannel = channel;

            BeforeWorkitemRun();

            IsOpen = true;
            await Create().ConfigureAwait(false);

            viewContainer = CreateViewContainer();

            Disposable(viewContainer);
            RegisterViews(viewContainer);

            ICommandContainer container = CreateCommandContainer();

            Disposable(container);
            RegisterCommands(container);

            AfterWorkitemRun();

            return(communicationChannel);
        }
예제 #9
0
 public PortfolioModel(IQueryContainer queries,
                       ICommandContainer commands,
                       UserManager userManager)
 {
     _queries     = queries;
     _commands    = commands;
     _userManager = userManager;
 }
        public void Register(ICommandContainer container)
        {
            container.Register(Command.For("sampleA").WithDescription("Sample command registration with delegate.").WithHelp("Help for sample command registration delegate").AddAction(() =>
            {
                Console.WriteLine("Sample command execution");
            }));

            container.Register(Command.For("sampleB").WithDescription("Sample command registration with class.").WithHelp("Help for sample command registration class").ImplementedBy(new SampleCommandDefinition()));
        }
예제 #11
0
        public static CommandInfo FindCommand(this ICommandContainer root, string name)
        {
            var result = root.Commands.FirstOrDefault(c => c.Name.Equals(name, StringComparison.OrdinalIgnoreCase));

            if (result == null)
            {
                result = root.Commands.FirstOrDefault(c => c.Aliases.Contains(name, StringComparer.OrdinalIgnoreCase));
            }
            return(result);
        }
예제 #12
0
        private CommandTree ParseCommand(
            CommandTreeParserContext context,
            ICommandContainer current,
            CommandTree parent,
            TokenStream stream)
        {
            context.ResetArgumentPosition();

            // Find the command.
            var commandToken = stream.Consume(Token.Type.String);
            var command      = current.FindCommand(commandToken.Value);

            if (command == null)
            {
                throw new CommandAppException($"Unknown command '{commandToken.Value}'.");
            }

            var node = new CommandTree(parent, command);

            while (stream.Peek() != null)
            {
                var token = stream.Peek();
                switch (token.TokenType)
                {
                case Token.Type.LongOption:
                    // Long option
                    ParseOption(context, stream, node, true);
                    break;

                case Token.Type.ShortOption:
                    // Short option
                    ParseOption(context, stream, node, false);
                    break;

                case Token.Type.String:
                    // Command
                    ParseString(context, stream, node);
                    break;

                default:
                    throw new InvalidOperationException("Unknown token type.");
                }
            }

            // Add unmapped parameters.
            foreach (var parameter in node.Command.Parameters)
            {
                if (node.Mapped.All(m => m.Item1 != parameter))
                {
                    node.Unmapped.Add(parameter);
                }
            }

            return(node);
        }
        public async Task ProcessCommandAsync(ICommandContainer commandContainer)
        {
            if (commandContainer == null)
            {
                throw new ArgumentException();
            }

            MessageHeader header      = GetCommandHeader(commandContainer);
            string        commandType = GetCommandType(header);

            await DispatchCommandAsync(commandContainer, commandType);
        }
예제 #14
0
 public void RaiseCommand()
 {
     if (!string.IsNullOrEmpty(Command))
     {
         ICommandContainer container = Container as ICommandContainer;
         if (container != null)
         {
             CommandEventArgs e = new CommandEventArgs(Command, this, null);
             container.RaiseCommand(e);
         }
     }
 }
        public void Register(ICommandContainer container)
        {
            container.Register(Command.For("help").WithDescription("Provides Help information for commands.").AddAction((args) =>
            {
                if (args == null || args.Length == 0)
                {
                    Console.WriteLine("For more information on a specific command, type HELP command-name");
                    var maxCommandLength = container.Commands.Max(x => x.Key.Length);
                    var marginLeft = maxCommandLength + 5;
                    var rigthPartPos = marginLeft % Console.BufferWidth;
                    var chunkSize = Console.BufferWidth - rigthPartPos;
                    var displayFormat = "{0,-" + marginLeft + "}";
                    foreach (var item in container.Commands.OrderBy(x => x.Key))
                    {
                        var leftPart = string.Format(displayFormat, item.Key.ToUpper());
                        Console.Write(leftPart);

                        if (item.Description.Length > chunkSize)
                        {
                            var chunks = new List<string>();
                            chunks.AddRange(Enumerable.Range(0, item.Description.Length / chunkSize).Select(i => item.Description.Substring(i * chunkSize, chunkSize)));
                            chunks.Add(item.Description.Length % chunkSize > 0 ? item.Description.Substring((item.Description.Length / chunkSize) * chunkSize, item.Description.Length - ((item.Description.Length / chunkSize) * chunkSize)) : string.Empty);
                            foreach (var chunk in chunks)
                            {
                                var rigthPart = string.Format("{0,-" + (rigthPartPos - Console.CursorLeft) + "}{1}",
                                    string.Empty, chunk);
                                if (chunk.Length == chunkSize)
                                    Console.Write(rigthPart);
                                else
                                    Console.WriteLine(rigthPart);
                            }
                        }
                        else
                        {
                            Console.WriteLine(item.Description);
                        }
                    }
                }
                else
                {
                    var command = container.Commands.FirstOrDefault(x => string.Compare(x.Key, args[0], StringComparison.InvariantCultureIgnoreCase) == 0);
                    if (command == null)
                        Console.WriteLine("Command '{0}' not found.", args[0]);
                    else if (!string.IsNullOrEmpty(command.Help))
                        Console.WriteLine(command.Help);
                }
            }));

            container.Register(Command.For("exit").WithDescription("Exits power shell.").WithHelp("Enter EXIT to close the program").AddAction(() =>
            {
                Environment.Exit(0);
            }));
        }
예제 #16
0
 public SignalCommandBinding(
     ICommandContainer container,
     object key,
     object name,
     Resolver resolver) :
     base(
         container,
         key,
         name,
         resolver)
 {
 }
예제 #17
0
        public CommandBinding(ICommandContainer container,
                              object key,
                              object name,
                              Resolver resolver)
            : base(key,
                   name,
                   resolver)
        {
            Requires.NotNull(container, nameof(container));

            this.container = container;
        }
예제 #18
0
        /// <summary>
        /// Executes a CommandChain from the beginning.
        /// </summary>
        /// <param name="commandChain"></param>
        /// <param name="onlyIFinallyCommands">indicates errors, if true only finally commands are executed. If an finally command throws an exceptions, remaining finally commands are still executed.</param>
        protected virtual void Execute(IList <ICommandContainer> commandChain, bool onlyIFinallyCommands, CommandRegistryFinishedCallback registryFinishedCallback = null)
        {
            if (commandChain.Count < 1)
            {
                String error = "It is not allowed to call execute with a command-chain of size zero.";
                Log.Error(error);
                throw new ArgumentException(error);
            }
            ICommandContainer commandContainer = commandChain[0];

            if (onlyIFinallyCommands)
            {
                if (!(commandContainer.Command is IFinallyCommand))
                {
                    ExecuteRecursion(commandChain, onlyIFinallyCommands, registryFinishedCallback);
                    return;
                }
            }
            ICommand command          = commandContainer.Command;
            Object   commandParameter = commandContainer.CommandParameter;

            if ((command is IAsyncCommand) || ((command is CommandRegistry) && ((CommandRegistry)command).IsAsync))
            {
                // The command works asynchronously, thus we must wait until all operations initiated by the command
                // are finished, before we can go on with the next command.
                // Therefore, we acquire a unique Id to identify the async command and we associate the index of the
                // following command with this index.
                IAsyncCommand asyncCommand = (IAsyncCommand)command;

                long processSequenceId = AcquireCommand();

                // The async command is called with the NextCommand delegate:
                asyncCommand.Execute(commandParameter, delegate(bool success)
                {
                    //commandChain, processSequenceId and onlyIFinallyCommands are stored (closure).
                    AsyncExecuteRecursion(commandChain, processSequenceId, success, onlyIFinallyCommands, registryFinishedCallback);
                });
                return;
            }

            // The command works synchronously, thus we can directly proceed with the next command:
            try
            {
                command.Execute(commandParameter);
            }
            catch (Exception ex)
            {
                Log.Warn("Execution of the command '" + command.GetType().Name + "' with parameter '" + commandParameter.GetType().Name + "' lead to the following exception: " + ex);
                onlyIFinallyCommands = true;
            }
            ExecuteRecursion(commandChain, onlyIFinallyCommands, registryFinishedCallback);
        }
예제 #19
0
        private static XmlDocument Serialize(ICommandContainer model)
        {
            var document = new XmlDocument();
            var root     = document.CreateElement("model");

            foreach (var command in model.Commands)
            {
                root.AppendChild(document.CreateComment(command.Name.ToUpperInvariant()));
                root.AppendChild(CreateCommandNode(document, command));
            }
            document.AppendChild(root);
            return(document);
        }
        public static CommandInfo?FindCommand(this ICommandContainer root, string name, CaseSensitivity sensitivity)
        {
            var result = root.Commands.FirstOrDefault(
                c => c.Name.Equals(name, sensitivity.GetStringComparison(CommandPart.CommandName)));

            if (result == null)
            {
                result = root.Commands.FirstOrDefault(
                    c => c.Aliases.Contains(name, sensitivity.GetStringComparer(CommandPart.CommandName)));
            }

            return(result);
        }
예제 #21
0
        /// <summary>
        /// Add all commands in a command container
        /// </summary>
        /// <param name="container"></param>
        internal void AddCommands(ICommandContainer container)
        {
            MethodInfo[] methods = container.GetType().GetMethods();
            for (int i = 0; i < methods.Length; i++)
            {
                MethodInfo method = methods[i];

                if (method.GetCustomAttribute <Command>() != null)
                {
                    AddCommand(container, method);
                }
            }
        }
예제 #22
0
 public bool TryReadCommand(out ICommandContainer commandTransport)
 {
     if (_commandTransports.Any())
     {
         // TODO: fix thread safety
         return(_commandTransports.TryRemove(_commandTransports.Keys.First(), out commandTransport));
     }
     else
     {
         commandTransport = default;
         return(false);
     }
 }
예제 #23
0
 /// <summary>
 /// Adds or set the command.
 /// </summary>
 /// <param name="key">The command key.</param>
 /// <param name="command">The command.</param>
 public void AddOrSetCommand(string key, ICommandContainer command)
 {
     if (string.IsNullOrEmpty(key) == false)
     {
         if (this.commandContainers.Any(k => k.Key == key))
         {
             this.commandContainers[key] = command;
         }
         else
         {
             this.commandContainers.AddOrUpdate(key, command, (exkey, excmd) => command);
         }
     }
 }
예제 #24
0
        public virtual void UnregisterCommand(ICommand command, String parameterKey, int priority)
        {
            CommandKey        commandKey       = new CommandKey(command, parameterKey, priority);
            ICommandContainer commandContainer = keyToCommandContainer.GetExtension(commandKey);

            if (!AlwaysExecutable)
            {
                commandContainer.CanExecuteChanged -= OnCanExecuteChanged;
            }
            if ((command is IAsyncCommand) || ((command is CommandRegistry) && ((CommandRegistry)command).IsAsync))
            {
                --nAsyncCommandsRegistered;
            }
            keyToCommandContainer.Unregister(commandContainer, commandKey);
        }
예제 #25
0
 public virtual void RaiseCommand(CommandEventArgs e)
 {
     if (Command != null)
     {
         Command(this, e);
     }
     if (!e.Handled)
     {
         ICommandContainer container = this.Container as ICommandContainer;
         if (container != null)
         {
             container.RaiseCommand(e);
         }
     }
 }
예제 #26
0
        public async Task ProcessAsync(ICommandContainer commandContainer)
        {
            var validateCommand = commandContainer.ParseCommand <IssueReceiptCommand>();

            var header  = validateCommand.Header;
            var content = validateCommand.Content;

            try
            {
                await CreateReceiptAsync(header, content);
            }
            catch (Exception exception)
            {
                await ProcessFailure(header, exception);
            }
        }
        public async Task ProcessAsync(ICommandContainer commandContainer)
        {
            var validateCommand = commandContainer.ParseCommand <CancelTransferCommand>();

            var header  = validateCommand.Header;
            var content = validateCommand.Content;

            try
            {
                await CancelTransferAsync(header, content);
            }
            catch (Exception exception)
            {
                await ProcessCancellationFailureAsync(header, exception);
            }
        }
예제 #28
0
        private CommandTree ParseCommand(
            CommandTreeParserContext context,
            ICommandContainer current,
            CommandTree parent,
            CommandTreeTokenStream stream)
        {
            // Find the command.
            var commandToken = stream.Consume(CommandTreeToken.Kind.String);
            var command      = current.FindCommand(commandToken.Value);

            if (command == null)
            {
                throw ParseException.UnknownCommand(_configuration, parent, context.Arguments, commandToken);
            }

            return(ParseCommandParameters(context, command, parent, stream));
        }
예제 #29
0
        protected BotProgram()
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            _logger.Info("Starting Bot v{0} on {1}({2})", Assembly.GetEntryAssembly().GetName().Version, Environment.MachineName, Environment.OSVersion.VersionString);

            //Configure Dependency Injection
            IServiceCollection serviceCollection = new ServiceCollection();

            ConfigureServices(serviceCollection);
            serviceCollection.AddSingleton(_discordClient);
            serviceCollection.TryAddSingleton(new BotConfiguration());  //Add default bot configuration if not already added
            IServiceProvider serviceProvider = serviceCollection.BuildServiceProvider();

            //Configure Command Container
            BotConfiguration  config    = serviceProvider.GetService <BotConfiguration>();
            ICommandContainer container = BuildCommandContainer();

            container.AddCommandHandler <HelpCommand>();
            container.AddCommandHandler <PrivateCommand>();
            container.AddCommandHandler <PingCommand>();
            if (config.EnableDebugCommandsForAdmins)
            {
                container.AddCommandHandler <InspectDscCommand>();
                container.AddCommandHandler <InfoCommand>();
            }
            else
            {
                _logger.Debug("Debug commands are disabled. Not adding them to command container");
            }
            _logger.Info("Added {0} command(s) to container", container.Count());
            serviceCollection.AddSingleton(container);
            serviceProvider = serviceCollection.BuildServiceProvider(); //Build ServiceProvider agein with ICommandContainer

            //Configure global filter
            IEnumerable <CommandFilter> globalFilter = ConfigureGlobalFilter().ToList();

            foreach (CommandFilter commandFilter in globalFilter)
            {
                _logger.Debug("Loaded global filter \"{0}\"", commandFilter.GetType().FullName);
            }
            _logger.Info("Added {0} global filter(s)", globalFilter.Count());

            //Configure Event Handler
            _newMessageHandler = new NewMessageHandler(serviceProvider, container, globalFilter);
        }
예제 #30
0
        public CommandHelp(ILifetimeScope scope, ICommandContainer container, ICommandContainerManager manager)
        {
            CommandContainerType = container.GetType();
            var containerLoggerType = typeof(ILogger <>).MakeGenericType(CommandContainerType);

            Logger = scope.Resolve(containerLoggerType) as ILogger;

            CommandInformation = new Dictionary <string, CommandInfo>();
            foreach (var(methodInfo, handlerAttr, _) in manager.ResolveHandlers())
            {
                var description = methodInfo.GetCustomAttribute <CommandDescriptionAttribute>()?.Description ?? "-";
                CommandInformation.Add(handlerAttr.Command, new CommandInfo()
                {
                    Name        = handlerAttr.Command,
                    Description = description
                });
            }
        }
예제 #31
0
        /// <summary>
        /// Initializes a new instance of the <see cref="UserInterfaceService"/> class.
        /// </summary>
        /// <param name="container">The container that stores all the references for the application.</param>
        /// <param name="onStartService">
        ///     The method that stores the IOC container that contains the references for the entire application.
        /// </param>
        /// <param name="diagnostics">The object that provides the diagnostics methods for the application.</param>
        /// <exception cref="ArgumentNullException">
        /// Thrown if <paramref name="container"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="ArgumentNullException">
        /// Thrown when <paramref name="onStartService"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="ArgumentNullException">
        ///     Thrown if <paramref name="diagnostics"/> is <see langword="null" />.
        /// </exception>
        public UserInterfaceService(IContainer container, Action <IContainer> onStartService, SystemDiagnostics diagnostics)
            : base(diagnostics)
        {
            {
                Enforce.Argument(() => container);
                Enforce.Argument(() => onStartService);
            }

            m_Container         = container;
            m_NotificationNames = container.Resolve <INotificationNameConstants>();
            m_Diagnostics       = container.Resolve <SystemDiagnostics>();
            m_OnStartService    = onStartService;

            m_Commands = container.Resolve <ICommandContainer>();
            {
                m_Commands.Add(
                    ShutdownApplicationCommand.CommandId,
                    () => new ShutdownApplicationCommand(() => m_Core.Shutdown()));

                m_Commands.Add(
                    CreateProjectCommand.CommandId,
                    () => new CreateProjectCommand(
                        () =>
                {
                    m_Projects.CreateNewProject();
                    return(m_Projects.Current);
                }));

                m_Commands.Add(
                    LoadProjectCommand.CommandId,
                    () => new LoadProjectCommand(
                        persistenceInformation =>
                {
                    m_Projects.LoadProject(persistenceInformation);
                    return(m_Projects.Current);
                }));

                m_Commands.Add(
                    UnloadProjectCommand.CommandId,
                    () => new UnloadProjectCommand(() => m_Projects.UnloadProject()));
            }
        }
예제 #32
0
        private static Task RegisterCommands(ICommandContainer container)
        {
            try
            {
                Task.WaitAll(new[]
                {
                    container.AddModuleAsync <TeleportModule>(),
                    container.AddModuleAsync <ButcherModule>(),
                    container.AddModuleAsync <ItemModule>(),
                    container.AddModuleAsync <CharacterModule>(),
                    container.AddModuleAsync <HelpModule>()
                });
            }
            catch (Exception e)
            {
                Log.Debug(e.StackTrace);
            }

            return(Task.CompletedTask);
        }
예제 #33
0
        protected virtual void OnCanExecuteChanged(Object sender, EventArgs e)
        {
            ICommandContainer sendingContainer = (ICommandContainer)sender;

            if (!GuiThreadHelper.IsInGuiThread())
            {
                String error = "The command " + sendingContainer.Command.GetType().FullName + " has fired CanExecuteChanged from a non-UI thread. This is illegal!";
                Log.Error(error);
                throw new Exception(error);
            }
            // CanExecuteChanged may be expensive methods for some registered commands
            // => avoid unnecessary evaluations
            if (canExecuteChangedState == null)
            {
                // State was never set => set it for the first time
                DetermineCanExecuteChangedState();
                RaiseCanExecuteChanged();
                return;
            }
            bool senderState = sendingContainer.Command.CanExecute(sendingContainer.CommandParameter);

            if (senderState == canExecuteChangedState)
            {
                // Senders state equals total state => no need to evaluate other states and no need to fire event
                return;
            }
            if (canExecuteChangedState == true)
            {
                // total state is true and senders state is false => set total to false and fire event
                canExecuteChangedState = false;
                RaiseCanExecuteChanged();
                return;
            }
            // total state is false, but senders state has turned to true => check whether there is any
            // other command with state false => if not, change total state to true and fire event
            DetermineCanExecuteChangedState();
            if (canExecuteChangedState == true)
            {
                RaiseCanExecuteChanged();
            }
        }
예제 #34
0
        /// <summary>
        /// Initializes a new instance of the <see cref="UserInterfaceService"/> class.
        /// </summary>
        /// <param name="container">The container that stores all the references for the application.</param>
        /// <param name="onStartService">
        ///     The method that stores the IOC container that contains the references for the entire application.
        /// </param>
        /// <param name="diagnostics">The object that provides the diagnostics methods for the application.</param>
        /// <exception cref="ArgumentNullException">
        /// Thrown if <paramref name="container"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="ArgumentNullException">
        /// Thrown when <paramref name="onStartService"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="ArgumentNullException">
        ///     Thrown if <paramref name="diagnostics"/> is <see langword="null" />.
        /// </exception>
        public UserInterfaceService(IContainer container, Action<IContainer> onStartService, SystemDiagnostics diagnostics)
            : base(diagnostics)
        {
            {
                Enforce.Argument(() => container);
                Enforce.Argument(() => onStartService);
            }

            m_Container = container;
            m_NotificationNames = container.Resolve<INotificationNameConstants>();
            m_Diagnostics = container.Resolve<SystemDiagnostics>();
            m_OnStartService = onStartService;

            m_Commands = container.Resolve<ICommandContainer>();
            {
                m_Commands.Add(
                    ShutdownApplicationCommand.CommandId,
                    () => new ShutdownApplicationCommand(() => m_Core.Shutdown()));

                m_Commands.Add(
                    CreateProjectCommand.CommandId,
                    () => new CreateProjectCommand(
                        () =>
                        {
                            m_Projects.CreateNewProject();
                            return m_Projects.Current;
                        }));

                m_Commands.Add(
                   LoadProjectCommand.CommandId,
                   () => new LoadProjectCommand(
                       persistenceInformation =>
                       {
                           m_Projects.LoadProject(persistenceInformation);
                           return m_Projects.Current;
                       }));

                m_Commands.Add(
                   UnloadProjectCommand.CommandId,
                   () => new UnloadProjectCommand(() => m_Projects.UnloadProject()));
            }
        }