private void RegisterCommand(IConsoleCommand commandObj)
 {
     if (!availableCommands.ContainsKey(commandObj.Command.ToLower()))
     {
         availableCommands.Add(commandObj.Command.ToLower(), commandObj);
     }
 }
Example #2
0
        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);
            Services.AddService(typeof(SpriteBatch), spriteBatch);

            player = new Player(this);
            var commands = new IConsoleCommand[] { new MovePlayerCommand(player), new RotatePlayerDegreesCommand(player) };
            console = new GameConsole(this, spriteBatch, commands, new GameConsoleOptions
                                                                       {
                                                                           Font = Content.Load<SpriteFont>("GameFont"),
                                                                           FontColor = Color.LawnGreen,
                                                                           Prompt = "~>",
                                                                           PromptColor = Color.Crimson,
                                                                           CursorColor = Color.OrangeRed,
                                                                           BackgroundColor = new Color(Color.Black,150),
                                                                           PastCommandOutputColor = Color.Aqua,
                                                                           BufferColor = Color.Gold
                                                                       });
            console.AddCommand("rotRad", a =>
                                             {
                                                 var angle = float.Parse(a[0]);
                                                 player.Angle = angle;
                                                 return String.Format("Rotated the player to {0} radians", angle);
                                             });
            base.Initialize();
        }
Example #3
0
 internal CommandData(string name, bool essential, string description, IConsoleCommand command)
 {
     Name        = name;
     Description = description;
     Essential   = essential;
     Command     = command;
 }
Example #4
0
        public bool Execute(IDebugConsole console, params string[] args)
        {
            switch (args.Length)
            {
            case 0:
                console.AddLine("To display help for a specific command, write 'help <command>'. To list all available commands, write 'list'.", Color.White);
                break;

            case 1:
                string commandname = args[0];
                if (!console.Commands.ContainsKey(commandname))
                {
                    if (!IoCManager.Resolve <INetworkManager>().IsConnected)
                    {
                        // No server so nothing to respond with unknown command.
                        console.AddLine("Unknown command: " + commandname, Color.Red);
                        return(false);
                    }
                    // TODO: Maybe have a server side help?
                    return(false);                            // return true;
                }
                IConsoleCommand command = console.Commands[commandname];
                console.AddLine(string.Format("{0} - {1}", command.Command, command.Description), Color.White);
                console.AddLine(command.Help, Color.White);
                break;

            default:
                console.AddLine("Invalid amount of arguments.", Color.Red);
                break;
            }
            return(false);
        }
        private void ExecuteCommand(string commandLine)
        {
            List <string> args = new List <string>(commandLine.Split(' '));

            if (args.Count == 0)
            {
                return;
            }
            string cmd = args[0].ToLower();

            try
            {
                IConsoleCommand command = AvailableCommands[cmd];
                args.RemoveAt(0);
                command.Execute(args.ToArray());
            }
            catch (KeyNotFoundException)
            {
                Con.ForegroundColor = ConsoleColor.Red;
                Con.WriteLine("Unknown command: '{0}'", cmd);
                Con.ResetColor();
            }
            catch (Exception e)
            {
                Con.ForegroundColor = ConsoleColor.Red;
                Con.WriteLine("There was an error while executing the command:\n{0}", e);
                Con.ResetColor();
            }
        }
Example #6
0
        public static void ShowCommandHelp(IConsoleCommand selectedCommand, TextWriter console, bool skipExeInExpectedUsage = false)
        {
            var haveOptions = selectedCommand.GetActualOptions().Count > 0;

            console.WriteLine();
            console.WriteLine("'" + ConsoleUtil.FormatCommandName(selectedCommand.Command) + "' - " + selectedCommand.OneLineDescription);
            console.WriteLine();

            if (!string.IsNullOrEmpty(selectedCommand.LongDescription))
            {
                console.WriteLine(selectedCommand.LongDescription);
                console.WriteLine();
            }

            console.Write("Expected usage:");

            if (!skipExeInExpectedUsage)
            {
                console.Write(" " + AppDomain.CurrentDomain.FriendlyName);
            }

            console.Write(" " + selectedCommand.Command);

            if (haveOptions)
                console.Write(" <options> ");

            console.WriteLine((haveOptions? "":" ") + selectedCommand.RemainingArgumentsHelpText);

            if (haveOptions)
            {
                console.WriteLine("<options> available:");
                selectedCommand.GetActualOptions().WriteOptionDescriptions(console);
            }
            console.WriteLine();
        }
