Inheritance: ICommand
        public void BufferTest()
        {
            var payload = new byte[] {0x01, 0x02, 0x03, 0x04, 0x05};

            var processor = new AsynchronousCommandProcessor();
            try
            {
                bool eventSuccess = false;
                var resetEvent = new ManualResetEvent(false);

                processor.StartProcessing();
                Assert.IsTrue(processor.IsProcessingMessages);

                processor.EchoEvent += (sender, args) =>
                {
                    eventSuccess = true;
                    resetEvent.Set();
                };

                var command = new EchoCommand {PayLoad = payload};
                EchoResponse response = processor.SendCommandWithResponse(command);
                Assert.IsNotNull(response, "SendCommand did not return a response.");
                Assert.IsInstanceOfType(response, typeof (EchoResponse));
                Assert.IsTrue(BufferCompare(response.Payload, payload), "Response payload did not match the command payload.");

                bool signaled = resetEvent.WaitOne(10000);
                Assert.IsTrue(signaled);
                Assert.IsTrue(eventSuccess);
            }
            finally
            {
                processor.StopProcessing();
                Assert.IsFalse(processor.IsProcessingMessages);
            }
        }
Ejemplo n.º 2
0
        public void EchoTest()
        {
            var expected = "123 abc \n 321321";
            var actual   = new EchoCommand().Execute("123 abc \n 321321");

            Assert.AreEqual(expected, actual);
        }
Ejemplo n.º 3
0
        public void AssignmentTest()
        {
            ICommand command = new EchoCommand();

            Assert.AreEqual("Echo", command.FullName);
            Assert.AreEqual("echo", command.ShortName);
        }
Ejemplo n.º 4
0
        public ConcordionBuilder()
        {
            SpecificationLocator = new ClassNameBasedSpecificationLocator();
            Source               = null;
            Target               = null;
            CommandRegistry      = new CommandRegistry();
            DocumentParser       = new DocumentParser(CommandRegistry);
            EvaluatorFactory     = new SimpleEvaluatorFactory();
            SpecificationCommand = new SpecificationCommand();
            AssertEqualsCommand  = new AssertEqualsCommand();
            AssertTrueCommand    = new AssertTrueCommand();
            AssertFalseCommand   = new AssertFalseCommand();
            ExecuteCommand       = new ExecuteCommand();
            RunCommand           = new RunCommand();
            VerifyRowsCommand    = new VerifyRowsCommand();
            EchoCommand          = new EchoCommand();
            ExceptionRenderer    = new ExceptionRenderer();

            // Set up the commands

            CommandRegistry.Register("", "specification", SpecificationCommand);
            WithApprovedCommand(HtmlFramework.NAMESPACE_CONCORDION_2007, "run", RunCommand);
            WithApprovedCommand(HtmlFramework.NAMESPACE_CONCORDION_2007, "execute", ExecuteCommand);
            WithApprovedCommand(HtmlFramework.NAMESPACE_CONCORDION_2007, "set", new SetCommand());
            WithApprovedCommand(HtmlFramework.NAMESPACE_CONCORDION_2007, "assertEquals", AssertEqualsCommand);
            WithApprovedCommand(HtmlFramework.NAMESPACE_CONCORDION_2007, "assertTrue", AssertTrueCommand);
            WithApprovedCommand(HtmlFramework.NAMESPACE_CONCORDION_2007, "assertFalse", AssertFalseCommand);
            WithApprovedCommand(HtmlFramework.NAMESPACE_CONCORDION_2007, "verifyRows", VerifyRowsCommand);
            WithApprovedCommand(HtmlFramework.NAMESPACE_CONCORDION_2007, "echo", EchoCommand);

            // Wire up the command listeners

            var assertEqualsResultRenderer = new AssertEqualsResultRenderer();

            AssertEqualsCommand.SuccessReported += assertEqualsResultRenderer.SuccessReportedEventHandler;
            AssertEqualsCommand.FailureReported += assertEqualsResultRenderer.FailureReportedEventHandler;
            AssertTrueCommand.SuccessReported   += assertEqualsResultRenderer.SuccessReportedEventHandler;
            AssertTrueCommand.FailureReported   += assertEqualsResultRenderer.FailureReportedEventHandler;
            AssertFalseCommand.SuccessReported  += assertEqualsResultRenderer.SuccessReportedEventHandler;
            AssertFalseCommand.FailureReported  += assertEqualsResultRenderer.FailureReportedEventHandler;

            var verifyRowsCommandRenderer = new VerifyRowResultRenderer();

            VerifyRowsCommand.MissingRowFound += verifyRowsCommandRenderer.MissingRowFoundEventHandler;
            VerifyRowsCommand.SurplusRowFound += verifyRowsCommandRenderer.SurplusRowFoundEventHandler;

            var runResultRenderer = new RunResultRenderer();

            RunCommand.SuccessfulRunReported += runResultRenderer.SuccessfulRunReportedEventHandler;
            RunCommand.FailedRunReported     += runResultRenderer.FailedRunReportedEventHandler;
            RunCommand.IgnoredRunReported    += runResultRenderer.IgnoredRunReportedEventHandler;

            var documentStructureImprovementRenderer = new DocumentStructureImprovementRenderer();

            DocumentParser.DocumentParsing += documentStructureImprovementRenderer.DocumentParsingEventHandler;

            var stylesheetEmbeddingRenderer = new StylesheetEmbeddingRenderer(HtmlFramework.EMBEDDED_STYLESHEET_RESOURCE);

            DocumentParser.DocumentParsing += stylesheetEmbeddingRenderer.DocumentParsingEventHandler;
        }
