Ejemplo n.º 1
0
 public void Run(SearchSpec spec)
 {
     foreach (var item in spec.Conditions.Where(cond => cond != null))
     {
         item.Apply(this);
     }
 }
        private async Task <List <Component> > GetTargetComponentsFromArdoq(SearchSpec spec)
        {
            List <Component> allComponents;

            if (string.IsNullOrEmpty(spec.SearchFolder))
            {
                allComponents = await _client.ComponentService.GetAllComponents();
            }
            else
            {
                var folder = await _client.FolderService.GetFolderByName(spec.SearchFolder);

                var componentCollectionTask = folder.Workspaces
                                              .Select(workspaceId => _client.ComponentService.GetComponentsByWorkspace(workspaceId));
                var componentCollection = await Task.WhenAll(componentCollectionTask);

                allComponents = componentCollection.Aggregate(
                    new List <Component>(),
                    (list, components) =>
                {
                    list.AddRange(components);
                    return(list);
                }
                    );
            }

            return(allComponents);
        }
        public void Search_OneSearchTerm_FindsExpectedComponents()
        {
            // Arrange
            var comp = new Component("my-comp", null, null)
            {
                Id = "my-id", Type = "MyType"
            };
            var spec = new SearchSpec(null);

            spec.AddElement(new ComponentTypeAndFieldSearchSpecElement {
                ComponentType = "MyType"
            });

            _tagServiceMock.Setup(ts => ts.GetAllTags(null))
            .Returns(Task.FromResult(new List <Tag>()));
            _componentServiceMock.Setup(cs => cs.GetAllComponents(null))
            .Returns(Task.FromResult(new List <Component> {
                comp
            }));

            var searcher = GetSearcher();

            // Act
            var found = searcher.Search(spec).Result;

            // Assert
            Assert.Single(found);
        }
        public async Task <IEnumerable <Component> > Search(SearchSpec spec)
        {
            List <Component> allComponents = await GetTargetComponentsFromArdoq(spec);

            var allTags = await _client.TagService.GetAllTags();

            bool started = false;

            return(spec.Elements
                   .Aggregate(
                       new List <Component>(),
                       (remaining, element) =>
            {
                IEnumerable <Component> comps;
                if (started)
                {
                    comps = element.Search(allTags, allComponents, remaining);
                }
                else
                {
                    comps = element.Search(allTags, allComponents);
                }

                started = true;

                return comps.ToList();
            }));
        }
Ejemplo n.º 5
0
        private void SearchAndLink(ParentChildRelation relation, SearchSpec searchSpec)
        {
            var sourceComponent = _sourceWorkspaceSession.GetChildComponent(relation);
            var components      = _searcher.Search(searchSpec).Result;

            if (components == null || !components.Any())
            {
                return;
            }

            var refType = _sourceWorkspaceSession.GetReferenceTypeForName(_ardoqReferenceName);

            var existingReferences = _sourceWorkspaceSession.GetAllSourceReferencesFromChild(relation)
                                     .Where(r => r.Type == refType)
                                     .ToList();

            foreach (var targetComponent in components)
            {
                if (existingReferences.Any(r => r.Target == targetComponent.Id))
                {
                    continue;
                }

                _sourceWorkspaceSession.AddReference(refType, sourceComponent, targetComponent);
            }
        }
        public async System.Threading.Tasks.Task <IActionResult> GetArticle(string searchValue, int pageSize, int skip, int take, string sortField, string dir, int showDraft = 0, string additionalFilter = "")
        {
            try
            {
                var searchspec = new SearchSpec();
                searchspec.Dir        = dir;
                searchspec.SearchText = searchValue;
                searchspec.PageSize   = pageSize;
                searchspec.Skip       = skip;
                searchspec.Take       = take;
                searchspec.SortField  = sortField;
                int  articalTypeNumber  = 0;
                bool showDraftedArticle = false;
                if (!string.IsNullOrEmpty(additionalFilter))
                {
                    var articalType = _articleService.GetArticleTypeByName(additionalFilter);
                    if (articalType.Result != null)
                    {
                        articalTypeNumber = articalType.Result.ArticleTypeId;
                    }
                }
                if (showDraft > 0)
                {
                    showDraftedArticle = true;
                }

                var articleData = await _articleService.GetArticles(articalTypeNumber, searchspec, showDraftedArticle);

                var result = articleData.Select(x => new
                {
                    Id              = x.ArticleId,
                    Title           = x.Title,
                    ShowInArchive   = (x.ShowInArchive == true ? "Yes" : "No"),
                    IslocalMedia    = (x.IsLocalMedia == true ? "Yes" : "No"),
                    Excerpt         = x.Excerpt,
                    ArticleTypeName = x.ArticleTypeName,
                    IsFeatured      = (x.IsFeatured == true ? "Yes" : "No"),
                    Body            = x.Body,
                    MediaCaption    = x.MediaCaption,
                    Status          = x.Status.ToString(),
                    UpdatedOn       = x.UpdatedOn.ToString("MM/dd/yyyy"),
                    CreatedOn       = x.CreatedOn?.ToString("MM/dd/yyyy"),
                    CreatedByName   = x.CreatedByName,
                    UpdatedByName   = x.UpdatedByName
                }).ToList();

                var totalCount = await _articleService.TotalArticleRecord(searchValue);

                return(Ok(new { result, count = totalCount }));
            }
            catch (Exception e)
            {
                ModelState.AddModelError("", e.Message);
                return(BadRequestFormatter.BadRequest(this, e));
            }
        }
