public async Task ShowErrorIfHelpForUnknownCommandIsRequested()
        {
            string expectedOutput = "\"foo\" is an unknown command. Type !help to list all available commands!";

            ICommandContainer container = new CommandContainer();

            container.AddCommandHandler <PingCommand>();

            string respone = null;

            //TODO Write a helper method to create this mock, because we use the same code in a lot of tests to create this basic mock
            Mock <IMessage>        socketMessageMock  = new Mock <IMessage>();
            Mock <IMessageChannel> messageChannelMock = new Mock <IMessageChannel>();

            messageChannelMock
            .Setup(c => c.SendMessageAsync(It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <Embed>(), It.IsAny <RequestOptions>()))
            .Callback <string, bool, Embed, RequestOptions>((msg, tts, embed, reqOptions) => respone = msg)
            .Returns(() => Task.FromResult <IUserMessage>(default(SocketUserMessage)));
            socketMessageMock
            .Setup(x => x.Channel)
            .Returns(messageChannelMock.Object);

            HelpCommand helpCommand = new HelpCommand(container);

            helpCommand.Command = "foo";

            //Act
            await helpCommand.Execute(socketMessageMock.Object);

            //Assert
            messageChannelMock.Verify(c => c.SendMessageAsync(It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <Embed>(), It.IsAny <RequestOptions>()), Times.Once());
            Assert.Equal(expectedOutput, respone);
        }
        public async Task RendersHelpForAllCommandInCommandContainerTest()
        {
            string expectedOutput = @":information_source: __**Here are all supported commands:**__ :information_source:

**!help**   - Prints usage for a command
**!ping**   - Execute this to get a super special response
";

            ICommandContainer container = new CommandContainer();

            container.AddCommandHandler <PingCommand>();
            container.AddCommandHandler <HelpCommand>();

            string respone = null;

            Mock <IMessage>        socketMessageMock  = new Mock <IMessage>();
            Mock <IMessageChannel> messageChannelMock = new Mock <IMessageChannel>();

            messageChannelMock
            .Setup(c => c.SendMessageAsync(It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <Embed>(), It.IsAny <RequestOptions>()))
            .Callback <string, bool, Embed, RequestOptions>((msg, tts, embed, reqOptions) => respone = msg)
            .Returns(() => Task.FromResult <IUserMessage>(default(SocketUserMessage)));
            socketMessageMock
            .Setup(x => x.Channel)
            .Returns(messageChannelMock.Object);

            HelpCommand helpCommand = new HelpCommand(container);

            //Act
            await helpCommand.Execute(socketMessageMock.Object);

            //Assert
            messageChannelMock.Verify(c => c.SendMessageAsync(It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <Embed>(), It.IsAny <RequestOptions>()), Times.Once());
            Assert.Equal(expectedOutput, respone);
        }
Example #3
0
    /// <summary>
    /// Spawn a new game object from the given name and primitve type in front of the main camera. See PrimitiveType.
    /// </summary>
    private static ConsoleCommandResult Spawn(params string[] args)
    {
        if (args.Length < 2)
        {
            return(HelpCommand.Execute("SPAWN"));
        }
        else
        {
            PrimitiveType primitiveType;
            try
            {
                primitiveType = (PrimitiveType)Enum.Parse(typeof(PrimitiveType), args[1], true);
            }
            catch
            {
                return(ConsoleCommandResult.Failed("Invalid primitive type specified: " + args[1]));
            }

            var name    = args[0];
            var spawned = GameObject.CreatePrimitive(primitiveType);
            spawned.name = name;
            spawned.transform.position = Camera.main.transform.position + Camera.main.transform.forward * 5;
            return(ConsoleCommandResult.Succeeded("Spawned a new " + primitiveType + " named " + name + "."));
        }
    }
        /// <summary>
        /// Spawn a new game object from the given name and primitve type in front of the main camera. See PrimitiveType.
        /// </summary>
        private static string Spawn(params string[] args)
        {
            string        name;
            PrimitiveType primitiveType;
            GameObject    spawned;

            if (args.Length < 2)
            {
                return(HelpCommand.Execute("SPAWN"));
            }
            else
            {
                name = args[0];
                try
                {
                    primitiveType = (PrimitiveType)Enum.Parse(typeof(PrimitiveType), args[1], true);
                }
                catch
                {
                    return("Invalid primitive type specified: " + args[1]);
                }

                spawned      = GameObject.CreatePrimitive(primitiveType);
                spawned.name = name;
                spawned.transform.position = Camera.main.transform.position + Camera.main.transform.forward * 5;
                return("Spawned a new " + primitiveType + " named " + name + ".");
            }
        }
