Example #1
0
        public void Run_RestorePage_WithValidCommand_ShouldReturnSuccessResponse()
        {
            // Arrange
            SetupCommand();

            // Act
            var result = _restorePage.Run();

            // Assert
            Assert.IsFalse(result.IsError);
            Assert.AreEqual(1, result.Records);
            Assert.IsFalse(result is ConsoleErrorResultModel);
        }
        public void Run_GetUserByEmailWithValidCommand_ShouldSuccessResponse()
        {
            // Arrange
            var recCount = 0;
            var cmd      = "--email [email protected]";

            _userControllerWrapperMock.Setup(c => c.GetUsersByEmail(_testPortalId, It.IsAny <string>(), It.IsAny <int>(), It.IsAny <int>(), ref recCount, It.IsAny <bool>(), It.IsAny <bool>())).Returns(_userId);

            SetupCommand(cmd.Split(new[] { ' ' }));

            // Act
            var result = _getUserCommand.Run();

            // Assert
            Assert.IsFalse(result.IsError);
        }
        public void Run_GetPageWithValidCommand_ShouldSuccessResponse()
        {
            // Arrange
            _tabControllerMock.Setup(t => t.GetTab(_tabId, _testPortalId)).Returns(_tab);

            SetupCommand();

            // Act
            var result = _getCommand.Run();

            // Assert
            Assert.IsFalse(result.IsError);
            Assert.IsNotNull(result.Data);
            Assert.AreEqual(1, result.Records);
            Assert.IsFalse(result is ConsoleErrorResultModel);
        }
        private void _processNewCommand(string input)
        {
            var result = mArgsParser.Parse(input);

            mView.ClearInput();

            IConsoleCommand command = null;

            try
            {
                command = mCommandsTable[result.Item1];
            }
            catch (KeyNotFoundException)
            {
                mView.Log($"<color=red>Unknown command: </color> {result.Item1}");

                return;
            }

            mView.Log(input);
            mView.Log(command.Run(result.Item2));
        }
        public int DispatchCommand(IReadOnlyCollection <IConsoleCommand> commands, string[] arguments, TextWriter consoleOut, bool skipExeInExpectedUsage = false)
        {
            IConsoleCommand selectedCommand = null;

            var console = consoleOut;

            foreach (var command in commands)
            {
                ValidateConsoleCommand(command);
            }

            try
            {
                List <string> remainingArguments;
                if (commands.Count == 1)
                {
                    selectedCommand = commands.First();

                    if (arguments.Any() && string.Equals(arguments.First(), selectedCommand.Command, StringComparison.OrdinalIgnoreCase))
                    {
                        remainingArguments = selectedCommand.GetActualOptions().Parse(arguments.Skip(1));
                    }
                    else
                    {
                        remainingArguments = selectedCommand.GetActualOptions().Parse(arguments);
                    }
                }
                else
                {
                    if (!arguments.Any())
                    {
                        throw new ConsoleHelpAsException("No arguments specified.");
                    }

                    if (arguments[0].Equals("help", StringComparison.OrdinalIgnoreCase))
                    {
                        selectedCommand = GetMatchingCommand(commands, arguments.Skip(1).FirstOrDefault());

                        if (selectedCommand == null)
                        {
                            ConsoleHelp.ShowSummaryOfCommands(commands, console);
                        }
                        else
                        {
                            ConsoleHelp.ShowCommandHelp(selectedCommand, console, skipExeInExpectedUsage);
                        }

                        return(-1);
                    }

                    selectedCommand = GetMatchingCommand(commands, arguments.First());

                    remainingArguments = selectedCommand?.GetActualOptions().Parse(arguments.Skip(1)) ?? throw new ConsoleHelpAsException("Command name not recognized.");
                }

                selectedCommand.CheckRequiredArguments();

                CheckRemainingArguments(remainingArguments, selectedCommand.RemainingArgumentsCount);

                var preResult = selectedCommand.OverrideAfterHandlingArgumentsBeforeRun(remainingArguments.ToArray());

                if (preResult.HasValue)
                {
                    return(preResult.Value);
                }

                ConsoleHelp.ShowParsedCommand(selectedCommand, console);

                return(selectedCommand.Run(remainingArguments.ToArray()));
            }
            catch (ConsoleHelpAsException e)
            {
                return(DealWithException(e, console, skipExeInExpectedUsage, selectedCommand, commands));
            }
            catch (NDesk.Options.OptionException e)
            {
                return(DealWithException(e, console, skipExeInExpectedUsage, selectedCommand, commands));
            }
        }
