public string ExecuteCommand(string commandName, string[] commandArguments)
        {
            ICommand command = null;
            if (commandName == "AddPhone" && commandArguments.Length >= 2)
            {
                command = new AddPhoneCommand(this.phonebookRepository, commandArguments);
            }
            else if (commandName == "ChangePhone" && commandArguments.Length == 2)
            {
                command = new ChangePhoneCommand(this.phonebookRepository, commandArguments);
            }
            else if (commandName == "List" && commandArguments.Length == 2)
            {
                command = new ListCommand(this.phonebookRepository, commandArguments);
            }
            else
            {
                return "Invalid command";
            }

            string commandResult;
            try
            {
                commandResult = command.Execute();
            }
            catch (Exception e)
            {
                commandResult = e.Message;

            }

            return commandResult;
        }
Esempio n. 2
0
        public void when_list_command_is_executed_then_all_versions_are_fetched_from_database()
        {
            var listCommand = new ListCommand(MockSecureConsole.Object, _mockConnectionFactory.Object, _mockVersionRepositoryFactory.Object);

            listCommand.Execute(_requiredListCommandArguments);

            _mockVersionRepository.Verify(m => m.GetAllVersions(It.IsAny<string>()), Times.Once);
        }
Esempio n. 3
0
        public void when_list_command_is_executed_then_a_database_connection_is_established()
        {
            var listCommand = new ListCommand(MockSecureConsole.Object, _mockConnectionFactory.Object, _mockVersionRepositoryFactory.Object);

            listCommand.Execute(_requiredListCommandArguments);

            _mockConnectionFactory.Verify(m => m.Create(It.IsAny<DatabaseConnectionInfo>()), Times.Once);
        }
Esempio n. 4
0
        public void Test()
        {
            var input = new ListInput()
                        {
                            PointFlag = @"..\..\..\.."
                        };

            var cmd = new ListCommand();

            cmd.Execute(input);

            //REVIEW: how do I test the console out put?
        }
Esempio n. 5
0
        public void Test()
        {
            var input = new ListInput()
            {
                PointFlag = @"..{0}..{0}..{0}..".ToFormat(Path.DirectorySeparatorChar)
            };

            var cmd = new ListCommand();

            cmd.Execute(input);

            //REVIEW: how do I test the console out put?
        }
Esempio n. 6
0
        public void when_database_contains_versions_then_they_are_listed_to_the_screen()
        {
            _mockVersionRepository.Setup(m => m.GetAllVersions(It.IsAny<string>()))
                .Returns(new List<DatabaseVersion> { new DatabaseVersion(1, "some script"), new DatabaseVersion(2, "some other script") });

            var listCommand = new ListCommand(MockSecureConsole.Object, _mockConnectionFactory.Object, _mockVersionRepositoryFactory.Object);

            using (var stringWriter = new StringWriter())
            {
                Console.SetOut(stringWriter);

                listCommand.Execute(_requiredListCommandArguments);

                Assert.That(stringWriter.ToString().Contains("  1\t\tsome script"));
                Assert.That(stringWriter.ToString().Contains("  2\t\tsome other script"));
            }
        }
Esempio n. 7
0
        public void CanPushStringList()
        {
            ParserParameter param = new ParserPositionalParameter("Names", true);
            ParseResult result = new ParseResult();

            result.AddCommandListValue(param, "Fred");
            result.AddCommandListValue(param, "Barney");

            var pusher = new CommandPusher(result);

            var command = new ListCommand();

            pusher.Push(command);

            command.Names.ShouldContain(x => x == "Fred");
            command.Names.ShouldContain(x => x == "Barney");
        }
