public async void GetSearchResultsController_ReturnsNullValue()
        {
            //Arrange
            var httpContext = new DefaultHttpContext();

            SearchQueryDto searchQueryDto = new SearchQueryDto();

            var items = await GetSearchResultsDtoFromFileAsync();

            var mediator = new Mock <IMediator>();

            var controller = new SearchController(mediator.Object)
            {
                ControllerContext = new ControllerContext()
                {
                    HttpContext = httpContext,
                }
            };

            //ACT
            var result = await controller.GetSearchResults(searchQueryDto);

            var okResult = result.Result as OkObjectResult;

            //ASSERT
            Assert.IsType <OkObjectResult>(result.Result);
            Assert.IsAssignableFrom <IActionResult>(result.Result);
            Assert.Empty((IEnumerable <SearchResultDto>)okResult.Value);
        }
        public async void GetSearchResultsController_ReturnsOkValue()
        {
            //Arrange
            var httpContext = new DefaultHttpContext();

            SearchQueryDto searchQueryDto = new SearchQueryDto();

            var items = await GetSearchResultsDtoFromFileAsync();

            var mediator = new Mock <IMediator>();

            mediator.Setup(m => m.Send(It.IsAny <GetSearchResultsQuery>(), new System.Threading.CancellationToken())).Returns(Task.FromResult(items));

            var controller = new SearchController(mediator.Object)
            {
                ControllerContext = new ControllerContext()
                {
                    HttpContext = httpContext,
                }
            };

            //ACT
            var result = await controller.GetSearchResults(searchQueryDto);

            var okResult = result.Result as OkObjectResult;

            //ASSERT
            Assert.IsType <OkObjectResult>(result.Result);
            Assert.IsAssignableFrom <IActionResult>(result.Result);
            Assert.NotEmpty((IEnumerable <SearchResultDto>)okResult.Value);
        }
Пример #3
0
        public async Task <IActionResult> GetMembers([FromBody] SearchQueryDto searchEntry, [FromRoute] string groupId)
        {
            var _userId = this.HttpContext.User.Claims.First(c => c.Type == "sub").Value;
            var result  = await _memberService.GetMembersAsync(groupId, searchEntry);

            return(Ok(result));
        }
Пример #4
0
        //Gets Server Status
        public List <SearchQueryDto> ServerStatus()
        {
            var          result = new List <SearchQueryDto>();
            const string query  = "select * from server_status where progress = 0 ORDER BY time ASC;";

            if (!OpenConnection())
            {
                return(result);
            }
            try
            {
                var cmd    = new MySqlCommand(query, _connection);
                var reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    var temp = new SearchQueryDto
                    {
                        QueryId      = reader["qID"].ToString(),
                        UserId       = reader["uID"].ToString(),
                        Progress     = reader["progress"].ToString(),
                        CreationTime = reader["time"].ToString()
                    };
                    result.Add(temp);
                }
                reader.Close();
            }
            catch (Exception)
            {
                // ignored
            }
            _connection.Close();
            return(result);
        }
        public async Task <SearchResult> ExecuteSearchAsync(SearchQueryDto searchQueryDto)
        {
            var cacheKey     = searchQueryDto.CompanyURI + searchQueryDto.SearchTerm + SearchEngineNames.Google;
            var searchResult = await _searchResultCacheProvider.GetOrCreate(cacheKey, () => GetSearchData(searchQueryDto));

            return(searchResult);
        }
        public async Task <IActionResult> GetGroups([FromBody] SearchQueryDto searchEntry)
        {
            var subjectId = HttpContext.User.Identity;
            var result    = await _groupService.GetGroups(searchEntry);

            return(Ok(result));
        }