Example #7
0
        private string GetFullParameterDescription(PropertyInfo property, IConsoleCommand command)
        {
            var name = Name ?? property.Name;

            if (IsRequired == false)
            {
                name = "Type [default] to use default value: \"" + property.GetValue(command) + "\"\n" + name;
            }

            if (!string.IsNullOrEmpty(Description))
            {
                name = Description + "\n" + name;
            }
            else
            {
                dynamic displayAttribute = property.GetCustomAttributes().SingleOrDefault(a => a.GetType().Name == "DisplayAttribute");
                if (displayAttribute != null && !string.IsNullOrEmpty(displayAttribute.Description))
                {
                    name = displayAttribute.Description + "\n" + name;
                }
                else
                {
                    dynamic descriptionAttribute = property.GetCustomAttributes().SingleOrDefault(a => a.GetType().Name == "DescriptionAttribute");
                    if (descriptionAttribute != null)
                    {
                        name = descriptionAttribute.Description + "\n" + name;
                    }
                }
            }

            return(name + ": ");
        }
Example #8
0
        public ICommandHelp GetCommandHelp(IConsoleCommand consoleCommand)
        {
            var cacheKey = $"{consoleCommand.GetType().Name}-{System.Threading.Thread.CurrentThread.CurrentUICulture.Name}";

            return(DataCache.GetCachedData <ICommandHelp>(new CacheItemArgs(cacheKey, CacheItemPriority.Low),
                                                          c => GetCommandHelpInternal(consoleCommand)));
        }
Example #9
0
        public GameConsoleComponent(GameConsole console, Game game, SpriteBatch spriteBatch)
            : base(game)
        {
            this.console = console;
            EventInput.Initialize(game.Window);
            this.spriteBatch = spriteBatch;
            AddPresetCommands();
            inputProcesser        = new InputProcessor(new CommandProcesser());
            inputProcesser.Open  += (s, e) => renderer.Open();
            inputProcesser.Close += (s, e) => renderer.Close();

            renderer = new Renderer(game, spriteBatch, inputProcesser);
            var inbuiltCommands = new IConsoleCommand[]
            {
                new ClearScreenCommand(inputProcesser),
                new ExitCommand(game),
                new MouseCommand(game),
                new TitleCommand(game),
                new PromptCommand(game),
                new BugCommand(game),
                new HelpCommand()
            };

            GameConsoleOptions.Commands.AddRange(inbuiltCommands);
        }
 private static void ValidateConsoleCommand(IConsoleCommand command)
 {
     if (string.IsNullOrEmpty(command.Command))
     {
         throw new InvalidOperationException($"Command {command.GetType().Name} did not call IsCommand in its constructor to indicate its name and description.");
     }
 }
Example #11
0
 public static void PrintCommandDescription(
     this IConsoleCommand command,
     string commandKey,
     string shortDescription)
 {
     Console.WriteLine("\t{0}:\t{1}", commandKey, shortDescription);
 }
Example #12
0
        public void Execute(IConsoleShell shell, string argStr, string[] args)
        {
            switch (args.Length)
            {
            case 0:
                shell.WriteLine("To display help for a specific command, write 'help <command>'. To list all available commands, write 'list'.");
                break;

            case 1:
                string commandname = args[0];
                if (!shell.ConsoleHost.RegisteredCommands.ContainsKey(commandname))
                {
                    if (!IoCManager.Resolve <IClientNetManager>().IsConnected)
                    {
                        // No server so nothing to respond with unknown command.
                        shell.WriteError("Unknown command: " + commandname);
                        return;
                    }
                    // TODO: Maybe have a server side help?
                    return;
                }
                IConsoleCommand command = shell.ConsoleHost.RegisteredCommands[commandname];
                shell.WriteLine(string.Format("{0} - {1}", command.Command, command.Description));
                shell.WriteLine(command.Help);
                break;

            default:
                shell.WriteError("Invalid amount of arguments.");
                break;
            }
        }