Example #5
0
        public void Start()
        {
            var initialCommand = new HelpCommand();
            var helpMessage    = initialCommand.Execute();

            _printer.Print(helpMessage.CommandOutput);

            do
            {
                var userInput      = _inputParser.Parse();
                var currentCommand = _commandParser.ParseCommand(userInput);
                currentCommand.CancellationRequested += CancellationRequested;

                if (CanScheduleTask)
                {
                    currentCommand.SortFinished += SortFinished;
                }

                var commandData = currentCommand.Execute(CanScheduleTask);

                _printer.Print(commandData.CommandOutput);
                _isRunning = commandData.ContinueExecution;

                if (commandData.Token.HasValue)
                {
                    _cancellationToken = commandData.Token;
                }
            } while (_isRunning);
        }
Example #6
0
            public static string Execute(params string[] args)
            {
                int         speed;
                PlayerMotor playerMotor = GameManager.Instance.PlayerMotor;//GameObject.FindObjectOfType<PlayerMotor>();

                if (playerMotor == null)
                {
                    return(error);
                }
                if (args == null || args.Length < 1)
                {
                    try
                    {
                        Console.Log(string.Format("Current Jump Speed: {0}", playerMotor.jumpSpeed));
                        return(HelpCommand.Execute(SetJumpSpeed.name));
                    }
                    catch
                    {
                        return(HelpCommand.Execute(SetJumpSpeed.name));
                    }
                }
                else if (!int.TryParse(args[0], out speed))
                {
                    return(error);
                }
                else
                {
                    playerMotor.jumpSpeed = speed;
                    return(string.Format("Jump speed set to: {0}", playerMotor.jumpSpeed));
                }
            }
        public void ShouldPrintListOfCommandsAndDescriptions()
        {
            // Arrange
            var command        = new HelpCommand();
            var createCommand  = new Mock <IConsoleCommand>();
            var versionCommand = new Mock <IConsoleCommand>();
            var helpCommand    = new Mock <IConsoleCommand>();
            var messageService = new MessageServiceMock();

            createCommand.Setup(c => c.Name).Returns("create");
            createCommand.Setup(c => c.Description).Returns("Creates or upgrades a database.");

            versionCommand.Setup(c => c.Name).Returns("version");
            versionCommand.Setup(c => c.Description).Returns("Displays the application version.");

            helpCommand.Setup(c => c.Name).Returns("help");
            helpCommand.Setup(c => c.Description).Returns("Provides help on using the application.");

            command.Commands       = new[] { createCommand.Object, versionCommand.Object, helpCommand.Object };
            command.MessageService = messageService;

            // Act
            command.Execute(new[] { "help" });

            // Assert
            string expected =
                "  create   Creates or upgrades a database." + Environment.NewLine +
                "  help     Provides help on using the application." + Environment.NewLine +
                "  version  Displays the application version." + Environment.NewLine + Environment.NewLine +
                "  Use dbversion help [command] for more help on a command." + Environment.NewLine;

            Assert.Equal(expected, messageService.Contents);
        }
Example #8
0
 public void ExecuteShouldShowHelpView()
 {
     var viewMock = new Mock<IHelpView>();
     ICommand target = new HelpCommand(viewMock.Object);
     target.Execute();
     viewMock.Verify(v => v.Show());
 }