Пример #7
0
        public SearchResultModel <ScenarioDigestListItem> MinimalDataSearch(
            SearchQueryDto queryModel,
            bool isLibraried,
            IEnumerable <int> passesToInclude)
        {
            lock (_session)
            {
                IReadOnlyCollection <ScenarioDigestListItem> allRecords
                    = _session.GetAllUsingProjection
                      <Scenario, Scenarios_MinimalData, ScenarioDigestListItem>
                          (s => s.IsLibraried.HasValue && s.IsLibraried.Value == isLibraried);

                List <ScenarioDigestListItem> searchQuery = allRecords.ToList();

                if (!string.IsNullOrWhiteSpace(queryModel.Title))
                {
                    searchQuery.RemoveAll(x => DoesNotContainTitle(queryModel.Title, x.Name));
                }

                if (passesToInclude.Any())
                {
                    IEnumerable <ScenarioDigestListItem> scenariosWithPassesToInclude = allRecords
                                                                                        .Where(scenario =>
                                                                                               scenario.Passes.Any(pass => passesToInclude.Contains(pass.Id)) && !searchQuery.Contains(scenario));
                    searchQuery.AddRange(scenariosWithPassesToInclude);
                }

                IOrderedEnumerable <ScenarioDigestListItem> orderQuery =
                    queryModel.OrderDirection == OrderDirection.Desc
                    ? searchQuery.OrderByDescending(OrderByProperty(queryModel.OrderBy))
                    : searchQuery.OrderBy(OrderByProperty(queryModel.OrderBy));

                var searchResults = new SearchResultModel <ScenarioDigestListItem>();
                searchResults.Items = orderQuery
                                      .Skip(queryModel.Skip)
                                      .Take(queryModel.Top)
                                      .ToList();
                searchResults.TotalCount = orderQuery.Count();

                return(searchResults);
            }

            Func <ScenarioDigestListItem, object> OrderByProperty(OrderBy orderBy)
            {
                if (OrderBy.Date == orderBy)
                {
                    return(x => x.DateUserModified);
                }
                else
                {
                    return(x => x.Name);
                }
            }

            bool DoesNotContainTitle(string title, string scenarioDigestName)
            {
                return(scenarioDigestName.IndexOf(title, StringComparison.CurrentCultureIgnoreCase) < 0);
            }
        }
        public async Task <IEnumerable <FoundItem> > Search([FromBody] SearchQueryDto searchQueryDto)
        {
            var query   = searchQueryDto.Query;
            var markets = searchQueryDto.Markets?.ToImmutableList() ?? ImmutableList <string> .Empty;
            var size    = searchQueryDto.MaxResults ?? Constants.MaxResults;

            return(await _searchService.Search(query, markets, size));
        }
        public async Task <IEnumerable <GroupDto> > GetSubgroups(SearchQueryDto searchEntryDto, string parentId)
        {
            var searchEntry = _mapper.Map <SearchQueryDto, SearchQueryModel>(searchEntryDto);
            var result      = await _groupRequestService.GetSubgroups(searchEntry, parentId);

            var list = _mapper.Map <IEnumerable <GroupModel>, IEnumerable <GroupDto> >(result);

            return(list);
        }
Пример #10
0
        public async Task <SearchResultDto <GroupDto> > GetRootGroups(SearchQueryDto searchEntryDto)
        {
            var searchEntry = _mapper.Map <SearchQueryDto, SearchQueryModel>(searchEntryDto);
            var result      = await _groupRequestService.GetRootGroups(searchEntry);

            var list = _mapper.Map <SearchResultModel <GroupModel>, SearchResultDto <GroupDto> >(result);

            return(list);
        }