Example #13
0
        protected override async Task FileSystemConsoleHandlerAsync(IConsoleCommand <ConsoleCommandCode> command)
        {
            var response = await this.Service.PerformCommandAsync(
                new CommandRequest()
            {
                UserName    = this.User.Credentials.UserName,
                Token       = this.User.Credentials.Token,
                CommandLine = command.CommandLine
            }
                );

            if (response is null)
            {
                string message = ServerReturnedNullResponseMessage;
                throw new FaultException <CommandFault>(
                          new CommandFault()
                {
                    UserName    = this.User.Credentials.UserName,
                    CommandLine = command.CommandLine
                },
                          message
                          );
            }

            this.WriteLine(response.ResponseMessage);
        }
 static void RegisterCommand(IConsoleCommand command)
 {
     foreach (var key in command.Keys)
     {
         Commands.Add(key, command);
     }
 }
Example #15
0
        static ConsoleCommandInfo BuildCommandInfo(IConsoleCommand command)
        {
            var info = BuildCommandInfo(command.GetType());

            info.Instance = command;
            return(info);
        }
Example #16
0
        /// <summary>
        /// Processes commands (chat messages starting with /)
        /// </summary>
        /// <param name="text">input text</param>
        private void ProcessCommand(string text)
        {
            //Commands are processed locally and then sent to the server to be processed there again.
            var args = new List <string>();

            CommandParsing.ParseArguments(text, args);

            string commandname = args[0];

            //Entity player;
            //var entMgr = IoCManager.Resolve<IEntityManager>();
            //var plrMgr = IoCManager.Resolve<IPlayerManager>();
            //player = plrMgr.ControlledEntity;
            //IoCManager.Resolve<INetworkManager>().

            bool forward = true;

            if (commands.ContainsKey(commandname))
            {
                IConsoleCommand command = commands[commandname];
                args.RemoveAt(0);
                forward = command.Execute(this, args.ToArray());
            }
            else if (!IoCManager.Resolve <INetworkManager>().IsConnected)
            {
                AddLine("Unknown command: " + commandname, Color.Red);
                return;
            }

            if (forward)
            {
                SendServerConsoleCommand(text);
            }
        }
        public CommandHelp GetCommandHelp(string[] args, IConsoleCommand consoleCommand)
        {
            var cacheKey = (string.Join("_", args) + "_" + PortalController.Instance.GetCurrentSettings()?.DefaultLanguage).Replace("-", "_");

            return(DataCache.GetCachedData <CommandHelp>(new CacheItemArgs(cacheKey, CacheItemPriority.Low),
                                                         c => this.GetCommandHelpInternal(consoleCommand)));
        }
Example #18
0
        private async Task AuthorizeAsync(IConsoleCommand <ConsoleCommandCode> command)
        {
            if (command is null)
            {
                throw new ArgumentNullException(nameof(command));
            }

            if (command.CommandCode != ConsoleCommandCode.Connect)
            {
                throw new ArgumentException(
                          paramName: nameof(command),
                          message: Invariant($"Command is not the '{nameof(ConsoleCommandCode.Connect)}' command.")
                          );
            }

            string userName;

            if (command.Parameters.Count == 0 || string.IsNullOrWhiteSpace(userName = command.Parameters[0]))
            {
                this.WriteLine("User name not specified.");
                return;
            }

            if (!(this.User.Credentials is null))
            {
                if (!UserNameComparer.Equals(this.User.Credentials.UserName, userName))
                {
                    this.WriteLine(Invariant($"Please disconnect current user ('{this.User.Credentials.UserName}') before connect new user."));
                    return;
                }
            }

            await this.ProcessOperationAsync <TAuthorizeException>(async() => await this.AuthorizeHandlerAsync(userName));
        }
