Exemple #1
0
        public async Task <List <SearchResult> > GetSearchResultsAsync(string query)
        {
            if (string.IsNullOrEmpty(query))
            {
                return(null);
            }

            bool googleSearchEnabled;
            bool bingSearchEnabled;

            try
            {
                googleSearchEnabled = bool.Parse(ConfigurationManager.AppSettings["GoogleSearchEnabled"]);
                bingSearchEnabled   = bool.Parse(ConfigurationManager.AppSettings["BingSearchEnabled"]);
            }
            catch (Exception)
            {
                return(null);
            }

            var searchTasks = new List <Task <List <SearchResult> > >();

            var registerTask = new Action <bool, ISearcher>(
                (flag, searcher) =>
            {
                if (flag && searcher != null)
                {
                    searchTasks.Add(searcher.GetSearchResultsAsync(query));
                }
            });

            ISearcher googleSearcher = _searcherFactory.CreateGoogleSearcher();
            ISearcher bingSearcher   = _searcherFactory.CreateBingSearcher();

            registerTask(googleSearchEnabled, googleSearcher);
            registerTask(bingSearchEnabled, bingSearcher);

            Task <List <SearchResult> > firstExecutedTask;

            try
            {
                firstExecutedTask = await Task.WhenAny(searchTasks);
            }
            catch (ArgumentException)
            {
                return(null);
            }

            List <SearchResult> searchResults = await firstExecutedTask;

            if (searchResults?.Count() != 0)
            {
                _searchRepository.AddSearchResults(searchResults, query);
            }

            return(searchResults);
        }