Пример #11
0
        /// <summary>
        /// Searches for items.
        /// </summary>
        /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
        /// <param name="searchQueryDto">The query, markets and max results. (optional)</param>
        /// <returns>Task of ApiResponse (List&lt;FoundItem&gt;)</returns>
        public async System.Threading.Tasks.Task <ApiResponse <List <FoundItem> > > SearchAsyncWithHttpInfo(SearchQueryDto searchQueryDto = null)
        {
            var    localVarPath         = "/api/search";
            var    localVarPathParams   = new Dictionary <String, String>();
            var    localVarQueryParams  = new List <KeyValuePair <String, String> >();
            var    localVarHeaderParams = new Dictionary <String, String>(this.Configuration.DefaultHeader);
            var    localVarFormParams   = new Dictionary <String, String>();
            var    localVarFileParams   = new Dictionary <String, FileParameter>();
            Object localVarPostBody     = null;

            // to determine the Content-Type header
            String[] localVarHttpContentTypes = new String[] {
                "application/json"
            };
            String localVarHttpContentType = this.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);

            // to determine the Accept header
            String[] localVarHttpHeaderAccepts = new String[] {
                "application/json"
            };
            String localVarHttpHeaderAccept = this.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);

            if (localVarHttpHeaderAccept != null)
            {
                localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
            }

            if (searchQueryDto != null && searchQueryDto.GetType() != typeof(byte[]))
            {
                localVarPostBody = this.Configuration.ApiClient.Serialize(searchQueryDto); // http body (model) parameter
            }
            else
            {
                localVarPostBody = searchQueryDto; // byte array
            }


            // make the HTTP request
            IRestResponse localVarResponse = (IRestResponse)await this.Configuration.ApiClient.CallApiAsync(localVarPath,
                                                                                                            Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
                                                                                                            localVarPathParams, localVarHttpContentType);

            int localVarStatusCode = (int)localVarResponse.StatusCode;

            if (ExceptionFactory != null)
            {
                Exception exception = ExceptionFactory("Search", localVarResponse);
                if (exception != null)
                {
                    throw exception;
                }
            }

            return(new ApiResponse <List <FoundItem> >(localVarStatusCode,
                                                       localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
                                                       (List <FoundItem>) this.Configuration.ApiClient.Deserialize(localVarResponse, typeof(List <FoundItem>))));
        }
Пример #12
0
 public async Task <IEnumerable <SearchResult> > GetSearchResultsAsync(SearchQueryDto searchQueryDto)
 {
     if (string.IsNullOrEmpty(searchQueryDto.SearchTerm) || string.IsNullOrEmpty(searchQueryDto.CompanyURI))
     {
         return(new List <SearchResult>());
     }
     else
     {
         return(await _provider.GetSearchResultsAsync(searchQueryDto));
     }
 }
Пример #13
0
        private SearchQueryDto GetSearchQueryDto(SearchQuery searchQuery)
        {
            var searchQueryDto = new SearchQueryDto
            {
                QueryId      = searchQuery.QueryId,
                CreationTime = searchQuery.CreationTime,
                Progress     = searchQuery.Progress,
                UserId       = searchQuery.UserId
            };

            return(searchQueryDto);
        }
Пример #14
0
        private SearchResult GetSearchData(SearchQueryDto searchQueryDto)
        {
            var result = new SearchResult
            {
                Id = Guid.NewGuid(),
                SearchEngineName = SearchEngineNames.Bing,
                SearchTerm       = searchQueryDto.SearchTerm,
                PositionResult   = BuildARandomPositionResult()
            };

            return(result);
        }
Пример #15
0
        private static async Task Main(string[] args)
        {
            if (args == null || args.Length == 0)
            {
                Console.WriteLine($"Usage: {nameof(SearcherWebClient)} \"query\" [\"Market1[,Market2[,...]]\" [size]] ");
                return;
            }

            // parse arguments
            var query          = args[0];
            var markets        = args.Length > 1 ? args[1].ParseMarkets().ToList() : null;
            var size           = args.Length > 2 ? ParseSize(args[2]) : (int?)null;
            var searchQueryDto = new SearchQueryDto(query, markets, size);

            // login
            var loginApi    = new LoginApi(BasePath);
            var loginResult = await loginApi.LoginAsync(new UserLoginDto("user", "qwerty"));

            if (!string.IsNullOrEmpty(loginResult.ErrorMessage))
            {
                Console.WriteLine($"Login error: {loginResult.ErrorMessage}");
                return;
            }

            Console.WriteLine($"Login as {loginResult.User.Login} (id={loginResult.User.Id}) is successful");

            // search
            var searchApi = new SearchApi(BasePath)
            {
                Configuration =
                {
                    DefaultHeader = new Dictionary <string, string> {
                        { "Authorization", "Bearer " + loginResult.Token }
                    }
                }
            };
            var foundItems = await searchApi.SearchAsync(searchQueryDto);

            // show results
            foreach (var item in foundItems)
            {
                var sb = new StringBuilder($"{item.Id} ({item.ItemType}): {item.Name}");
                if (!string.IsNullOrEmpty(item.FormerName))
                {
                    sb.Append($" ({item.FormerName})");
                }

                sb.Append($" {item.Address}");
                Console.WriteLine(sb.ToString());
            }
        }