Example #6
0
        /// <summary>
        /// Log every command run by a users.
        /// </summary>
        /// <param name="consoleCommand"></param>
        /// <param name="cmdTypeToRun"></param>
        /// <param name="command"></param>
        /// <param name="startTime"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        private HttpResponseMessage AddLogAndReturnResponse(IConsoleCommand consoleCommand, Type cmdTypeToRun, CommandInputModel command,
                                                            DateTime startTime, string error = null)
        {
            HttpResponseMessage message;
            var isValid = consoleCommand?.IsValid() ?? false;
            var logInfo = new LogInfo
            {
                LogTypeKey = "PROMPT_ALERT"
            };

            logInfo.LogProperties.Add(new LogDetailInfo("Command", FilterCommand(command.CmdLine)));
            logInfo.LogProperties.Add(new LogDetailInfo("IsValid", isValid.ToString()));

            try
            {
                if (cmdTypeToRun != null)
                {
                    logInfo.LogProperties.Add(new LogDetailInfo("TypeFullName", cmdTypeToRun.FullName));
                }
                if (isValid)
                {
                    var result = consoleCommand.Run();
                    if (result.PagingInfo != null)
                    {
                        if (result.PagingInfo.PageNo < result.PagingInfo.TotalPages)
                        {
                            result.Output = string.Format(Localization.GetString("Prompt_PagingMessageWithLoad", Constants.LocalResourcesFile),
                                                          result.PagingInfo.PageNo, result.PagingInfo.TotalPages);

                            var args        = command.Args;
                            var indexOfPage = args.Any(x => x.ToLowerInvariant() == "--page")
                                ? args.TakeWhile(arg => arg.ToLowerInvariant() != "--page").Count()
                                : -1;
                            if (indexOfPage > -1)
                            {
                                args[indexOfPage + 1] = (result.PagingInfo.PageNo + 1).ToString();
                            }
                            var nextPageCommand = string.Join(" ", args);
                            if (indexOfPage == -1)
                            {
                                nextPageCommand += " --page " + (result.PagingInfo.PageNo + 1);
                            }
                            result.NextPageCommand = nextPageCommand;
                        }
                        else if (result.Records > 0)
                        {
                            result.Output = string.Format(Localization.GetString("Prompt_PagingMessage", Constants.LocalResourcesFile),
                                                          result.PagingInfo.PageNo, result.PagingInfo.TotalPages);
                        }
                    }
                    message = this.Request.CreateResponse(HttpStatusCode.OK, result);
                    logInfo.LogProperties.Add(new LogDetailInfo("RecordsAffected", result.Records.ToString()));
                    logInfo.LogProperties.Add(new LogDetailInfo("Output", result.Output));
                }
                else
                {
                    logInfo.LogProperties.Add(new LogDetailInfo("Output", consoleCommand?.ValidationMessage ?? error));
                    message = this.BadRequestResponse(consoleCommand?.ValidationMessage ?? error);
                }
            }
            catch (Exception ex)
            {
                logInfo.Exception = new ExceptionInfo(ex);
                message           = this.BadRequestResponse(ex.Message);
            }
            logInfo.LogProperties.Add(new LogDetailInfo("ExecutionTime(hh:mm:ss)", TimeSpan.FromMilliseconds(DateTime.Now.Subtract(startTime).TotalMilliseconds).ToString(@"hh\:mm\:ss\.ffffff")));
            LogController.Instance.AddLog(logInfo);
            return(message);
        }