Esempio n. 8
0
            public static ListCommand Parse(String command)
            {
                ListCommand newCommand = new ListCommand();

                if (command.StartsWith("+", StringComparison.Ordinal))
                {
                    newCommand.Operator = "+";
                    String[] newItemText = command.Substring(1).Split(textSeperator);
                    newCommand.Value = newItemText[0];
                    newCommand.Text = newItemText[1];
                    if (newItemText.Length == 3)
                    {
                        String IndexText = newItemText[2];
                        try
                        {
                            newCommand.Index = Int32.Parse(IndexText, System.Globalization.CultureInfo.InvariantCulture);
                        }
                        catch
                        {
                        }
                    }
                }
                else if (command.StartsWith("-", StringComparison.Ordinal))
                {
                    newCommand.Operator = "-";
                    String removalIndexString = command.Substring(1);
                    try
                    {
                        newCommand.Index = Int32.Parse(removalIndexString, System.Globalization.CultureInfo.InvariantCulture);
                    }
                    catch
                    {
                    }
                }

                return newCommand;
            }
Esempio n. 9
0
        /// <summary>
        /// 初始化服务器端文件列表
        /// </summary>
        private void InitServerTreeView()
        {
            ListCommand cmd = new ListCommand(myFTP, "/");

            cmd.Execute();
            treeServer.Nodes.Clear();

            int i = 0;

            foreach (List <String> dir in cmd.Directories)
            {
                int      imageIndex = 2;
                TreeNode node       = new TreeNode(dir[3])
                {
                    Tag                = dir[3],
                    ImageIndex         = imageIndex,
                    SelectedImageIndex = imageIndex,
                };
                treeServer.Nodes.Add(node);
                treeServer.Nodes[i].Nodes.Add("");//增加一个空白节点,看起来是加号.为文件夹可展开之必要
                i++;
            }
            ;

            foreach (List <String> file in cmd.Files)
            {
                int      imageIndex = 3;
                TreeNode node       = new TreeNode(file[3])
                {
                    Tag                = file[3],
                    ImageIndex         = imageIndex,
                    SelectedImageIndex = imageIndex,
                };
                treeServer.Nodes.Add(node);
            }
        }
Esempio n. 10
0
        public async Task ExecuteAsync_NoBaseAddressOnHttpState_ShowsWarning()
        {
            ArrangeInputs(commandText: "ls",
                          baseAddress: "http://localhost/",
                          path: "/",
                          urlsWithResponse: null,
                          out MockedShellState shellState,
                          out HttpState httpState,
                          out ICoreParseResult parseResult,
                          out _,
                          out IPreferences preferences);

            httpState.BaseAddress     = null;
            httpState.SwaggerEndpoint = new Uri("http://localhost/swagger.json");
            httpState.Structure       = new DirectoryStructure(null);

            ListCommand listCommand = new ListCommand(preferences);

            await listCommand.ExecuteAsync(shellState, httpState, parseResult, CancellationToken.None);

            string actualOutput = string.Join(Environment.NewLine, shellState.Output);

            Assert.Equal(Resources.Strings.ListCommand_Error_NoBaseAddress, actualOutput);
        }
Esempio n. 11
0
        public async Task ExecuteTest()
        {
            var targetPath = $"{TestContext.CurrentContext.TestDirectory}\\test";
            var listener   = new TcpListener(IPAddress.Any, 8888);

            listener.Start();

            try
            {
                Directory.CreateDirectory(targetPath);
                File.Create($"{targetPath}\\test1.txt");
                File.Create($"{targetPath}\\test2.txt");
                File.Create($"{targetPath}\\test3.txt");
                File.Create($"{targetPath}\\test4.txt");
                Directory.CreateDirectory($"{targetPath}\\test1");
                Directory.CreateDirectory($"{targetPath}\\test2");
                Directory.CreateDirectory($"{targetPath}\\test3");

                using (var client = new TcpClient("localhost", 8888))
                {
                    var acceptedClient = listener.AcceptTcpClient();
                    var command        = new ListCommand(targetPath, acceptedClient);
                    await command.Execute();

                    var reader = new StreamReader(client.GetStream());
                    var actual = await reader.ReadLineAsync();

                    Assert.AreEqual($"7 {targetPath}\\test1.txt false {targetPath}\\test2.txt false {targetPath}\\test3.txt false " +
                                    $"{targetPath}\\test4.txt false {targetPath}\\test1 true {targetPath}\\test2 true {targetPath}\\test3 true", actual);
                }
            }
            finally
            {
                listener.Stop();
            }
        }