Пример #16
0
        public async void GetSearchResultsHandler_ReturnsNoResult()
        {
            //Arrange
            var searchServiceMock = new Mock <ISearchService>();

            GetSearchResultsHandler handler = new GetSearchResultsHandler(searchServiceMock.Object, _mapper);

            SearchQueryDto        searchQueryDto = new SearchQueryDto();
            GetSearchResultsQuery query          = new GetSearchResultsQuery(searchQueryDto);

            //Act
            var result = await handler.Handle(query, new System.Threading.CancellationToken());

            //Assert
            Assert.Empty(result);
        }
Пример #17
0
        public async Task <ActionResult> Facet(SearchQueryDto dto)
        {
            var facetRequired = new[] { "TargetName", "Application", "Reactivity", "HostSpecies" };
            var searchQuery   = mapper.Map <SearchQuery>(dto);

            searchQuery.PageSize = 0;

            var searchResultModel = await searchService.GetFacets(searchQuery);

            var result = mapper.Map <List <FacetCategoryDto> >(searchResultModel.FacetCategories);

            // TODO this should be handled by the service
            var filteredResult = result
                                 .Where(category => facetRequired.Contains(category.Name));

            return(new JsonResult(filteredResult));
        }
Пример #18
0
        public async void GetSearchResultsHandler_ReturnsNotNullResult()
        {
            //Arrange
            var searchServiceMock = new Mock <ISearchService>();

            searchServiceMock.Setup(a => a.GetSearchResultsAsync(It.IsAny <SearchQueryDto>())).Returns(GetSearchResultsFromFileAsync()).Verifiable();

            GetSearchResultsHandler handler = new GetSearchResultsHandler(searchServiceMock.Object, _mapper);

            SearchQueryDto        searchQueryDto = new SearchQueryDto();
            GetSearchResultsQuery query          = new GetSearchResultsQuery(searchQueryDto);

            //Act
            var result = await handler.Handle(query, new System.Threading.CancellationToken());

            //Assert
            Assert.NotEmpty(result);
        }
Пример #19
0
        public IHttpActionResult SearchLibraryItems([FromUri] SearchQueryModel query)
        {
            var searchQuery = new SearchQueryDto(query);

            var passesWithMinimalData = _passRepository.MinimalDataSearch(
                searchQuery,
                true
                );

            if (passesWithMinimalData.TotalCount > 0)
            {
                return(Ok(passesWithMinimalData));
            }
            else
            {
                return(NotFound());
            }
        }
        public async void GetBingSearchResults_ReturnsNullValue()
        {
            //Arrange
            SearchQueryDto searchQuery = new SearchQueryDto();

            var items = await GetGoogleSearchResultFromFileAsync();

            var distributedCacheMock = new Mock <IDistributedCache>();
            var cacheProviderMock    = new Mock <ISearchResultCacheProvider <SearchResult> >();

            var bingSearchExecutor = new BingSearchExecutor(distributedCacheMock.Object, cacheProviderMock.Object);

            //Act
            var result = await bingSearchExecutor.ExecuteSearchAsync(searchQuery);

            //Assert
            Assert.Null(result);
        }