Example #19
0
        private ICommandHelp GetCommandHelpInternal(IConsoleCommand consoleCommand)
        {
            var commandHelp = new CommandHelp();

            if (consoleCommand != null)
            {
                var cmd  = consoleCommand.GetType();
                var attr = cmd.GetCustomAttributes(typeof(ConsoleCommandAttribute), false).FirstOrDefault() as ConsoleCommandAttribute ?? new ConsoleCommandAttribute(CreateCommandFromClass(cmd.Name), Constants.CommandCategoryKeys.General, $"Prompt_{cmd.Name}_Description");
                commandHelp.Name        = attr.Name;
                commandHelp.Description = LocalizeString(attr.DescriptionKey, consoleCommand.LocalResourceFile);
                var commandParameters = cmd.GetFields(BindingFlags.NonPublic | BindingFlags.Static)
                                        .Select(x => x.GetCustomAttributes(typeof(ConsoleCommandParameterAttribute), false).FirstOrDefault())
                                        .Cast <ConsoleCommandParameterAttribute>().ToList();
                if (commandParameters.Any())
                {
                    var options = commandParameters.Where(attribute => attribute != null).Select(attribute => new CommandOption
                    {
                        Name         = attribute.Name,
                        Required     = attribute.Required,
                        DefaultValue = attribute.DefaultValue,
                        Description  =
                            LocalizeString(attribute.DescriptionKey, consoleCommand.LocalResourceFile)
                    }).ToList();
                    commandHelp.Options = options;
                }
                commandHelp.ResultHtml = consoleCommand.ResultHtml;
            }
            else
            {
                commandHelp.Error = LocalizeString("Prompt_CommandNotFound");
            }
            return(commandHelp);
        }
        public static void ShowParsedCommand(IConsoleCommand consoleCommand, TextWriter consoleOut)
        {
            if (!consoleCommand.TraceCommandAfterParse)
            {
                return;
            }

            var skippedProperties = new [] {
                "Command",
                "OneLineDescription",
                "LongDescription",
                "Options",
                "TraceCommandAfterParse",
                "RemainingArgumentsCount",
                "RemainingArgumentsHelpText",
                "RequiredOptions"
            };

            var properties = consoleCommand.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)
                             .Where(p => !skippedProperties.Contains(p.Name));

            var fields = consoleCommand.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance)
                         .Where(p => !skippedProperties.Contains(p.Name));

            var allValuesToTrace = new Dictionary <string, string>();

            foreach (var property in properties)
            {
                var value = property.GetValue(consoleCommand, new object[0]);
                allValuesToTrace[property.Name] = value?.ToString() ?? "null";
            }

            foreach (var field in fields)
            {
                allValuesToTrace[field.Name] = MakeObjectReadable(field.GetValue(consoleCommand));
            }

            consoleOut.WriteLine();

            string introLine = $"Executing {consoleCommand.Command}";

            if (string.IsNullOrEmpty(consoleCommand.OneLineDescription))
            {
                introLine = introLine + ":";
            }
            else
            {
                introLine = introLine + " (" + consoleCommand.OneLineDescription + "):";
            }

            consoleOut.WriteLine(introLine);

            foreach (var value in allValuesToTrace.OrderBy(k => k.Key))
            {
                consoleOut.WriteLine("    " + value.Key + " : " + value.Value);
            }

            consoleOut.WriteLine();
        }
Example #21
0
        public CommandHelp GetCommandHelp(CommandInputModel command, IConsoleCommand consoleCommand, bool showSyntax = false, bool showLearn = false)
        {
            var cacheKey = (string.Join("_", command.Args) + "_" + PortalController.Instance.GetCurrentPortalSettings()?.DefaultLanguage).Replace("-", "_");

            cacheKey = $"{cacheKey}_{(showSyntax ? "1" : "0")}_{(showLearn ? "1" : "0")}}}";
            return(DataCache.GetCachedData <CommandHelp>(new CacheItemArgs(cacheKey, CacheItemPriority.Low),
                                                         c => this.GetCommandHelpInternal(consoleCommand, showSyntax, showLearn)));
        }
Example #22
0
        private void SetupCommand()
        {
            this._restorePage = new RestorePage(this._tabControllerMock.Object, this._recyclebinControllerMock.Object, this._contentVerifierMock.Object);

            var args = new[] { "restore-page", this._tabId.ToString() };

            this._restorePage.Initialize(args, this._portalSettings, null, 0);
        }
Example #23
0
        private void SetupCommand()
        {
            this._getCommand = new GetPage(this._tabControllerMock.Object, this._securityServiceMock.Object, this._contentVerifierMock.Object);

            var args = new[] { "get-page", this._tabId.ToString() };

            this._getCommand.Initialize(args, this._portalSettings, null, this._tabId);
        }