Esempio n. 12
0
        public void GetPackageFiltersPackagesUsingIsLatestIfRepositoryDoesNotSupportPrerelease()
        {
            // Arrange
            var package = new Mock <IPackage>(MockBehavior.Strict);

            package.SetupGet(p => p.Id).Returns("A");
            package.SetupGet(p => p.Version).Returns(new SemanticVersion("1.0.0"));
            package.SetupGet(p => p.IsLatestVersion).Returns(true).Verifiable();
            package.SetupGet(p => p.Listed).Returns(true);
            package.SetupGet(p => p.IsAbsoluteLatestVersion).Throws(new Exception("Repository does not support this property."));

            var repository = new Mock <IPackageRepository>(MockBehavior.Strict);

            repository.SetupGet(r => r.SupportsPrereleasePackages).Returns(false).Verifiable();
            repository.Setup(r => r.GetPackages()).Returns(new[] { package.Object }.AsQueryable());
            var factory = new Mock <IPackageRepositoryFactory>(MockBehavior.Strict);

            factory.Setup(f => f.CreateRepository(DefaultRepoUrl)).Returns(repository.Object);

            var cmd = new ListCommand(factory.Object, GetSourceProvider())
            {
                Console    = new Mock <IConsole>().Object,
                Prerelease = true
            };

            cmd.Source.Add(DefaultRepoUrl);

            // Act
            var packages = cmd.GetPackages();

            // Assert
            Assert.Equal(1, packages.Count());
            AssertPackage(new { Id = "A", Ver = "1.0.0" }, packages.First());
            package.Verify();
            repository.Verify();
        }
Esempio n. 13
0
        public void GetPackagesUsesAggregateSourceIfNoSourceDefined()
        {
            // Arrange
            IPackageRepositoryFactory factory = CreatePackageRepositoryFactory();
            IConsole    console = new Mock <IConsole>().Object;
            ListCommand cmd     = new ListCommand()
            {
                RepositoryFactory = factory,
                SourceProvider    = GetSourceProvider(),
                Console           = console
            };

            // Act
            var packages = cmd.GetPackages();

            // Assert
            Assert.Equal(6, packages.Count());
            AssertPackage(new { Id = "AnotherTerm", Ver = "1.0" }, packages.ElementAt(0));
            AssertPackage(new { Id = "CustomUrlUsed", Ver = "1.0" }, packages.ElementAt(1));
            AssertPackage(new { Id = "DefaultUrlUsed", Ver = "1.0" }, packages.ElementAt(2));
            AssertPackage(new { Id = "jQuery", Ver = "1.50" }, packages.ElementAt(3));
            AssertPackage(new { Id = "NHibernate", Ver = "1.2" }, packages.ElementAt(4));
            AssertPackage(new { Id = "SearchPackage", Ver = "1.0" }, packages.ElementAt(5));
        }
Esempio n. 14
0
        internal static IEnumerable <UserListItem> List(ListCommand cmd, UserListFilter filter, IEnumerable <int> selectedIDs, out int totalRecords)
        {
            using (var scope = new QPConnectionScope())
            {
                var options = new UserPageOptions
                {
                    SortExpression = !string.IsNullOrWhiteSpace(cmd.SortExpression) ? UserListItem.TranslateSortExpression(cmd.SortExpression) : null,
                    StartRecord    = cmd.StartRecord,
                    PageSize       = cmd.PageSize,
                    SelectedIDs    = selectedIDs
                };

                if (filter != null)
                {
                    options.Email     = filter.Email;
                    options.FirstName = filter.FirstName;
                    options.LastName  = filter.LastName;
                    options.Login     = filter.Login;
                }

                var rows = Common.GetUserPage(scope.DbConnection, options, out totalRecords);
                return(MapperFacade.UserListItemRowMapper.GetBizList(rows.ToList()));
            }
        }
Esempio n. 15
0
 public static ListResult <ContentListItem> List(ContentListFilter filter, ListCommand cmd, int id) => ContentRepository.GetList(filter, cmd, new[] { id });
Esempio n. 16
0
 public static ListResult <ContentListItem> List(ContentListFilter filter, ListCommand cmd, int[] selectedContentIds) => ContentRepository.GetList(filter, cmd, selectedContentIds);