Пример #21
0
        public SearchResultModel <PassDigestListItem> MinimalDataSearch(
            SearchQueryDto queryModel,
            bool isLibraried)
        {
            List <PassDigestListItem> allRecords = _dbContext.Query <PassEntity>()
                                                   .Where(p => p.IsLibraried.HasValue && p.IsLibraried.Value == isLibraried)
                                                   .ProjectTo <PassDigestListItem>(_mapper.ConfigurationProvider)
                                                   .ToList();

            if (!string.IsNullOrWhiteSpace(queryModel.Title))
            {
                allRecords.RemoveAll(x => DoesNotContainTitle(queryModel.Title, x.Name));
            }

            IOrderedEnumerable <PassDigestListItem> orderQuery =
                queryModel.OrderDirection == OrderDirection.Desc
                   ? allRecords.OrderByDescending(OrderByProperty(queryModel.OrderBy))
                   : allRecords.OrderBy(OrderByProperty(queryModel.OrderBy));

            var searchResults = new SearchResultModel <PassDigestListItem>();

            searchResults.Items = orderQuery
                                  .Skip(queryModel.Skip)
                                  .Take(queryModel.Top)
                                  .ToList();
            searchResults.TotalCount = orderQuery.Count();

            return(searchResults);

            Func <PassDigestListItem, object> OrderByProperty(OrderBy orderBy)
            {
                if (OrderBy.Date == orderBy)
                {
                    return(x => x.DateModified);
                }
                else
                {
                    return(x => x.Name);
                }
            }

            bool DoesNotContainTitle(string title, string passDigestName) =>
            passDigestName.IndexOf(title, StringComparison.CurrentCultureIgnoreCase) < 0;
        }
Пример #22
0
        public async Task <ActionResult> Product(SearchQueryDto dto, [FromQuery] int size = 0, [FromQuery] int page = 1)
        {
            var searchQuery = mapper.Map <SearchQuery>(dto);

            // TODO refactor and protect load on search server
            searchQuery.PageSize   = size;
            searchQuery.PageNumber = page;
            // TODO remove this workaround
            if (size == 0)
            {
                searchQuery.PageSize = 100000;
            }

            var searchResultModel = await searchService.GetProducts(searchQuery);

            var result = mapper.Map <ProductsDto>(searchResultModel);

            return(new JsonResult(result));
        }
        public async void GetBingSearchResults_ReturnsValue()
        {
            //Arrange
            SearchQueryDto searchQuery = new SearchQueryDto();

            var items = await GetGoogleSearchResultFromFileAsync();

            var distributedCacheMock = new Mock <IDistributedCache>();
            var cacheProviderMock    = new Mock <ISearchResultCacheProvider <SearchResult> >();

            cacheProviderMock.Setup(m => m.GetOrCreate(It.IsAny <string>(), It.IsAny <Func <SearchResult> >())).Returns(Task.FromResult(items));

            var bingSearchExecutor = new BingSearchExecutor(distributedCacheMock.Object, cacheProviderMock.Object);

            //Act
            var result = await bingSearchExecutor.ExecuteSearchAsync(searchQuery);

            //Assert
            Assert.NotNull(result);
        }
Пример #24
0
        /// <summary>
        /// Searches for items.
        /// </summary>
        /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
        /// <param name="searchQueryDto">The query, markets and max results. (optional)</param>
        /// <returns>Task of List&lt;FoundItem&gt;</returns>
        public async System.Threading.Tasks.Task <List <FoundItem> > SearchAsync(SearchQueryDto searchQueryDto = null)
        {
            ApiResponse <List <FoundItem> > localVarResponse = await SearchAsyncWithHttpInfo(searchQueryDto);

            return(localVarResponse.Data);
        }
Пример #25
0
        public async Task <ActionResult <IEnumerable <SearchResultDto> > > GetSearchResults([FromQuery] SearchQueryDto searchQueryDto)
        {
            var query  = new GetSearchResultsQuery(searchQueryDto);
            var result = await _mediator.Send(query);

            return(Ok(result));
        }
        public async Task <SearchResultDto <MemberDto> > GetMembersAsync(string groupId, SearchQueryDto searchEntryDto)
        {
            var searchEntry = _mapper.Map <SearchQueryDto, SearchQueryModel>(searchEntryDto);
            var result      = await _groupMemberRequestService.GetMembers(groupId, searchEntry);

            var list = _mapper.Map <SearchResultModel <MemberModel>, SearchResultDto <MemberDto> >(result);

            return(list);
        }
 public GetSearchResultsQuery(SearchQueryDto searchQueryDto)
 {
     _searchQueryDto = searchQueryDto;
 }