Ejemplo n.º 7
0
        public IEnumerable <IContactInfo> GetContacts(SearchSpec spec)
        {
            using (_lock.Read())
            {
                var executor = new QueryExecutor(_list);

                executor.Run(spec);

                return(ConvertListOfContactToListOfContactInfo(executor.GetSubset().ToList()));
            }
        }
Ejemplo n.º 8
0
        public async Task <IEnumerable <Article> > GetArticles(int articleTypeId, SearchSpec searchSpec, bool includeDraft = false)
        {
            var whereClause = "WHERE IsDeleted=0";

            if (articleTypeId > 0)
            {
                searchSpec.SearchText = "%" + searchSpec.SearchText + "%";
                whereClause          += " AND (article.ArticleTypeId = " + articleTypeId + ") ";
            }
            if (!string.IsNullOrEmpty(searchSpec.SearchText))
            {
                searchSpec.SearchText = "%" + searchSpec.SearchText + "%";
                whereClause          += " AND (article.Name LIKE @searchText OR article.Title LIKE @searchText OR Excerpt LIKE @searchText OR Body LIKE @searchText) ";
            }
            var sortField = searchSpec.SortField;

            if (string.IsNullOrEmpty(sortField))
            {
                sortField = "article.Name";
            }
            var showDraft = "";

            if (!includeDraft)
            {
                if (!string.IsNullOrEmpty(whereClause))
                {
                    showDraft += " AND ";
                }
                showDraft += $@" Status<> {(int)ArticleStatus.Draft} ";
            }
            else
            {
                if (!string.IsNullOrEmpty(whereClause))
                {
                    showDraft += " AND ";
                }
                showDraft += $@" Status<> {(int)ArticleStatus.Published} ";
            }
            var sql = $@"SELECT article.*,
                                    createdByUser.Displayname CreatedByName,
                                    updatedByUser.Displayname UpdatedByName,
                                    articleType.Name ArticleTypeName
                                    FROM [Article] article
                                    LEFT JOIN [Users] createdByUser
                                    ON createdByUser.UserGuid = article.CreatedBy
                                    LEFT JOIN [Users] updatedByUser
                                    ON updatedByUser.UserGuid = article.CreatedBy
                                    LEFT JOIN [ArticleType] articleType
                                    ON articleType.ArticleTypeId = article.ArticleTypeId 
                                {whereClause} {showDraft} ORDER BY {sortField} {searchSpec.Dir} OFFSET {searchSpec.Skip} ROWS FETCH NEXT {searchSpec.Take} ROWS ONLY";

            return(await _context.Connection.QueryAsync <Article>(sql, searchSpec));
        }