Esempio n. 17
0
        public void ListCommand_CheckCommandType()
        {
            var listCommand = new ListCommand(null);

            Assert.AreEqual(CommandType.List, listCommand.Type);
        }
        public ListResult <ChildEntityPermissionListItem> List(int parentId, int?groupId, int?userId, ListCommand cmd)
        {
            var list         = Enumerable.Empty <ChildEntityPermissionListItem>();
            var totalRecords = 0;

            if (groupId.HasValue || userId.HasValue)
            {
                list = Repository.List(parentId, groupId, userId, cmd, out totalRecords);
            }

            return(new ListResult <ChildEntityPermissionListItem>
            {
                Data = list.ToList(),
                TotalRecords = totalRecords
            });
        }
Esempio n. 19
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ListCommandBuilder"/> class.
 /// </summary>
 /// <param name="command">The command.</param>
 internal ListCommandBuilder(ref ListCommand command)
 {
     this.command = command;
 }
Esempio n. 20
0
 public static ListResult <FieldListItem> List(int contentId, ListCommand cmd) => FieldRepository.GetList(cmd, contentId);
Esempio n. 21
0
 public static ListResult <ContentListItem> GetAcceptableContentForWorkflow(ContentListFilter filter, ListCommand cmd, int[] selectedContentIDs) => ContentRepository.GetList(filter, cmd, selectedContentIDs);
Esempio n. 22
0
 public static ListResult <ContentListItem> List(ContentListFilter filter, ListCommand cmd)
 {
     filter.IsVirtual = true;
     return(ContentRepository.GetList(filter, cmd));
 }
Esempio n. 23
0
        internal static ListResult <ContentListItem> GetList(ContentListFilter filter, ListCommand cmd, int[] selectedContentIDs = null, int workflowId = 0)
        {
            using (var scope = new QPConnectionScope())
            {
                var options = new ContentPageOptions
                {
                    ContentName    = filter.ContentName,
                    SiteId         = filter.SiteId,
                    IsVirtual      = filter.IsVirtual,
                    GroupId        = filter.GroupId,
                    Mode           = filter.Mode,
                    SelectedIDs    = selectedContentIDs,
                    UserId         = QPContext.CurrentUserId,
                    UseSecurity    = !QPContext.IsAdmin,
                    IsAdmin        = QPContext.IsAdmin,
                    SortExpression = cmd.SortExpression,
                    StartRecord    = cmd.StartRecord,
                    PageSize       = cmd.PageSize,
                    LanguageId     = QPContext.CurrentUserIdentity.LanguageId,
                    CustomFilter   = filter.CustomFilter
                };

                var rows = Common.GetContentsPage(scope.DbConnection, options, out var totalRecords);
                return(new ListResult <ContentListItem> {
                    Data = MapperFacade.ContentListItemRowMapper.GetBizList(rows.ToList()), TotalRecords = totalRecords
                });
            }
        }