Example #24
0
 public Authentication GetAuthentication(IConsoleCommand command)
 {
     if (this.commission != null)
     {
         throw new Exception("임시 인증이 발급되어 있습니다.");
     }
     this.commission = this.authentication.BeginCommission();
     return(this.commission);
 }
        private void SetupCommand(string[] argParams)
        {
            _getUserCommand = new GetUser(_userValidatorMock.Object, _userControllerWrapperMock.Object);

            var args = argParams.ToList();

            args.Insert(0, "get-user");
            _getUserCommand.Initialize(args.ToArray(), _portalSettings, null, _userId.Value);
        }
Example #26
0
        private void ExecuteCommand(IConsoleCommand command, string options)
        {
            var message = command.Execute(options);

            if (message.Length > 0)
            {
                View.Success(message);
            }
        }
        public static void MapCommand(string cmdLabel, IConsoleCommand command)
        {
            if (commandMap.ContainsKey(cmdLabel))
            {
                throw new Exception(String.Format("Command:'{0}' is already mapped!", cmdLabel));
            }

            commandMap.Add(cmdLabel, command);
        }
        /// <summary>
        /// The method register a given command within the controller
        /// </summary>
        /// <param name="command">An implementation of IConsoleCommand</param>

        public void RegisterCommand(IConsoleCommand command)
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }

            mCommandsTable.Add(command.Name, command);
        }
Example #29
0
 /// <summary>
 /// Register command to execute with the given key
 /// </summary>
 public void RegisterCommand(string commandName, IConsoleCommand command)
 {
     if (Commands.ContainsKey(commandName))
     {
         throw new InvalidOperationException(string.Format(
                                                 "A command with name '{0}' is already registered", commandName));
     }
     Commands[commandName] = command;
 }
Example #30
0
        private string ShowHelp(IConsoleCommand command)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append(Environment.NewLine);
            sb.Append(command.Key);
            sb.Append(Environment.NewLine);
            sb.Append($"- {command.Description}");
            return(sb.ToString());
        }
Example #31
0
        private static IConsoleCommand InstantiateCommandType(Type _type, String _parameterStr)
        {
            ConstructorInfo constructorInfo = _type.GetConstructor(new Type[0] {
            });
            IConsoleCommand consoleCommand  = constructorInfo.Invoke(new Object[0] {
            })
                                              as IConsoleCommand;

            consoleCommand.ParseStringParameter(_parameterStr);
            return(consoleCommand);
        }
Example #32
0
 private void TryInitializeTypeNameGenerators(IConsoleCommand codeGenerator)
 {
     if (codeGenerator is SwaggerToCSharpControllerCommand controllerCommand)
     {
         controllerCommand?.InitializeCustomTypes(new AssemblyLoader());
     }
     if (codeGenerator is SwaggerToCSharpClientCommand clientCommand)
     {
         clientCommand?.InitializeCustomTypes(new AssemblyLoader());
     }
 }
Example #33
0
        public void WriteHelp(IConsoleCommand comm)
        {
            Console.WriteLine($"Help for command: '{comm.Keyword?.ToUpper() ?? "Unknown"}'");
            var to = new TabularOutput(77);
            foreach (var sig in comm.Signatures)
            {
                to.AddRow(comm.Keyword, sig.GetHelp(), ":", sig.Description);
            }

            WriteTable(to);
        }
Example #34
0
 public static bool DoesArgMatchCommand(string argument, IConsoleCommand command)
 {
     if (argument == null || command == null)
     {
         return false;
     }
     return
         command.Command.ToLower()
             .Split(new[] {'|'}, StringSplitOptions.RemoveEmptyEntries).Select(it => it.Trim()).ToArray()
             .Contains(argument.ToLower());
 }
        void UpdateStringPrefixExternally(string newValue) => prefix = newValue; //The stored prefix in the developerConsole instance was altered somewhere different than this class, so update the stored value here to the new one

        void UpdateCommandListExternally(IConsoleCommand newCommand)
        {
            if (commands.ContainsKey(newCommand.InvocationKeyword))
            {
                return;
            }
            else
            {
                commands[newCommand.InvocationKeyword] = newCommand;
            }
        } //The stored commands in the developerConsole instance were altered somewhere different than this class, so update the stored value here to the new one