Example #9
0
        public void Execute_CommandFound_WritesCommandHelp()
        {
            var helpCommand = new HelpCommand(
                this.commandLoop,
                this.commandGroupMetadataFactoryMock.Object);

            typeof(HelpCommand)
            .GetProperty(nameof(HelpCommand.CommandName))
            .SetValue(helpCommand, "Command0");
            string outputString;

            using (var newOut = new StringWriter(CultureInfo.InvariantCulture))
            {
                var previousOut = Console.Out;
                Console.SetOut(newOut);

                helpCommand.Execute(CancellationToken.None);

                Console.SetOut(previousOut);
                outputString = newOut.ToString();
            }

            Assert.That(outputString, Does.Contain("Command0"));
            Assert.That(outputString, Does.Not.Contain("Command1"));
            Assert.That(outputString, Does.Contain("This is some help text."));
            Assert.That(outputString, Does.Not.Contain("This is some more help text."));
            Assert.That(outputString, Does.Contain("Arg0"));
            Assert.That(outputString, Does.Contain("This is some parameter help text."));
        }
        public void ShouldNotPrintShortOptionIfItIsNullOrEmpty()
        {
            // Arrange
            var command        = new HelpCommand();
            var createCommand  = new Mock <IConsoleCommand>();
            var messageService = new MessageServiceMock();

            createCommand.Setup(c => c.Name).Returns("create");
            createCommand.Setup(c => c.Description).Returns("Creates or upgrades a database");
            createCommand.Setup(c => c.Usage).Returns("dbversion create [options]");
            createCommand.Setup(c => c.Parameters).Returns(
                new[]
            {
                new CommandParameter(null, "--archive", "Specifies the path to the archive."),
                new CommandParameter(string.Empty, "--connectionString", "Specifies the database connection string."),
                new CommandParameter("-s", "--saved-connection", "Specifies the saved connection to use.")
            });

            command.Commands       = new[] { createCommand.Object };
            command.MessageService = messageService;

            // Act
            command.Execute(new[] { "help", "create" });

            // Assert
            string expected =
                "Usage: dbversion create [options]" + Environment.NewLine + Environment.NewLine +
                "Options:" + Environment.NewLine +
                "  --archive               Specifies the path to the archive." + Environment.NewLine +
                "  --connectionString      Specifies the database connection string." + Environment.NewLine +
                "  -s, --saved-connection  Specifies the saved connection to use." + Environment.NewLine;

            Assert.Equal(expected, messageService.Contents);
        }
Example #11
0
            public void PrintsCommandsToConsole()
            {
                // arrange
                var console      = new Mock <IConsole>();
                var repl         = new Mock <IRepl>();
                var clearCommand = new ClearCommand(console.Object);
                var exitCommand  = new ExitCommand(console.Object);

                var commands = new Dictionary <string, IReplCommand>
                {
                    { clearCommand.CommandName, clearCommand },
                    { exitCommand.CommandName, exitCommand },
                };

                repl.Setup(x => x.Commands).Returns(commands);

                var cmd = new HelpCommand(console.Object);

                // act
                cmd.Execute(repl.Object, null);

                // assert
                console.Verify(x => x.WriteLine(It.IsAny <string>()), Times.Exactly(3));
                console.Verify(x => x.WriteLine(It.Is <string>(f => f.StartsWith(":" + clearCommand.CommandName) && f.Contains(clearCommand.Description))), Times.Once);
                console.Verify(x => x.WriteLine(It.Is <string>(f => f.StartsWith(":" + exitCommand.CommandName) && f.Contains(exitCommand.Description))), Times.Once);
            }