Ejemplo n.º 9
0
        public IEnumerable <IContactInfo> GetContacts(SearchSpec spec)
        {
            Send(new XElement(XName.Get("request", this.Namespace),
                              new XElement(XName.Get("search", this.Namespace),
                                           new XElement(XName.Get(spec.Conditions.First().GetType().ToString(), this.Namespace), spec.Conditions.First().Text),
                                           spec.Conditions.Count == 1 ? null : new XElement(XName.Get(spec.Conditions.First().GetType().ToString(), this.Namespace), spec.Conditions.First().Text)
                                           )
                              )
                 );

            return(RecieveContacts().ToList());
        }
        public void Search_Hierarchy_FindsExpectedComponents()
        {
            // Arrange
            var parentId  = "parent-1";
            var component = new Component("myName", null, null)
            {
                Id     = parentId,
                Type   = "myType",
                Fields = new Dictionary <string, object> {
                    ["k1"] = 99
                }
            };


            _tagServiceMock.Setup(ts => ts.GetAllTags(null))
            .Returns(Task.FromResult(new List <Tag> {
                new Tag("tag1", null, null)
                {
                    Components = new List <string> {
                        parentId
                    }
                }
            }));
            _componentServiceMock.Setup(cs => cs.GetAllComponents(null))
            .Returns(Task.FromResult(new List <Component> {
                component
            }));

            var spec      = new SearchSpec(null);
            var tagSearch = new TagSearchSpecElement();

            tagSearch.AddTags(new List <string> {
                "tag1"
            });
            spec.AddElement(tagSearch);

            var typeAndFieldSearchSpec = new ComponentTypeAndFieldSearchSpecElement {
                ComponentType = "myType"
            };

            typeAndFieldSearchSpec.AddFieldFilter("k1", 99);

            spec.AddElement(typeAndFieldSearchSpec);
            var searcher = GetSearcher();

            // Act
            var found = searcher.Search(spec).Result;

            // Assert
            Assert.Single(found);
            Assert.Equal("myName", found.Single().Name);
        }
        /// <summary>
        /// Tests the url against the system provided search descriptors and returns the first matching
        /// search spec (if any).
        /// </summary>
        /// <param name="url">The url to test</param>
        /// <returns>The first matching spec, null if no search spec could be matched</returns>
        private SearchSpec GetSearchSpec(string url)
        {
            SearchSpec searchSpec = null;

            foreach (SearchDescriptor searchDescriptor in SearchDescriptors)
            {
                if (IsSearchUrl(url, searchDescriptor))
                {
                    string keywords = (string)UrlHelper.GetQueryParams(url)[searchDescriptor.KeyWordQueryParam];

                    searchSpec = new SearchSpec();
                    searchSpec.SearchProviderName = searchDescriptor.SearchProviderName;
                    searchSpec.SearchUrl          = url;
                    searchSpec.Keywords           = keywords.Split('+');
                    break;
                }
            }
            return(searchSpec);
        }
        public static SearchSpec ToSearchSpecFromConnectionString(this string connectionString, string searchFolder)
        {
            var connectionStringType = connectionString.GetConnectionStringType();

            if (ConnectionStringType.NotConnectionString == connectionStringType)
            {
                throw new ArgumentException("Not a connection string.");
            }

            SearchSpec res = null;

            switch (connectionStringType)
            {
            case ConnectionStringType.ServiceBusOrEventHub:
                res = GetSearchSpecForServiceBusOrEventHubNamespace(connectionString, searchFolder);
                break;
            }

            return(res);
        }
        private static SearchSpec GetSearchSpecForServiceBusOrEventHubNamespace(string connectionString, string searchFolder)
        {
            var arr        = connectionString.Split(';');
            var endpoint   = arr.Single(a => a.StartsWith("Endpoint="));
            var entityPath = arr.Single(a => a.StartsWith("EntityPath="));

            var spec = new SearchSpec(searchFolder);

            var namespaceElement = new ComponentTypeAndFieldSearchSpecElement();

            namespaceElement.ComponentType = "ServiceBusNamespace";
            namespaceElement.AddFieldFilter("uri", endpoint.Split('=')[1]);
            spec.AddElement(namespaceElement);

            var entityElement = new ComponentTypeAndFieldSearchSpecElement();

            entityElement.Name = entityPath.Split('=')[1];
            spec.AddElement(entityElement);

            return(spec);
        }
        private void Search_IntegrationTest()
        {
            // Arrange
            var url          = "";
            var token        = "";
            var organization = "";
            var client       = new ArdoqClient(new HttpClient(), url, token, organization);

            var searcher = new ArdoqSearcher(client, new ConsoleLogger());

            var tag = "integration-test";

            var spec       = new SearchSpec(null);
            var tagElement = new TagSearchSpecElement();

            tagElement.AddTags(new List <string> {
                tag
            });
            spec.AddElement(tagElement);

            // Act
            var results = searcher.Search(spec).Result;
        }
        public void Search_HierarchyNoHits_ReturnsEmptyList()
        {
            // Arrange
            var parentId        = "parent-1";
            var childId         = "child-1";
            var parentComponent = new Component("parent", null, null)
            {
                Id       = parentId,
                Type     = "ParentType",
                Children = new List <string> {
                    childId
                }
            };

            var childComponent = new Component("child", null, null)
            {
                Id     = childId,
                Type   = "ChildType",
                Fields = new Dictionary <string, object> {
                    ["k1"] = 66
                }
            };


            _tagServiceMock.Setup(ts => ts.GetAllTags(null))
            .Returns(Task.FromResult(new List <Tag> {
                new Tag("tag1", null, null)
                {
                    Components = new List <string> {
                        parentId
                    }
                }
            }));
            _componentServiceMock.Setup(cs => cs.GetAllComponents(null))
            .Returns(Task.FromResult(new List <Component> {
                parentComponent, childComponent
            }));

            var spec    = new SearchSpec(null);
            var tagSpec = new TagSearchSpecElement();

            tagSpec.AddTags(new List <string> {
                "tag1"
            });
            spec.AddElement(tagSpec);

            var typeAndFieldSearchSpec = new ComponentTypeAndFieldSearchSpecElement {
                ComponentType = "ChildType"
            };

            typeAndFieldSearchSpec.AddFieldFilter("k1", 99);

            spec.AddElement(typeAndFieldSearchSpec);
            var searcher = GetSearcher();

            // Act
            var found = searcher.Search(spec).Result;

            // Assert
            Assert.Empty(found);
        }