Пример #28
0
        public IHttpActionResult SearchLibraryItems([FromUri] SearchQueryModel query)
        {
            var searchQuery = new SearchQueryDto(query);

            IEnumerable <PassDigestListItem> passesContainingTitleFromQuery = new List <PassDigestListItem>();

            if (!string.IsNullOrEmpty(searchQuery.Title))
            {
                var passesSearchQuery = new SearchQueryDto(new SearchQueryModel()
                {
                    OrderBy        = query.OrderBy,
                    OrderDirection = query.OrderDirection,
                    Title          = query.Title,
                    Top            = int.MaxValue,
                    Skip           = 0
                });

                passesContainingTitleFromQuery = _passRepository.MinimalDataSearch(passesSearchQuery, false)
                                                 .Items
                                                 .Where(p =>
                                                        p.Name.IndexOf(searchQuery.Title, StringComparison.CurrentCultureIgnoreCase) >= 0
                                                        );
            }

            var scenariosWithMinimalData = _scenarioRepository.MinimalDataSearch(
                searchQuery,
                true,
                passesContainingTitleFromQuery
                .Select(p => p.Id)
                );

            if (scenariosWithMinimalData.TotalCount > 0)
            {
                var defaultScenarioId = _tenantSettingsRepository.GetDefaultScenarioId();
                var defaultScenario   = scenariosWithMinimalData.Items.FirstOrDefault(c => c.Id == defaultScenarioId);

                if (defaultScenario != null)
                {
                    defaultScenario.IsDefault = true;
                }

                var extractedPasses = ExtractMinimalPassesFromScenarios(scenariosWithMinimalData)
                                      .ToList();

                var passesFromDb = _passRepository.FindByIds(extractedPasses.Select(pass => pass.Id))
                                   .Select(p => (p.Id, p.Name, p.DateModified))
                                   .ToDictionary(p => p.Id);

                List <int> passIdsToRemove = new List <int>();
                UpdatePassesWithMinimalData(extractedPasses, passesFromDb, passIdsToRemove);

                RemoveDeletedPasses(scenariosWithMinimalData, passIdsToRemove);

                var minimalDataSearchResult = _mapper.Map <SearchResultModel <ScenarioDigestListItemModel> >(scenariosWithMinimalData);

                return(Ok(minimalDataSearchResult));
            }
            else
            {
                return(NotFound());
            }

            void UpdatePassesWithMinimalData(
                List <PassDigestListItem> passesWithMinimalData,
                Dictionary <int, (int Id, string Name, DateTime?DateModified)> passesFromDb,
                List <int> passIdsToRemove)
            {
                passesWithMinimalData.ForEach(minimalDataPass =>
                {
                    var pass = passesFromDb.FirstOrDefault(pass => pass.Key == minimalDataPass.Id).Value;

                    if (pass.Id == minimalDataPass.Id)
                    {
                        minimalDataPass.DateModified = pass.DateModified.Value;
                        minimalDataPass.Name         = pass.Name;
                    }
                    else
                    {
                        passIdsToRemove.Add(minimalDataPass.Id);
                    }
                });
            }

            void RemoveDeletedPasses(SearchResultModel <ScenarioDigestListItem> scenariosWithMinimalData, List <int> passIdsToRemove)
            {
                passIdsToRemove.ForEach(id =>
                {
                    scenariosWithMinimalData.Items.ForEach(scenario =>
                    {
                        var passToRemove = scenario.Passes.Find(p => p.Id == id);
                        if (passToRemove != null)
                        {
                            scenario.Passes.Remove(passToRemove);
                        }
                    });
                });
            }

            IEnumerable <PassDigestListItem> ExtractMinimalPassesFromScenarios(SearchResultModel <ScenarioDigestListItem> searchScenarios)
            {
                var passes = new List <PassDigestListItem>();

                foreach (var scenario in searchScenarios.Items)
                {
                    passes.AddRange(scenario.Passes);
                }

                return(passes);
            }
        }
        public async Task <IActionResult> GetRootGroups([FromBody] SearchQueryDto searchEntry)
        {
            var result = await _groupService.GetRootGroups(searchEntry);

            return(Ok(result));
        }
        public async Task <IActionResult> GetSubgroupList([FromBody] SearchQueryDto searchEntry, string id)
        {
            var result = await _groupService.GetSubgroups(searchEntry, id);

            return(Ok(result));
        }