Ejemplo n.º 5
0
        public void InvalidArgumentsTest()
        {
            ICommand command       = new EchoCommand();
            var      commandResult = command.Execute(null);

            Assert.IsNotNull(commandResult);
            Assert.AreEqual(commandResult.Count(), 1);
            Assert.AreEqual("Invalid arguments", commandResult.First());
        }
Ejemplo n.º 6
0
        public void CanHandle(string commandText, bool expected)
        {
            ArrangeInputs(commandText, out MockedShellState shellState, out HttpState httpState, out ICoreParseResult parseResult);

            EchoCommand echoCommand = new EchoCommand();

            bool?result = echoCommand.CanHandle(shellState, httpState, parseResult);

            Assert.Equal(expected, result);
        }
Ejemplo n.º 7
0
        public void OnEcho(IClientSocket socket, ICommand command)
        {
            EchoCommand reply = (EchoCommand)command;

            Console.Out.WriteLine("< Client received echo-reply on seq: " + reply.Sequence);

            WhatTimeIsItCommand wtit = new WhatTimeIsItCommand();

            client.Send(wtit);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Raised when the echo command is received by a client
        /// </summary>
        /// <param name='client'>
        /// Client.
        /// </param>
        /// <param name='echo'>
        /// Echo.
        /// </param>
        protected void OnEcho(IClientSocket client, ICommand echo)
        {
            EchoCommand request = (EchoCommand)echo;

            Console.Out.WriteLine("> Server received echo request, seq: " + request.Sequence);

            EchoCommand reply = new EchoCommand();

            reply.Reply    = true;
            reply.Sequence = request.Sequence;
            client.Send(reply);
        }
Ejemplo n.º 9
0
        public async Task CanSendInvalid_Test()
        {
            // arrange
            var command = new EchoCommand();

            // act
            var response = await this.mediator.Send(command).AnyContext();

            // assert
            //response.ShouldNotBeNull();
            //response.Result.ShouldNotBeNull();
            //response.Result.Message.ShouldNotBeNullOrEmpty();
        }
Ejemplo n.º 10
0
        protected void OnConnected(IClientSocket client)
        {
            // set it to asynchronous mode
            client.OnReceivedInvokeAsynchronously = true;

            System.Diagnostics.Debug.WriteLine(String.Format(
                                                   "Test Client Connected {0}",
                                                   client
                                                   ));
            EchoCommand echo = new EchoCommand();

            echo.Reply    = false;
            echo.Sequence = ++sequencer;
            client.Send(echo);
        }
Ejemplo n.º 11
0
        public async Task MiscTest()
        {
            // arrange
            var mediator = Substitute.For <IMediator>();
            var request  = new EchoCommand
            {
                Message = "John Doe"
            };

            // act
            var response = await mediator.Send(request).AnyContext();

            // assert
            //result.ShouldNotBeNull();
        }
Ejemplo n.º 12
0
        public void Test_MetadataActions()
        {
            // Arrange
            var echo = new EchoCommand();

            _meta = new CommandMetadata(echo);
            var actionMeta = _meta.ActionsMeta[0];

            // Assert
            Assert.AreEqual(true, actionMeta.Default);
            Assert.AreEqual("Echoed", actionMeta.Name);
            Assert.AreEqual("String", actionMeta.ReturnType);
            Assert.AreEqual(1, actionMeta.ParamsType.Length);
            Assert.AreEqual("String[]", actionMeta.ParamsType[0]);
        }
Ejemplo n.º 13
0
        public void BasicCommandBufferTest()
        {
            var payload = new byte[] {0x01, 0x02, 0x03, 0x04, 0x05};

            var commandStore = new byte[] {(byte) MessageIdentifier.Echo, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05};
            var responseStore = new byte[] {(byte) MessageIdentifier.Echo, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05};

            var command = new EchoCommand {PayLoad = payload};
            byte[] store = command.Store;
            Assert.IsTrue(BufferCompare(store, commandStore), "EchoCommand.Execute() creates invalid store.");

            EchoResponse response = command.CreateResponse(responseStore);
            Assert.IsNotNull(response, "EchoCommand.CreateResponse() did not create a response.");
            Assert.IsInstanceOfType(response, typeof (EchoResponse),
                "EchoCommand.CreateResponse() did not create a response of type EchoResponse.");
            Assert.IsTrue(BufferCompare(response.Payload, payload), "EchoResponse.Payload doesn't match payload.");
        }
        public async Task <IActionResult> GetEcho(
            [FromBody] EchoCommand command,
            [FromHeader(Name = "x-requestid")] string requestId
            )
        {
            if (!Guid.TryParse(requestId, out var guid))
            {
                return(BadRequest());
            }

            var identifiedCommand = new IdentifiedCommand <EchoCommand, string>(
                command,
                guid
                );

            return(Ok(await _mediator.Send(identifiedCommand)));
        }
Ejemplo n.º 15
0
        public void WhenExecuteCommandWithoutText_CommandManager_ShouldThrowException()
        {
            var storedDataService = new StoredDataServiceMock();
            var commandDefinition = new EchoCommand();

            var instance = new CommandManager(_loggerServiceMock, storedDataService, _cryptoServiceMock);

            instance.RegisterCommand(commandDefinition);

            var inputRequest = new InputRequest(
                commandDefinition.GetInvocationCommandName());

            Assert.Throws <InvalidParamsException>(() =>
            {
                instance.ExecuteInputRequest(inputRequest);
            });
        }
Ejemplo n.º 16
0
        public SimpleScript()
        {
            Name = "simple";

            var echo   = new EchoCommand();
            var prompt = new PromptCommand();

            Actions = new[]
            {
                new AndAction(
                    new CommandAction(echo, echo.FindDefaultAction(), new object[] { "Hello World" }),
                    new PipeAction(new[]
                {
                    new CommandAction(prompt, prompt.FindAction("set")),
                    new CommandAction(echo, echo.FindAction("echoed"))
                }, "$")),
            };
        }
Ejemplo n.º 17
0
        private static bool TryDeserialize(
            BridgeMessageDeserializer deserializer,
            out IServiceCommand command,
            out IServiceCommandResponse errorResponse)
        {
            switch (deserializer.CommandName)
            {
            case ServiceCommandName.ShutdownServer:
                command = new ShutdownServerCommand();
                break;

            case ServiceCommandName.Echo:
                command = new EchoCommand(deserializer);
                break;

            case ServiceCommandName.RegistryReadIntValue:
                command = new RegistryReadIntValueCommand(deserializer);
                break;

            case ServiceCommandName.RegistryReadStringValue:
                command = new RegistryReadStringValueCommand(deserializer);
                break;

            case ServiceCommandName.RegistryWriteIntValue:
                command = new RegistryWriteIntValueCommand(deserializer);
                break;

            case ServiceCommandName.RegistryWriteStringValue:
                command = new RegistryWriteStringValueCommand(deserializer);
                break;

            case ServiceCommandName.Unknown:
            default:
                throw new InvalidOperationException(
                          "This should be unreachable because the deserializer should have detected an invalid command name");
            }

            if (deserializer.HadError)
            {
                command = null;
            }
            errorResponse = deserializer.LastError;
            return(!deserializer.HadError);
        }
Ejemplo n.º 18
0
        public void GetArgumentSuggestionsForText(string commandText, params string[] expectedResults)
        {
            ArrangeInputs(commandText, out MockedShellState shellState, out HttpState httpState, out ICoreParseResult parseResult);

            EchoCommand echoCommand = new EchoCommand();

            IEnumerable <string> result = echoCommand.Suggest(shellState, httpState, parseResult);

            Assert.NotNull(result);

            List <string> resultList = result.ToList();

            Assert.Equal(expectedResults.Length, resultList.Count);

            for (int index = 0; index < expectedResults.Length; index++)
            {
                Assert.Contains(expectedResults[index], resultList, StringComparer.OrdinalIgnoreCase);
            }
        }
Ejemplo n.º 19
0
        public void Does_parser_use_correct_command_with_long_name()
        {
            // Arrange
            string          result       = "";
            Action <string> outputAction = (string output) => result = output;

            EchoCommand       testCommand = new EchoCommand();
            TestOutputHandler output      = new TestOutputHandler();

            output.OutputAction = outputAction;

            CommandParser sut = new CommandParser(new [] { testCommand }, output);

            // Act
            sut.Parse(new[] { "echo", "Echoed string" });

            // Assert
            result.Should().Be("Echoed string");
        }
Ejemplo n.º 20
0
        public ConcordionBuilder()
        {
            BuildListeners = new List <IConcordionBuildListener>();
            SpecificationProcessingListeners = new List <ISpecificationProcessingListener>();
            ResourceToCopyMap  = new Dictionary <string, Resource>();
            ExceptionListeners = new List <IExceptionCaughtListener>();

            SpecificationLocator = new ClassNameBasedSpecificationLocator();
            Source               = null;
            Target               = null;
            CommandRegistry      = new CommandRegistry();
            DocumentParser       = new DocumentParser(CommandRegistry);
            EvaluatorFactory     = new SimpleEvaluatorFactory();
            SpecificationCommand = new SpecificationCommand();
            AssertEqualsCommand  = new AssertEqualsCommand();
            AssertTrueCommand    = new AssertTrueCommand();
            AssertFalseCommand   = new AssertFalseCommand();
            ExecuteCommand       = new ExecuteCommand();
            RunCommand           = new RunCommand();
            VerifyRowsCommand    = new VerifyRowsCommand();
            EchoCommand          = new EchoCommand();
            ExceptionRenderer    = new ExceptionRenderer();

            WithExceptionListener(ExceptionRenderer);

            // Set up the commands

            CommandRegistry.Register("", "specification", SpecificationCommand);

            // Wire up the command listeners

            var assertResultRenderer = new AssertResultRenderer();

            WithAssertEqualsListener(assertResultRenderer);
            WithAssertTrueListener(assertResultRenderer);
            WithAssertFalseListener(assertResultRenderer);
            WithVerifyRowsListener(new VerifyRowResultRenderer());
            WithRunListener(new RunResultRenderer());
            WithDocumentParsingListener(new DocumentStructureImprover());
            WithDocumentParsingListener(new MetadataCreator());
            WithEmbeddedCss(HtmlFramework.EMBEDDED_STYLESHEET_RESOURCE);
        }
        public void Execute(EchoCommand command)
        {
            if (Connection == null)
            {
                Console.WriteLine("There is no connection to server!");

                return;
            }

            var request = new TextCommand()
            {
                CommandType = CommandType.EchoRequest,
                Text        = command.Message
            };

            Connection.Send(request);
            var response = Connection.Receive().Deserialize <TextCommand>();

            Console.WriteLine(response.Text);
        }
        public CommandApplier()
        {
            simulator = new BashSimulator();
            commands  = new Dictionary <string, ICommand>();
            CatCommand catCommand = new CatCommand();

            commands[catCommand.Name] = catCommand;
            WcCommand wcCommand = new WcCommand();

            commands[wcCommand.Name] = wcCommand;
            PwdCommand pwdCommand = new PwdCommand();

            commands[pwdCommand.Name] = pwdCommand;
            AnotherCommand anotherCommand = new AnotherCommand();

            commands[anotherCommand.Name] = anotherCommand;
            EchoCommand echoCommand = new EchoCommand();

            commands[echoCommand.Name] = echoCommand;
        }
Ejemplo n.º 23
0
        public void WhenExecuteCommandText_CommandManager_ShouldLogText()
        {
            var cmd = "hellomoto";
            var storedDataService = new StoredDataServiceMock();
            var commandDefinition = new EchoCommand();

            var instance = new CommandManager(_loggerServiceMock, storedDataService, _cryptoServiceMock);

            instance.RegisterCommand(commandDefinition);
            instance.OnLog += Instance_OnLog;
            var inputRequest = new InputRequest(
                commandDefinition.GetInvocationCommandName(),
                commandDefinition.CommandTextParameter.GetInvokeName(),
                cmd);

            instance.ExecuteInputRequest(inputRequest);

            var expected = cmd;
            var actual   = _loggerServiceMock.Logs.First();

            Assert.Equal(expected, actual);
        }
        public void BasicCommandTest()
        {
            var payload = new byte[] {0x01, 0x02, 0x03, 0x04};

            var command = new EchoCommand { Payload = payload};

            var idBytes= BitConverter.GetBytes((ushort) new Identifier(MessageIdentifier.Echo, MessageType.ResponseType));

            var responseStore = new byte[idBytes.Length + payload.Length];
            System.Buffer.BlockCopy(idBytes, 0, responseStore, 0, idBytes.Length);
            System.Buffer.BlockCopy(payload, 0, responseStore, idBytes.Length, payload.Length);

            var response = command.CreateResponse();

            Assert.IsNotNull(response);

            response.SetStore(responseStore);

            Assert.IsTrue(response.Key.IsMatch(responseStore));
            Assert.IsInstanceOfType(response, typeof(EchoResponse));
            Assert.IsTrue(BufferCompare(response.Payload, payload));
        }
Ejemplo n.º 25
0
        public void ExecuteTest()
        {
            ICommand command = new EchoCommand();

            // single argument test
            var arguments = new List <string>()
            {
                "Something"
            };
            var commandResult = command.Execute(arguments);

            Assert.IsNotNull(commandResult);
            Assert.AreEqual(commandResult.Count(), 1);
            Assert.AreEqual("Something", commandResult.First());

            // multi argiment test
            arguments.Add("Something more");
            commandResult = command.Execute(arguments);
            Assert.IsNotNull(commandResult);
            Assert.AreEqual(commandResult.Count(), 2);
            Assert.AreEqual("Something", commandResult.First());
            Assert.AreEqual("Something more", commandResult.Last());
        }
Ejemplo n.º 26
0
 public void Before_Each_Test()
 {
     mock = MockRepository.GenerateMock <IConsoleFacade>();
     cmd  = new EchoCommand(mock);
 }
Ejemplo n.º 27
0
        public override void InitiateClient(DiscordClient _client)
        {
            _client.GetService <CommandService>().CreateGroup("echo", egp => {
                egp.CreateCommand("add")
                .Parameter("challenge")
                .Parameter("response")
                .Do(e => {
                    if (Config.INSTANCE.GetPermissionLevel(e.User, e.Server) > 0)
                    {
                        EchoCommand ec = new EchoCommand {
                            challenge = e.Args[0],
                            response  = e.Args[1],
                            server_id = e.Server.Id
                        };
                        if (Config.INSTANCE.echoCommands.Contains(ec))
                        {
                            e.Channel.SendMessage("Cannot add echo !" + ec.challenge + "... already exists");
                            return;
                        }
                        Config.INSTANCE.echoCommands.Add(ec);
                        Config.INSTANCE.Commit();
                        e.Channel.SendMessage("Added echo !" + ec.challenge + " : " + ec.response);
                    }
                    else
                    {
                        e.Channel.SendMessage("Sorry, you don't have permission to do that.");
                    }
                });
                egp.CreateCommand("remove")
                .Parameter("challenge")
                .Do(e => {
                    if (Config.INSTANCE.GetPermissionLevel(e.User, e.Server) >= 2)
                    {
                        foreach (EchoCommand c in Config.INSTANCE.echoCommands)
                        {
                            if (c.challenge == e.Args[0])
                            {
                                Config.INSTANCE.echoCommands.Remove(c);
                                break;
                            }
                        }
                        e.Channel.SendMessage($"The echo {e.Args[0]} has been removed.");
                        Config.INSTANCE.Commit();
                    }
                });
                egp.CreateCommand("list-old")
                .Do(async e => {
                    if (Config.INSTANCE.GetPermissionLevel(e.User, e.Server) >= 0)
                    {
                        await e.Channel.SendMessage($"Please wait, compiling echo list. :clock2:");

                        // Compile echolist.html file
                        StreamWriter sw = new StreamWriter("echolist-old.html", false);
                        sw.Write(@"<!DOCTYPE html>
                        <html>
                        <head>
                            <title>Echo List</title>
                            <meta charset='utf-8'>
                            <style>
                            html, body{
                                margin: 0; padding: 0;
                            }

                            body{
                                background-color: #36393E;
                                color: #eee;
                                font-family: Whitney, Helvetica Neue, Helvetica, Arial, sans-serif;
                            }

                            h1{
                                text-align: center;
                            }

                            a{
                                text-decoration: none;
                                color: #46B7E4;
                            }

                            a:hover{
                                text-decoration: underline;
                            }

                            .echos{
                                margin: 40px auto;
                                max-width: 1400px;
                            }

                            .echo{
                                border-top: 1px solid #555;
                                padding-top: 25px;
                                margin-top: 25px;
                            }

                            .title{
                                font-weight: bold;
                                margin-bottom: 5px;
                            }

                            .content{
                                white-space: pre-wrap;
                                color: #aaa;
                            }
                            </style>
                        </head>
                        <body>
                            <h1>Echo List</h1>
                            <div class='echos'>
                        ");
                        foreach (EchoCommand ec in Config.INSTANCE.echoCommands)
                        {
                            if (ec.server_id == e.Server.Id)
                            {
                                if (ec.response.StartsWith("http://") || ec.response.StartsWith("https://"))
                                {
                                    sw.WriteLine($"<div class='echo'><div class='title'>{ec.challenge}</div><div class='content'><a href='{ec.response}' target='_blank'>link</a></div></div>");
                                }
                                else
                                {
                                    sw.WriteLine($"<div class='echo'><div class='title'>{ec.challenge}</div><div class='content'>{ec.response}</div></div>");
                                }
                            }
                        }
                        sw.Write(@"
                            </div>
                            <script>
                            </script>
                        </body>
                        </html>");
                        sw.Close();

                        await e.Channel.SendMessage("List compiled! :robot: :tools:");
                        await e.Channel.SendFile("echolist-old.html");
                    }
                });
                egp.CreateCommand("list")
                .Do(async e => {
                    if (Config.INSTANCE.GetPermissionLevel(e.User, e.Server) >= 0)
                    {
                        await e.Channel.SendMessage($"Please wait, compiling echo list. :clock2:");

                        // Compile echolist.html file
                        StreamWriter sw = new StreamWriter("echolist.html", false);
                        sw.Write(@"<!DOCTYPE html>
                        <html>
                        <head>
                            <title>Echo List</title>
                            <meta charset='utf-8'>
                            <script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js'></script>
                            <style>
                            html, body{
                                margin: 0; padding: 0;
                            }

                            body{
                                background-color: #36393E;
                                color: #eee;
                                font-family: Whitney, Helvetica Neue, Helvetica, Arial, sans-serif;
                            }
                            
                            .clearfix:after {
                                content:' ';
                                display:block;
                                clear:both;
                            }
                            
                            .col-6{
                                float: left;
                                width: 50%;
                                padding: 8px;
                                box-sizing: border-box;
                            }
                            
                            .text-left{ text-align: left; }
                            .text-center{ text-align: center; }
                            .text-right{ text-align: right; }
                            
                            .container{
                                max-width: 1400px;
                                margin-left: auto;
                                margin-right: auto;
                                box-sizing: border-box;
                            }
                            
                            nav{
                                position: fixed;
                                top: 0;
                                width: 100%;
                                height: 50px;
                                background-color: #1E2124;
                            }
                            
                            input[type=text]{
                                background-color: #303338;
                                border: 1px solid #222427;
                                color: #ccc;
                                border-radius: 2px;
                                padding: 6px 12px;
                                
                                transition: all .2s;
                                -webkit-transition: all .2s;
                                -moz-transition: all .2s;
                                -o-transition: all .2s;
                                -ms-transition: all .2s;
                            }
                            
                            input[type=text]:hover, input[type=text]:active, input[type=text]:focus{
                                background-color: #313339;
                                border-color: #040405;
                                box-shadow: none;
                            }
                            
                            input[type=text]:active, input[type=text]:focus{
                                border-color: #7289da;
                            }
                            

                            h1, h2, h3, h4, h5, h6{
                                margin: 0;
                            }

                            a{
                                text-decoration: none;
                                color: #46B7E4;
                            }

                            a:hover{
                                text-decoration: underline;
                            }

                            .echos{
                                margin-top: 15px;
                                padding: 8px;
                            }

                            .echo{
                                border-top: 1px solid #555;
                                padding-top: 25px;
                                margin-top: 25px;
                            }

                            .title{
                                font-weight: bold;
                                margin-bottom: 5px;
                            }

                            .content{
                                color: #aaa;
                            }
                            
                            .content .content_text{
                                white-space: pre-wrap;
                            }
                            
                            .content img{
                                max-width: 350px;
                                max-height: 150px;
                            }
                            </style>
                        </head>
                        <body ng-app='EchoApp' ng-controller='EchoController as self'>
                            <nav>
                                <div class='container clearfix'>
                                    <div class='col-6'>
                                        <h1>Echo List</h1>
                                    </div>
                                    <div class='col-6 text-right'>
                                        <input ng-model='self.search_input' type='text' placeholder='Search...' size='25'>
                                    </div>
                                </div>
                            </nav>
                            <div class='echos container'>
                                <div class='echo' ng-repeat='echo in self.echos | filter:self.search_input'>
                                    <div class='title'>{{echo.title}}</div>
                                    <div class='content'>
                                        <a ng-if='echo.is_link' ng-href='{{echo.content}}' target='_blank'>
                                            <span ng-if='!echo.is_image'>link: {{echo.content}}</span>
                                            <img ng-if='echo.is_image' ng-src='{{echo.content}}'>
                                        </a>
                                        <div ng-if='!echo.is_link' class='content_text'>{{echo.content}}</div>
                                    </div>
                                </div>
                            </div>
                            
                            <script>
                            angular.module('EchoApp', [])
                                   .factory('EchoData', EchoData)
                                   .controller('EchoController', EchoController);
                            
                            function EchoData(){
                                var echos = 
                        ");

                        // write out echo data
                        List <EchoCommand> echos = new List <EchoCommand>();
                        foreach (EchoCommand ec in Config.INSTANCE.echoCommands)
                        {
                            if (ec.server_id == e.Server.Id)
                            {
                                echos.Add(ec);
                            }
                        }

                        String json = JsonConvert.SerializeObject(echos);
                        sw.Write(json + ";\n");

                        sw.Write(@"
                                var image_formats = ['jpg', 'jpeg', 'png', 'gif'];

                                //echos = JSON.parse(echos);

                                // process echo data
                                for (var i = 0; i < echos.length; i++){
                                    e = echos[i];
                                    e.content = e.response;
                                    e.title = e.challenge;
                                    e.tags = [];
                                    
                                    // check if link
                                    var lower = e.content.toLowerCase();
                                    if (lower.startsWith('http://') || lower.startsWith('https://')){
                                        e.is_link = true;
                                        
                                        // check if image link
                                        if (image_formats.indexOf(lower.split('.').pop()) >= 0){
                                            e.is_image = true;
                                            e.tags.push('image');
                                        } else {
                                            e.tags.push('link');
                                        }
                                    }
                                }
                                
                                return echos;
                            }
                            
                            function EchoController($scope, EchoData){
                                var self = this;
                                self.echos = EchoData;
                                self.search_input = '';
                            }
                            </script>
                        </body>
                        </html>
                            ");
                        sw.Close();

                        await e.Channel.SendMessage("List compiled! :robot: :tools:");
                        await e.Channel.SendFile("echolist.html");
                    }
                });
            });
        }
Ejemplo n.º 28
0
 public void Before_Each_Test()
 {
     mock = MockRepository.GenerateMock<IConsoleFacade>();
     cmd = new EchoCommand(mock);
 }