Ejemplo n.º 16
0
 static bool ParseArguments(string[] args)
 {
     bool cOptionFound = false;
     bool pOptionFound = false;
     bool rOptionFound = false;
     bool fOptionFound = false;
     bool oOptionFound = false;
     foreach (string optionString in args)
     {
         string option = optionString.Substring(0, 2);
         string[] pars = optionString.Substring(2).Split(new char[] { ':' });
         for (int i = 0; i < pars.Length; i += 1)
         {
             if (pars[i].StartsWith("\"") && pars[i].EndsWith("\""))
                 pars[i] = pars[i].Substring(1, pars[i].Length - 2);
         }
         switch (option)
         {
             case "-c":
                 if (cOptionFound)
                     throw new ArgumentException("The -c option can only be specified once");
                 if (pars.Length != 5)
                     throw new ArgumentException("The -c option was not specified correctly");
                 cOptionFound = true;
                 server = pars[0];
                 portNumber = Int32.Parse(pars[1]);
                 databaseName = pars[2];
                 sdkUser = pars[3];
                 sdkUserPwd = pars[4];
                 break;
             case "-p":
                 if (pOptionFound)
                     throw new ArgumentException("The -p option can only be specified once");
                 if (pars.Length != 2)
                     throw new ArgumentException("The -p option was not specified correctly");
                 pOptionFound = true;
                 projectName = pars[0];
                 switch (pars[1])
                 {
                     case "a":
                         viewType = EHPMReportViewType.AgileMainProject;
                         break;
                     case "s":
                         viewType = EHPMReportViewType.ScheduleMainProject;
                         break;
                     case "b":
                         viewType = EHPMReportViewType.AgileBacklog;
                         break;
                     case "q":
                         viewType = EHPMReportViewType.AllBugsInProject;
                         break;
                     default:
                         throw new ArgumentException("An unsupported view type was specified, valid values are one of [a|s|b|q]");
                 }
                 break;
             case "-r":
                 if (rOptionFound || fOptionFound)
                     throw new ArgumentException("Either the -r option or the -f option can only be specified once");
                 if (pars.Length != 2)
                     throw new ArgumentException("The -r option was not specified correctly");
                 reportName = pars[0];
                 reportUserName = pars[1];
                 searchSpec = SearchSpec.Report;
                 rOptionFound = true;
                 break;
             case "-f":
                 if (rOptionFound || fOptionFound)
                     throw new ArgumentException("Either the -r option or the -f option can only be specified once");
                 if (pars.Length != 1)
                     throw new ArgumentException("The -f option was not specified correctly");
                 findQuery = pars[0];
                 searchSpec = SearchSpec.FindQuery;
                 fOptionFound = true;
                 break;
             case "-o":
                 if (oOptionFound)
                     throw new ArgumentException("The -o option can only be specified once");
                 if (pars.Length != 1)
                     throw new ArgumentException("The -o option was not specified correctly");
                 outputFileName = pars[0];
                 oOptionFound = true;
                 break;
             case "-h":
                 if (oOptionFound)
                     throw new ArgumentException("The -o option can only be specified once");
                 if (pars.Length != 1)
                     throw new ArgumentException("The -o option was not specified correctly");
                 outputFileName = pars[0];
                 oOptionFound = true;
                 break;
             default:
                 throw new ArgumentException("An unsupported option was specifed: " + option);
         }
     }
     return (cOptionFound && pOptionFound && oOptionFound && (rOptionFound || fOptionFound));
 }