Example #12
0
        public void Execute_CommandNotFound_WritesNotFound()
        {
            var helpCommand = new HelpCommand(
                this.commandLoop,
                this.commandGroupMetadataFactoryMock.Object);

            typeof(HelpCommand)
            .GetProperty(nameof(HelpCommand.CommandName))
            .SetValue(helpCommand, "NotFound");

            string outputString;

            using (var newOut = new StringWriter(CultureInfo.InvariantCulture))
            {
                var previousOut = Console.Out;
                Console.SetOut(newOut);

                helpCommand.Execute(CancellationToken.None);

                Console.SetOut(previousOut);
                outputString = newOut.ToString();
            }

            Assert.That(
                outputString,
                Is.EqualTo(
                    "Invalid command 'NotFound'." +
                    Environment.NewLine +
                    Environment.NewLine));
        }
Example #13
0
            public static string Execute(params string[] args)
            {
                PlayerEnterExit playerEnterExit = GameManager.Instance.PlayerEnterExit;//GameObject.FindObjectOfType<PlayerEnterExit>();

                if (playerEnterExit == null || !playerEnterExit.IsPlayerInside)
                {
                    Console.Log(HelpCommand.Execute(TransitionToExterior.name));
                    return(error);
                }
                else
                {
                    try
                    {
                        if (playerEnterExit.IsPlayerInsideDungeon)
                        {
                            playerEnterExit.TransitionDungeonExterior();
                        }
                        else
                        {
                            playerEnterExit.TransitionExterior();
                        }

                        return("Transitioning to exterior");
                    }
                    catch
                    {
                        return("Error on transitioning");
                    }
                }
            }
Example #14
0
            public void CorrectlyPrintsCommandsToConsoleAfterAlias()
            {
                // arrange
                var console      = new Mock <IConsole>();
                var repl         = new Mock <IRepl>();
                var clearCommand = new ClearCommand(console.Object);
                var aliasCommand = new AliasCommand(console.Object);

                var commands = new Dictionary <string, IReplCommand>
                {
                    { clearCommand.CommandName, clearCommand },
                    { aliasCommand.CommandName, aliasCommand },
                };

                repl.Setup(x => x.Commands).Returns(commands);
                var cmd = new HelpCommand(console.Object);

                aliasCommand.Execute(repl.Object, new[] { "clear", "clr" });

                // act
                cmd.Execute(repl.Object, null);

                // assert
                console.Verify(x => x.WriteLine(It.Is <string>(f => f.StartsWith(":" + clearCommand.CommandName) && f.Contains(clearCommand.Description))), Times.Once);
                console.Verify(x => x.WriteLine(It.Is <string>(f => f.StartsWith(":" + aliasCommand.CommandName) && f.Contains(aliasCommand.Description))), Times.Once);
                console.Verify(x => x.WriteLine(It.Is <string>(f => f.StartsWith(":clr") && f.Contains(clearCommand.Description))), Times.Once);
            }
Example #15
0
            public void CorrectlyPrintsCommandsToConsoleAfterAlias()
            {
                // arrange
                var console = new Mock <IConsole>();

                console.Setup(c => c.Width).Returns(80);

                var repl         = new Mock <IRepl>();
                var clearCommand = new ClearCommand(console.Object);
                var aliasCommand = new AliasCommand(console.Object);

                var commands = new Dictionary <string, IReplCommand>
                {
                    { clearCommand.CommandName, clearCommand },
                    { aliasCommand.CommandName, aliasCommand },
                };

                repl.Setup(x => x.Commands).Returns(commands);
                var cmd = new HelpCommand(console.Object);

                aliasCommand.Execute(repl.Object, new[] { "clear", "clr" });

                // act
                cmd.Execute(repl.Object, null);

                // assert
                // because we now have formatted wrapping with the description, we have to remove
                // all the extra spaces before verifying
                console.Verify(x => x.WriteLine(It.Is <string>(f => f.StartsWith(" :" + clearCommand.CommandName) && f.Replace("  ", " ").Contains(clearCommand.Description))), Times.Once);
                console.Verify(x => x.WriteLine(It.Is <string>(f => f.StartsWith(" :" + aliasCommand.CommandName) && f.Replace("  ", " ").Contains(aliasCommand.Description))), Times.Once);
                console.Verify(x => x.WriteLine(It.Is <string>(f => f.StartsWith(" :clr") && f.Replace("  ", " ").Contains(clearCommand.Description))), Times.Once);
            }