Example #36
0
        /// <summary>Gets the argument value.</summary>
        /// <param name="consoleHost">The command line host.</param>
        /// <param name="args">The arguments.</param>
        /// <param name="property">The property.</param>
        /// <param name="command">The command.</param>
        /// <param name="input">The output from the previous command in the chain.</param>
        /// <returns>The value.</returns>
        public override object GetValue(IConsoleHost consoleHost, string[] args, PropertyInfo property, IConsoleCommand command, object input)
        {
            foreach (var argument in args)
            {
                if (argument == "-" + ShortName)
                    return true;

                if (argument == "--" + LongName)
                    return true;
            }

            return false;
        }
        public GameConsoleComponent(GameConsole console, Game game, SpriteBatch spriteBatch)
            : base(game)
        {
            this.console = console;
            EventInput.Initialize(game.Window);
            this.spriteBatch = spriteBatch;
            AddPresetCommands();
            inputProcesser = new InputProcessor(new CommandProcesser());
            inputProcesser.Open += (s, e) => renderer.Open();
            inputProcesser.Close += (s, e) => renderer.Close();

            renderer = new Renderer(game, spriteBatch, inputProcesser);
            var inbuiltCommands = new IConsoleCommand[] {new ClearScreenCommand(inputProcesser),new ExitCommand(game),new HelpCommand()};
            GameConsoleOptions.Commands.AddRange(inbuiltCommands);
        }
        public override void Specify()
        {
            given("we have some commands", delegate
            {
                var firstcommand = new TestCommand().IsCommand("command-a", "oneline description a");
                var secondCommand = new TestCommand().IsCommand("command-b", "oneline description b");

                var commands = new IConsoleCommand[]
                {
                    firstcommand,
                    secondCommand
                }.ToList();

                var writer = new StringWriter();

                WhenTheUserDoesNotSpecifyACommandThenShowAvailableCommands(commands, writer, firstcommand, secondCommand, new string[0]);
                WhenTheUserDoesNotSpecifyACommandThenShowAvailableCommands(commands, writer, firstcommand, secondCommand, new [] { "help"});

                ShouldShowHelpWhenRequested(commands, new string[] { "command-c", "/?" });
                ShouldShowHelpWhenRequested(commands, new string[] { "help", "command-c" });
            });
        }
Example #39
0
 public bool TryDeregisterCommand(IConsoleCommand command)
 {
     return TryDeregisterCommand(command.Name);
 }
Example #40
0
        public void AddHelpForConsoleCommand(IConsoleCommand command)
        {
            Trace.Assert(command != null);

              AddHelpImpl(specialCommandHelps, command);
        }
Example #41
0
        public bool TryRegisterCommand(IConsoleCommand command)
        {
            if (IsRegistered(command.Name))
            {
                return false;
            }

            registeredCommands.Add(command);
            return true;
        }
Example #42
0
 private bool TryGet(string commandName, out IConsoleCommand command)
 {
     command = Get(commandName);
     return command != null;
 }
Example #43
0
 static void Register(IConsoleCommand cmd)
 {
     Actions.Add(cmd.Usage.Split(new[] { ' ' }, 2).First(), cmd);
 }
Example #44
0
 public void DeregisterCommand(IConsoleCommand command)
 {
     DeregisterCommand(command.Name);
 }
 public ConsoleCommandInstance(IConsole console, IConsoleCommand command, string[] arguments)
 {
     Console = console;
     Command = command;
     Arguments = arguments;
 }
Example #46
0
 public void AddCommand(IConsoleCommand command)
 {
     _commands.Add(GetNextCommandShortcut(), command);
 }
 private void AddCommand(string commandKey,  IConsoleCommand command)
 {
     _commandDictionary.Add(
         commandKey,
         command);
 }
Example #48
0
 public bool IsRegistered(IConsoleCommand command)
 {
     return IsRegistered(command.Name);
 }
 private static void ValidateConsoleCommand(IConsoleCommand command)
 {
     if (string.IsNullOrEmpty(command.Command))
     {
         throw new InvalidOperationException(string.Format(
             "Command {0} did not call IsCommand in its constructor to indicate its name and description.",
             command.GetType().Name));
     }
 }
        private static int DealWithException(Exception e, TextWriter console, bool skipExeInExpectedUsage,
            IConsoleCommand selectedCommand, IEnumerable<IConsoleCommand> commands)
        {
            if (selectedCommand != null && !selectedCommand.IsHidden)
                // dont show help for hidden command even after exception
            {
                console.WriteLine();
                console.WriteLine(e.Message);
                ConsoleHelp.ShowCommandHelp(selectedCommand, console, skipExeInExpectedUsage);
            }
            else
            {
                ConsoleHelp.ShowSummaryOfCommands(commands, console);
            }

            return -1;
        }
 public static int DispatchCommand(IConsoleCommand command, string[] arguments, TextWriter consoleOut)
 {
     return DispatchCommand(new[] {command}, arguments, consoleOut);
 }