Ejemplo n.º 17
0
 public async Task <IEnumerable <Article> > GetArticles(int articleTypeId, SearchSpec searchSpec, bool includeDraft = false)
 {
     return(await _articleRepository.GetArticles(articleTypeId, searchSpec, includeDraft));
 }
Ejemplo n.º 18
0
        public async Task <IEnumerable <Application> > GetApplications(int applicationCategoryId, SearchSpec searchSpec)
        {
            var whereClause = "";

            if (!string.IsNullOrEmpty(searchSpec.SearchText))
            {
                searchSpec.SearchText = "%" + searchSpec.SearchText + "%";
                whereClause           = " AND (Name like @searchText OR Title like @searchText OR Description like @searchText)";
            }
            var sortField = searchSpec.SortField;

            if (string.IsNullOrEmpty(sortField))
            {
                sortField = "Name";
            }
            var sql = $@"SELECT * FROM [Application] WHERE 1=1 {whereClause} ORDER BY {sortField} {searchSpec.Dir} OFFSET {searchSpec.Skip} ROWS FETCH NEXT {searchSpec.Take} ROWS ONLY";

            return(await _context.Connection.QueryAsync <Application>(sql, searchSpec));
        }
        /// <summary>
        /// Tests the url against the system provided search descriptors and returns the first matching
        /// search spec (if any).
        /// </summary>
        /// <param name="url">The url to test</param>
        /// <returns>The first matching spec, null if no search spec could be matched</returns>
        private SearchSpec GetSearchSpec(string url)
        {
            SearchSpec searchSpec = null;
            foreach (SearchDescriptor searchDescriptor in SearchDescriptors)
            {
                if (IsSearchUrl(url, searchDescriptor))
                {
                    string keywords = (string)UrlHelper.GetQueryParams(url)[searchDescriptor.KeyWordQueryParam];

                    searchSpec = new SearchSpec();
                    searchSpec.SearchProviderName = searchDescriptor.SearchProviderName;
                    searchSpec.SearchUrl = url;
                    searchSpec.Keywords = keywords.Split('+');
                    break;
                }

            }
            return searchSpec;
        }
Ejemplo n.º 20
0
 public async Task <IEnumerable <Application> > GetApplications(int applicationCategoryId, SearchSpec searchSpec)
 {
     return(await _applicationRepository.GetApplications(applicationCategoryId, searchSpec));
 }