Example #16
0
        public static string Parse(List <string> args)
        {
            try
            {
                string result;

                var command = args.First();

                if (command == Statics.Commands.Help)
                {
                    var helpCommand  = new HelpCommand();
                    var numberOfArgs = helpCommand.GetNumberOfArgs();
                    if (numberOfArgs == args.Count - 1)
                    {
                        result = helpCommand.Execute(new List <string>());
                    }
                    else
                    {
                        throw new Exception("Command not recognized. Please use 'WixXmlGenerator -help' to see command the usages.");
                    }
                }
                else if (command == Statics.Commands.Version)
                {
                    var versionCommand = new VersionCommand();
                    var numberOfArgs   = versionCommand.GetNumberOfArgs();
                    if (numberOfArgs == args.Count - 1)
                    {
                        result = versionCommand.Execute(new List <string>());
                    }
                    else
                    {
                        throw new Exception("Command not recognized. Please use 'WixXmlGenerator -help' to see command the usages.");
                    }
                }
                else if (command == Statics.Commands.Generate)
                {
                    var generateCommand = new GenerateCommand();
                    var numberOfArgs    = generateCommand.GetNumberOfArgs();
                    if (numberOfArgs == args.Count - 1)
                    {
                        result = generateCommand.Execute(args);
                    }
                    else
                    {
                        throw new Exception("Command not recognized. Please use 'WixXmlGenerator -help' to see command the usages.");
                    }
                }
                else
                {
                    throw new Exception("Command not recognized. Please use 'WixXmlGenerator -help' to see command the usages.");
                }

                return(result);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Example #17
0
 private void ExecuteRequestHelp()
 {
     RaiseRoutedEvent(Wizard.HelpEvent);
     if (HelpCommand?.CanExecute(CanHelp) == true)
     {
         HelpCommand?.Execute(CanHelp);
     }
 }
Example #18
0
        public void ExpectedBehavior()
        {
            var command = new HelpCommand();
            var args    = new HelpArgs();
            var execute = command.Execute(args);

            StringAssert.Contains("Help", execute);
        }
Example #19
0
        /// <summary>
        /// Defines the entry point of this application.
        /// </summary>
        /// <param name="Arguments">The CLI arguments.</param>
        private static async Task Main(string[] Arguments)
        {
            var EngineConfig = new BekoConfig
            {
                Process         = Process.GetCurrentProcess(),
                MemoryHandler   = new NativeMemoryHandler(),
                RequestsHandler = new NativeRequestsHandler()
            };

            // ..

            try
            {
                Engine = BekoEngine.FromConfiguration(EngineConfig);
            }
            catch (Exception Exception)
            {
                Console.WriteLine("[*] " + Exception.Message.Split('\n')[0]);
            }

            // ..

            if (Engine != null)
            {
                if (Arguments.Length == 0)
                {
                    HelpCommand.Execute(null);
                }

                Console.Write("[*] > ");

                using (Engine)
                {
                    while (true)
                    {
                        var Command = Console.ReadLine();

                        if (!string.IsNullOrEmpty(Command))
                        {
                            if (Command == "dispose" || Command == "exit" || Command == "quit")
                            {
                                break;
                            }

                            CliCommands.TryExecute(Command.Split(' '));
                        }

                        Console.Write("[*] > ");
                    }
                }
            }
            else
            {
                Console.WriteLine("[*] The engine failed to initialize.");
            }

            await Task.Delay(500);
        }
Example #20
0
        public void HelpCommand_CheckLogic()
        {
            var helpCommand = new HelpCommand();
            var context     = new CommandContext(null, null, null);

            var result         = helpCommand.Execute(context);
            var expectedResult = $"**Список команд:**{Environment.NewLine}{Environment.NewLine}Добавление ревьювера в список: **add [user name] [-t team]**{Environment.NewLine}Примеры использования:{Environment.NewLine}1)Добавление пользователя с именем Ivan Ivanov{Environment.NewLine}*add Ivan Ivanov*{Environment.NewLine}2)Добавление пользователя с именем Ivan Ivanov из команды Team1{Environment.NewLine}*add Ivan Ivanov -t Team1*{Environment.NewLine}3)Добавление отправителя{Environment.NewLine}*add*{Environment.NewLine}4)Добавление отправителя из команды Team1{Environment.NewLine}*add -t Team1*{Environment.NewLine}{Environment.NewLine}Удаление ревьювера из списка: **delete [user name]**{Environment.NewLine}Примеры использования:{Environment.NewLine}1)Удаление пользователя с именем Ivan Ivanov{Environment.NewLine}*delete Ivan Ivanov*{Environment.NewLine}2)Удаление отправителя{Environment.NewLine}*delete*{Environment.NewLine}{Environment.NewLine}Запросить ревьювера: **get [N] [-t team]**{Environment.NewLine}Примеры использования:{Environment.NewLine}1)Получить одного ревьювера{Environment.NewLine}*get*{Environment.NewLine}2)Получить одного ревьювера из команды Team1{Environment.NewLine}*get -t Team1*{Environment.NewLine}3)Получить список из двух ревьюверов{Environment.NewLine}*get 2*{Environment.NewLine}4)Получить список из двух ревьюверов из команды Team1{Environment.NewLine}*get 2 -t Team1*{Environment.NewLine}{Environment.NewLine}Список ревьюверов: **list**{Environment.NewLine}{Environment.NewLine}**Пожелания/замечания/предложения:**{Environment.NewLine}github: https://github.com/KotovAnton/review-bot/";

            Assert.AreEqual(expectedResult, result);
        }
Example #21
0
    public async Task ShouldReturnSuccessfulResult()
    {
        var command = new HelpCommand();
        var message = GenerateMessage(DefaultUser.Id, DefaultUser.Id, command.Aliases[0]);

        var result = await command.Execute(message, DefaultUser);

        result.Should().BeOfType <SuccessfulResult>();
        result.Message.Should().NotBeNullOrEmpty();
    }
Example #22
0
        public void ShouldOutputHelpInformation()
        {
            var types = new List <Type> {
                FooCommandType, BazQuxCommandType, FooBarCommandType
            };
            var writer      = new StringWriter();
            var helpCommand = new HelpCommand(types, writer);

            helpCommand.Execute(new string[0]);
            Assert.Equal("Usage: appharbor COMMAND [command-options]\r\n\r\nAvailable commands:\r\n\r\n  bar foo [bar]               #  Lorem Ipsum m**********r\r\n  foo [bar]                   #  Lorem Ipsum m**********r\r\n  qux baz [quz]               #  Ipsum lol (\"quux\")\r\n\r\nCommon options:\r\n  -h, --help                 Show command help\r\n",
                         writer.ToString());
        }
Example #23
0
        public void ShowHelpMessage_WhenExecuted()
        {
            // Arrange
            var helpCommand = new HelpCommand();

            // Act
            string result = helpCommand.Execute();

            // Assert
            Assert.IsNotNull(result);
            Assert.IsTrue(result.Length > 0);
        }
Example #24
0
        public async Task Execute()
        {
            var output   = A.Fake <Action <string> >();
            var command  = A.Fake <ICommand>();
            var commands = new [] { command };

            var helpCommand = new HelpCommand(output, commands);

            var result = await helpCommand.Execute(new string[0]);

            A.CallTo(output).MustHaveHappenedANumberOfTimesMatching(n => n == 2);
            Assert.Equal(CommandResult.OK, result);
        }
        public void ExecuteWillWriteCorrectOutput(HelpCommand sut)
        {
            // Fixture setup
            var expectedOutput = "Usage: UpdateCurrency <DKK | EUR | USD> <DKK | EUR | USD> <rate>." + Environment.NewLine;

            using (var sw = new StringWriter())
            {
                Console.SetOut(sw);
                // Exercise system
                sut.Execute();
                // Verify outcome
                Assert.Equal(expectedOutput, sw.ToString());
                // Teardown
            }
        }
Example #26
0
        public void ExecuteWillWriteCorrectOutput(HelpCommand sut)
        {
            // Fixture setup
            var expectedOutput = "Usage: UpdateCurrency <DKK | EUR | USD> <DKK | EUR | USD> <rate>." + Environment.NewLine;

            using (var sw = new StringWriter())
            {
                Console.SetOut(sw);
                // Exercise system
                sut.Execute();
                // Verify outcome
                Assert.Equal(expectedOutput, sw.ToString());
                // Teardown
            }
        }
        public string DispatchCommand(string[] commandParameters)
        {
            string commandName = commandParameters[0];

            commandParameters = commandParameters.Skip(1).ToArray();
            string result = string.Empty;

            EventService eventService = new EventService();

            switch (commandName)
            {
            case "CreateEvent":
                CreateEventCommand createEvent = new CreateEventCommand(eventService);
                result = createEvent.Execute(commandParameters);
                break;

            case "DeleteEvent":
                DeleteEventCommand deleteEvent = new DeleteEventCommand(eventService);
                result = deleteEvent.Execute(commandParameters);
                break;

            case "EditEvent":
                EditEventCommand editEvent = new EditEventCommand(eventService);
                result = editEvent.Execute(commandParameters);
                break;

            case "ListEvents":
                ListEventsCommand listEvents = new ListEventsCommand(eventService);
                result = listEvents.Execute(commandParameters);
                break;

            case "Help":
                HelpCommand help = new HelpCommand();
                result = help.Execute(commandParameters);
                break;

            case "Exit":
                ExitCommand exit = new ExitCommand(eventService);
                result = exit.Execute(commandParameters);
                break;

            default:
                result = $@"Command {commandName} does not exist. Type ""Help"" to check the available commands.";
                break;
            }

            return(result);
        }
Example #28
0
        public void Execute_PrintsSomethingToTheLog()
        {
            var        sb           = new StringBuilder();
            TextWriter outputStream = new StringWriter(sb);
            var        log          = new Mock <ILog>();

            log.Setup(x => x.Info(It.IsAny <string>()));
            var config = new ArgumentParser().Parse(new List <string>());
            var cmd    = new HelpCommand(config, log.Object, outputStream);

            cmd.Execute();
            string output = sb.ToString();

            Debug.WriteLine(output);
            Assert.That(output, Is.Not.Empty);
        }
            public static string Execute(params string[] args)
            {
                if (args.Length == 0)
                {
                    return(HelpCommand.Execute(name));
                }
                else
                {
                    GuildManager guildManager = GameManager.Instance.GuildManager;

                    // Is the group a guild group?
                    if (Enum.IsDefined(typeof(FactionFile.GuildGroups), args[0]))
                    {
                        FactionFile.GuildGroups guildGroup = (FactionFile.GuildGroups)Enum.Parse(typeof(FactionFile.GuildGroups), args[0]);

                        if (guildManager.HasJoined(guildGroup))
                        {
                            return("Already a member.");
                        }
                        else if (guildGroup == FactionFile.GuildGroups.HolyOrder || guildGroup == FactionFile.GuildGroups.KnightlyOrder)
                        {
                            if (args.Length > 1)
                            {
                                int    factionId = int.Parse(args[1]);
                                IGuild guild     = guildManager.JoinGuild(guildGroup, factionId);
                                guildManager.AddMembership(guildGroup, guild);
                                return("Guild joined.");
                            }
                            else
                            {
                                return("Need a faction id for temples & knightly orders.");
                            }
                        }
                        else
                        {
                            IGuild guild = guildManager.JoinGuild(guildGroup);
                            guildManager.AddMembership(guildGroup, guild);
                            return("Guild " + guildGroup.ToString() + " joined.");
                        }
                    }
                    else
                    {
                        return("Not a recognised guild group, see FactionFile.GuildGroups enum.");
                    }
                }
            }
            public static string Execute(params string[] args)
            {
                if (args.Length != 2)
                {
                    return(HelpCommand.Execute(name));
                }
                else
                {
                    GuildManager guildManager = GameManager.Instance.GuildManager;
                    PlayerEntity playerEntity = GameManager.Instance.PlayerEntity;

                    // Is the group a guild group?
                    if (Enum.IsDefined(typeof(FactionFile.GuildGroups), args[0]))
                    {
                        FactionFile.GuildGroups guildGroup = (FactionFile.GuildGroups)Enum.Parse(typeof(FactionFile.GuildGroups), args[0]);

                        if (guildManager.HasJoined(guildGroup))
                        {
                            int newRank = int.Parse(args[1]);
                            if (newRank > 0 && newRank < 10)
                            {
                                IGuild guild  = guildManager.GetGuild(guildGroup);
                                int    rep    = guild.GetReputation(playerEntity);
                                int    newRep = Guild.rankReqReputation[newRank];
                                playerEntity.FactionData.ChangeReputation(guild.GetFactionId(), newRep - rep, true);
                                guild.Rank = newRank;
                                return("Rank & reputation updated.");
                            }
                            else
                            {
                                return("Rank must be between 1 and 9.");
                            }
                        }
                        else
                        {
                            return("Not a member of that guild.");
                        }
                    }
                    else
                    {
                        return("Not a recognised guild group, see FactionFile.GuildGroups enum.");
                    }
                }
            }
Example #31
0
            public static string Execute(params string[] args)
            {
                DaggerfallEntityBehaviour playerBehavior = GameManager.Instance.PlayerEntityBehaviour;

                int health = 0;

                if (args == null || args.Length < 1 || !int.TryParse(args[0], out health))
                {
                    return(HelpCommand.Execute(SetHealth.name));
                }
                else if (playerBehavior != null)
                {
                    playerBehavior.Entity.SetHealth(health);
                    return(string.Format("Set health to: {0}", playerBehavior.Entity.CurrentHealth));
                }
                else
                {
                    return(error);
                }
            }
Example #32
0
            public static string Execute(params string[] args)
            {
                int x = 0; int y = 0;

                DaggerfallWorkshop.StreamingWorld streamingWorld = GameManager.Instance.StreamingWorld; //GameObject.FindObjectOfType<DaggerfallWorkshop.StreamingWorld>();
                PlayerEnterExit playerEE = GameManager.Instance.PlayerEnterExit;                        //GameObject.FindObjectOfType<PlayerEnterExit>();

                if (args == null || args.Length < 2)
                {
                    return(HelpCommand.Execute(TeleportToMapPixel.name));
                }

                else if (streamingWorld == null)
                {
                    return("Could not locate Streaming world object");
                }


                else if (playerEE == null || playerEE.IsPlayerInside)
                {
                    return("PlayerEnterExit could not be found or player inside");
                }

                else if (int.TryParse(args[0], out x) && int.TryParse(args[1], out y))
                {
                    if (x <= 0 || y <= 0)
                    {
                        return("Invalid Coordinates");
                    }
                    else if (x >= MapsFile.MaxMapPixelX || y >= MapsFile.MaxMapPixelY)
                    {
                        return("Invalid coordiantes");
                    }
                    else
                    {
                        streamingWorld.TeleportToCoordinates(x, y);
                    }
                    return(string.Format("Teleporting player to: {0} {1}", x, y));
                }
                return("Invalid coordiantes");
            }