Esempio n. 24
0
 /// <summary>
 /// Splits a full command string set into an array of ListCommands.
 /// </summary>
 /// <remarks>You don't need to use this from your code.</remarks>
 /// <param name="postedCommands">The set of commands to split.</param>
 /// <returns>The created array of ListCommands.</returns>
 public static ListCommand[] Split(String postedCommands)
 {
     String[] commandsText = postedCommands.Split(commandSeperator);
     ListCommand[] commands = new ListCommand[commandsText.Length];
     for (Int32 i = 0; i < commandsText.Length; i++)
     {
         commands[i] = ListCommand.Parse(commandsText[i]);
     }
     return commands;
 }
 static Int32 Main(String[] args)
 {
     try {
         if (args.Length == 0)
         {
             Error.WriteLine(Usage);
             return(ArgumentErrorCode);
         }
         var c = args[0];
         if (ListCommand.StartsWith(c, OrdinalIgnoreCase))
         {
             if (args.Length != 2)
             {
                 Error.WriteLine(Usage);
                 return(ArgumentErrorCode);
             }
             WriteLine(Join(NewLine,
                            new FileInfo(args[1])
                            .ListExtendedAttributes()));
             return(SuccessCode);
         }
         else if (GetCommand.StartsWith(c, OrdinalIgnoreCase))
         {
             if (args.Length != 3)
             {
                 Error.WriteLine(Usage);
                 return(ArgumentErrorCode);
             }
             OpenStandardOutput().Write(
                 new FileInfo(args[1])
                 .GetExtendedAttribute(args[2]).Span);
             return(SuccessCode);
         }
         else if (SetCommand.StartsWith(c, OrdinalIgnoreCase))
         {
             if (args.Length != 4)
             {
                 Error.WriteLine(Usage);
                 return(ArgumentErrorCode);
             }
             new FileInfo(args[1])
             .SetExtendedAttributeString(args[2], args[3]);
             return(SuccessCode);
         }
         else if (DeleteCommand.StartsWith(c, OrdinalIgnoreCase))
         {
             if (args.Length != 3)
             {
                 Error.WriteLine(Usage);
                 return(ArgumentErrorCode);
             }
             new FileInfo(args[1]).DeleteExtendedAttribute(args[2]);
             return(SuccessCode);
         }
         else
         {
             Error.WriteLine(Usage);
             return(ArgumentErrorCode);
         }
     } catch (Exception e) {
         Error.WriteLine(e.Message);
         return(FailureCode);
     }
 }
Esempio n. 26
0
 public ListTemplatesCommand(ListCommand parent, IConsole console)
 {
     _main    = parent.Main;
     _console = console;
 }
Esempio n. 27
0
 public static ListResult <FieldListItem> ListForExportExpanded(ListCommand cmd, int contentId, int[] ids) => FieldRepository.GetListForSelect(cmd, contentId, ids, FieldSelectMode.ForExportExpanded);
Esempio n. 28
0
 public static ListResult <ContentListItem> ListForField(ContentListFilter filter, ListCommand cmd, int id)
 {
     filter.Mode = ContentSelectMode.ForField;
     return(List(filter, cmd, id));
 }
Esempio n. 29
0
 public ListResult <ObjectFormatVersionListItem> GetTemplateObjectFormatVersionsByFormatId(ListCommand listCommand, int parentId) => GetObjectFormatVersionsByFormatId(listCommand, parentId, false);
Esempio n. 30
0
 public static ListResult <ContentListItem> ListForUnion(ContentListFilter filter, ListCommand cmd, int[] ids)
 {
     filter.Mode = ContentSelectMode.ForUnion;
     return(List(filter, cmd, ids));
 }
Esempio n. 31
0
        private static ListResult <ObjectFormatVersionListItem> GetObjectFormatVersionsByFormatId(ListCommand listCommand, int formatId, bool pageOrTemplate)
        {
            var list = PageTemplateRepository.ListFormatVersions(listCommand, formatId, out var totalRecords, pageOrTemplate);

            return(new ListResult <ObjectFormatVersionListItem>
            {
                Data = list.ToList(),
                TotalRecords = totalRecords
            });
        }