Example #52
0
        public void RegisterCommand(IConsoleCommand command)
        {
            if (IsRegistered(command.Name))
            {
                throw new ConsoleCommandAlreadyRegistered(command.Name);
            }

            registeredCommands.Add(command);
        }
Example #53
0
        private void ResetConsoleCommands()
        {
            IConsoleCommand[] commands = new IConsoleCommand[]
            {
                new Utils.ConsoleCommands.RandomizeField(playField),
                new Utils.ConsoleCommands.ChangeCellType(playField),
                new Utils.ConsoleCommands.ResetCell(playField),
                new Utils.ConsoleCommands.Reset(this),
                new Utils.ConsoleCommands.SetHP(PlayerData),
                new Utils.ConsoleCommands.ToggleFrameCounter(this),
                new Utils.ConsoleCommands.AddTime(Timer)
                //new Utils.ConsoleCommands.GetLastMessage(EV3Connection)
            };

            if (console.Commands.Count > 3)
            {
                console.Commands.RemoveRange(3, commands.Length);
            }

            console.AddCommand(commands);
        }
Example #54
0
        public static void ShowParsedCommand(IConsoleCommand consoleCommand, TextWriter consoleOut)
        {

            if (!consoleCommand.TraceCommandAfterParse || consoleCommand.IsHidden)
            {
                return;
            }

            string[] skippedProperties = {
                "IsHidden",
                "Command",
                "OneLineDescription",
                "LongDescription",
                "Options",
                "Console",
                "TraceCommandAfterParse",
                "RemainingArgumentsCount",
                "RemainingArgumentsHelpText",
                "ShowHelpWithoutFurtherArgs",
                "RequiredOptions"
            };

            var properties = consoleCommand.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)
                .Where(p => !skippedProperties.Contains(p.Name));

            var fields = consoleCommand.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance)
                .Where(p => !skippedProperties.Contains(p.Name));

            Dictionary<string,string> allValuesToTrace = new Dictionary<string, string>();

            foreach (var property in properties)
            {
                object value = property.GetValue(consoleCommand, new object[0]);
                allValuesToTrace[property.Name] = value != null ? value.ToString() : "null";
            }

            foreach (var field in fields)
            {
                allValuesToTrace[field.Name] = MakeObjectReadable(field.GetValue(consoleCommand));
            }

            consoleOut.WriteLine();

            string introLine = String.Format("Executing {0}", ConsoleUtil.FormatCommandName(consoleCommand.Command));

            if (string.IsNullOrEmpty(consoleCommand.OneLineDescription))
            {
                introLine = introLine + ":";
                Console.WriteLine(introLine);
            }
            else
            {
                var description =  consoleCommand.OneLineDescription;
                PrintCommandConsoleFriendly(consoleOut, introLine, description, introLine.Length, offset => "{0} ({1}):");
            }

            foreach(var value in allValuesToTrace.OrderBy(k => k.Key))
                consoleOut.WriteLine("    " + value.Key + " : " + value.Value);

            consoleOut.WriteLine();
        }
 public ConsoleCommandInstance(IConsole console, IConsoleCommand command)
     : this(console, command, new string[0])
 {
 }
 public ConsoleExecutingAssembly(string nameSpace, IConsoleCommand instance)
 {
     Namespace = nameSpace;
     Instance = instance;
 }
 /// <summary>Gets the argument value.</summary>
 /// <param name="consoleHost">The command line host.</param>
 /// <param name="args">The arguments.</param>
 /// <param name="property">The property.</param>
 /// <param name="command"></param>
 /// <param name="input">The output from the previous command in the chain.</param>
 /// <returns>The value.</returns>
 public abstract object GetValue(IConsoleHost consoleHost, string[] args, PropertyInfo property, IConsoleCommand command, object input);