Esempio n. 32
0
        public void when_no_arguments_have_been_specified_then_the_list_command_help_text_is_displayed()
        {
            var stringWriter = new StringWriter();
            typeof(ParserSettings).GetProperty("Consumed", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(Parser.Default.Settings, false);
            Parser.Default.Settings.HelpWriter = stringWriter;

            var listCommand = new ListCommand(MockSecureConsole.Object, _mockConnectionFactory.Object, _mockVersionRepositoryFactory.Object);

            listCommand.Execute(new string[] { });

            Assert.That(stringWriter, Is.Not.Null.Or.Empty);
        }
Esempio n. 33
0
 public ListResult <ObjectFormatVersionListItem> GetPageObjectFormatVersionsByFormatId(ListCommand listCommand, int parentId) => GetObjectFormatVersionsByFormatId(listCommand, parentId, true);
Esempio n. 34
0
        public IEnumerable <SearchInArticlesResultItem> SearchInArticles(int siteId, int userId, string sqlSearchString, int?articleId, ListCommand listCmd, out int totalRecords)
        {
            var dt     = Common.SearchInArticles(QPContext.EFContext, QPConnectionScope.Current.DbConnection, siteId, userId, sqlSearchString, articleId, TranslateSortExpression(listCmd.SortExpression), listCmd.StartRecord, listCmd.PageSize, out totalRecords);
            var result = Mapper.Map <IEnumerable <DataRow>, IEnumerable <SearchInArticlesResultItem> >(dt.AsEnumerable()).ToList();

            if (QPContext.DatabaseType == DatabaseType.Postgres)
            {
                var ids          = result.Select(n => n.Id).ToArray();
                var descriptions = Common.GetPgFtDescriptions(QPConnectionScope.Current.DbConnection, ids, sqlSearchString);
                foreach (var item in result)
                {
                    if (descriptions.TryGetValue(item.Id, out var text))
                    {
                        item.Text = text;
                    }
                }
            }
            else
            {
                foreach (var item in result)
                {
                    item.Text = Cleaner.RemoveAllHtmlTags(item.Text);
                }
            }

            return(result);
        }
Esempio n. 35
0
 public GenericListPage()
 {
     ContextMenuCommand = new ListCommand(this);
     InitializeComponent();
 }
Esempio n. 36
0
        public IEnumerable <SearchInArticlesResultItem> SearchInArticles(int siteId, int userId, string sqlSearchString, int?articleId, ListCommand listCmd, out int totalRecords)
        {
            var dt     = QPContext.EFContext.SearchInArticles(siteId, userId, sqlSearchString, articleId, TranslateSortExpression(listCmd.SortExpression), listCmd.StartRecord, listCmd.PageSize, out totalRecords);
            var result = Mapper.Map <IDataReader, IEnumerable <SearchInArticlesResultItem> >(dt.CreateDataReader()).ToList();

            foreach (var item in result)
            {
                item.Text = Cleaner.RemoveAllHtmlTags(item.Text);
            }

            return(result);
        }
Esempio n. 37
0
 internal static IEnumerable <PageTemplateSearchListItem> GetSearchTemplatePage(ListCommand listCommand, int siteId, string filter, out int totalRecords)
 {
     using (var scope = new QPConnectionScope())
     {
         var rows   = Common.GetSearchTemplatePage(scope.DbConnection, listCommand.SortExpression, siteId, filter, out totalRecords, listCommand.StartRecord, listCommand.PageSize);
         var result = MapperFacade.PageTemplateSearchResultRowMapper.GetBizList(rows.ToList());
         return(result);
     }
 }
Esempio n. 38
0
 public ListRecordsCommand(ListCommand parent, IConsole console)
 {
     _main    = parent.Main;
     _console = console;
 }
Esempio n. 39
0
 private ListConnector ConnectListControl(ListCommand command, ComboBox control, Label label, CommandCategory category)
 {
     return(new ListConnector(command, control, label, category));
 }
        public IEnumerable <ChildEntityPermissionListItem> List(int siteId, int?groupId, int?userId, ListCommand cmd, out int totalRecords)
        {
            using (var scope = new QPConnectionScope())
            {
                cmd.SortExpression = TranslateHelper.TranslateSortExpression(cmd.SortExpression);
                IEnumerable <DataRow> rows;
                totalRecords = 0;
                if (userId.HasValue)
                {
                    rows = Common.GetChildContentPermissionsForUser(scope.DbConnection, siteId, userId.Value, cmd.SortExpression, cmd.StartRecord, cmd.PageSize, out totalRecords);
                }
                else if (groupId.HasValue)
                {
                    rows = Common.GetChildContentPermissionsForGroup(scope.DbConnection, siteId, groupId.Value, cmd.SortExpression, cmd.StartRecord, cmd.PageSize, out totalRecords);
                }
                else
                {
                    throw new ArgumentNullException(nameof(groupId));
                }

                return(MapperFacade.ChildEntityPermissionListItemRowMapper.GetBizList(rows.ToList()));
            }
        }
Esempio n. 41
0
 private WarningListConnector ConnectWarningListControl(ListCommand command, ComboBox control, Label label, CommandCategory category, string message, string caption, bool clearSelectedItem)
 {
     return(new WarningListConnector(command, control, label, category, message, caption, clearSelectedItem));
 }