コード例 #1
0
        public async Task <List <Song> > GetSongs(string searchQuery)
        {
            try
            {
                var            http   = new HttpClient();
                IConfiguration config = new ConfigurationBuilder()
                                        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                                        .AddEnvironmentVariables()
                                        .Build();
                var accounts = new AccountsService(http, config);

                var search        = new SearchApi(http, accounts);
                var searchResults = await search.Search(searchQuery, "track", "");

                var songList = new List <Song>();
                foreach (var result in searchResults.Tracks.Items)
                {
                    songList.Add(new Song()
                    {
                        Artist             = result.Artists[0].Name,
                        Name               = result.Name,
                        ServiceAvailableOn = Enums.StreamingServiceTypes.Spotify,
                        ServiceId          = result.Uri,
                    });
                }

                return(songList);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
コード例 #2
0
        public async Task <SearchResult> FindContents(string access, string request)
        {
            var api    = new SearchApi();
            var result = await api.FindContentsAsync(access, request);

            return(result);
        }
コード例 #3
0
 public static object searchArticles(string keyword, int pageNumber)
 {
     return(new ThunkAction <AppState>((dispatcher, getState) => {
         return SearchApi.SearchArticle(keyword, pageNumber)
         .Then(searchResponse => {
             dispatcher.dispatch(new UserMapAction {
                 userMap = searchResponse.userMap
             });
             dispatcher.dispatch(new TeamMapAction {
                 teamMap = searchResponse.teamMap
             });
             dispatcher.dispatch(new SearchArticleSuccessAction {
                 keyword = keyword,
                 pageNumber = pageNumber,
                 searchResponse = searchResponse
             });
         })
         .Catch(error => {
             dispatcher.dispatch(new SearchArticleFailureAction {
                 keyword = keyword
             });
             Debug.Log(error);
         });
     }));
 }
        public SearchApiController(ILogger <SearchApiController> logger)
        {
            _logger = logger;
            var invertedIndex = SearchApi.InitializeInvertedIndex();

            searchEngine = new SearchEngine(invertedIndex);
        }
コード例 #5
0
 public static object searchArticles(string keyword, int pageNumber)
 {
     return(new ThunkAction <AppState>((dispatcher, getState) => {
         return SearchApi.SearchArticle(keyword, pageNumber)
         .Then(searchArticleResponse => {
             dispatcher.dispatch(new UserMapAction {
                 userMap = searchArticleResponse.userMap
             });
             dispatcher.dispatch(new TeamMapAction {
                 teamMap = searchArticleResponse.teamMap
             });
             dispatcher.dispatch(new PlaceMapAction {
                 placeMap = searchArticleResponse.placeMap
             });
             dispatcher.dispatch(new LikeMapAction {
                 likeMap = searchArticleResponse.likeMap
             });
             dispatcher.dispatch(new SearchArticleSuccessAction {
                 keyword = keyword,
                 pageNumber = pageNumber,
                 searchArticles = searchArticleResponse.projects,
                 currentPage = searchArticleResponse.currentPage,
                 pages = searchArticleResponse.pages
             });
         })
         .Catch(error => {
             dispatcher.dispatch(new SearchArticleFailureAction {
                 keyword = keyword
             });
             Debuger.LogError(message: error);
         });
     }));
 }
コード例 #6
0
        public async Task TvShow()
        {
            var httpClient = HttpClientMockFactory.CreateClient(new HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.OK,
                Content    = new StringContent(JsonConvert.SerializeObject(allTvShowProperties))
            });

            var search = new SearchApi("", httpClient);

            var result = await search.TvShowAsync("Game of thrones");

            result.ShouldNotBeNull();
            result.Results.ShouldNotBeNull();
            result.Results.Count.ShouldBe(allTvShowProperties.Results.Length);

            for (var index = 0; index < result.Results.Count; index++)
            {
                var tvShow         = result.Results[index];
                var expectedTvShow = MediaFactory.Create <TvShow>(
                    allTvShowProperties.Results[index]);

                tvShow.ShouldBe(expectedTvShow);
            }
        }
コード例 #7
0
ファイル: InvalidProperties.cs プロジェクト: chandlli/TMDBNet
        public async Task Movie_Null()
        {
            var httpClient = HttpClientMockFactory.CreateClient(new HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.OK,
                Content    = new StringContent(JsonConvert.SerializeObject(nullProperties))
            });

            var search = new SearchApi("", httpClient);

            var result = await search.MovieAsync("avengers");

            result.ShouldNotBeNull();
            result.Results.ShouldNotBeNull();
            result.Results.Count.ShouldBe(nullProperties.Results.Length);

            for (var index = 0; index < result.Results.Count; index++)
            {
                var movie         = result.Results[index];
                var expectedMovie = SearchResultItemFactory.Create <Movie>(
                    nullProperties.Results[index]);

                movie.ShouldBe(expectedMovie);
            }
        }
コード例 #8
0
        public async Task <TopicsResult> FindTopicsAsync(string access, string request)
        {
            var api    = new SearchApi();
            var result = await api.FindTopicsAsync(access, request);

            return(result);
        }
コード例 #9
0
        public async Task <QuestionsResult> FindQuestionsAsync(String access, String request)
        {
            var api    = new SearchApi();
            var result = await api.FindQuestionsAsync(access, request);

            return(result);
        }
コード例 #10
0
        public async Task <Song> GetSong(string searchQuery)
        {
            try
            {
                var            http   = new HttpClient();
                IConfiguration config = new ConfigurationBuilder()
                                        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                                        .AddEnvironmentVariables()
                                        .Build();
                var accounts = new AccountsService(http, config);

                var search       = new SearchApi(http, accounts);
                var searchResult = await search.Search(searchQuery, "track", "", (1, 0));

                var song = new Song()
                {
                    Artist             = searchResult?.Tracks?.Items[0].Artists[0].Name,
                    Name               = searchResult?.Tracks?.Items[0].Name,
                    ServiceAvailableOn = Enums.StreamingServiceTypes.Spotify,
                    SpotifyId          = searchResult?.Tracks.Items[0].Uri,
                };

                return(song);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
コード例 #11
0
        public async Task <AuthorsResult> FindPeople(string access, string keyword)
        {
            var api    = new SearchApi();
            var result = await api.FindPeopleAsync(access, keyword);

            return(result);
        }
コード例 #12
0
 /// <summary>
 ///  Search for accounts.
 /// </summary>
 /// <exception cref="Algorand.Client.ApiException">Thrown when fails to make API call</exception>
 /// <param name="assetId">Asset ID (optional)</param>
 /// <param name="limit">Maximum number of results to return. (optional)</param>
 /// <param name="next">The next page of results. Use the next token provided by the previous results. (optional)</param>
 /// <param name="currencyGreaterThan">Results should have an amount greater than this value. MicroAlgos are the default currency unless an asset-id is provided, in which case the asset will be used. (optional)</param>
 /// <param name="currencyLessThan">Results should have an amount less than this value. MicroAlgos are the default currency unless an asset-id is provided, in which case the asset will be used. (optional)</param>
 /// <param name="authAddr">Include accounts configured to use this spending key. (optional)</param>
 /// <param name="round">Include results for the specified round. For performance reasons, this parameter may be disabled on some configurations. (optional)</param>
 /// <param name="applicationId">Application ID (optional)</param>
 /// <returns>AccountsResponse</returns>
 public AccountsResponse SearchForAccounts(long?assetId = null, long?limit = null, string next = null, long?currencyGreaterThan = null, long?currencyLessThan = null, string authAddr = null, long?round = null, long?applicationId = null)
 {
     if (_searchapi is null)
     {
         _searchapi = new SearchApi(_config);
     }
     return(_searchapi.SearchForAccounts(assetId, limit, next, currencyGreaterThan, currencyLessThan, authAddr, round, applicationId));
 }
コード例 #13
0
        public ActionResult Search(string search)
        {
            SearchApi           api   = new SearchApi();
            List <SearchResult> books = api.searchData(search);

            ViewBag.searchData = search;
            return(View(books));
        }
コード例 #14
0
 /// <summary>
 ///  Search for assets.
 /// </summary>
 /// <exception cref="Algorand.Client.ApiException">Thrown when fails to make API call</exception>
 /// <param name="limit">Maximum number of results to return. (optional)</param>
 /// <param name="next">The next page of results. Use the next token provided by the previous results. (optional)</param>
 /// <param name="creator">Filter just assets with the given creator address. (optional)</param>
 /// <param name="name">Filter just assets with the given name. (optional)</param>
 /// <param name="unit">Filter just assets with the given unit. (optional)</param>
 /// <param name="assetId">Asset ID (optional)</param>
 /// <returns>AssetsResponse</returns>
 public AssetsResponse SearchForAssets(long?limit = null, string next = null, string creator = null, string name = null, string unit = null, long?assetId = null)
 {
     if (_searchapi is null)
     {
         _searchapi = new SearchApi(_config);
     }
     return(_searchapi.SearchForAssets(limit, next, creator, name, unit, assetId));
 }
コード例 #15
0
 /// <summary>
 ///  Search for transactions.
 /// </summary>
 /// <exception cref="Algorand.Client.ApiException">Thrown when fails to make API call</exception>
 /// <param name="limit">Maximum number of results to return. (optional)</param>
 /// <param name="next">The next page of results. Use the next token provided by the previous results. (optional)</param>
 /// <param name="notePrefix">Specifies a prefix which must be contained in the note field. (optional)</param>
 /// <param name="txType"> (optional)</param>
 /// <param name="sigType">SigType filters just results using the specified type of signature: * sig - Standard * msig - MultiSig * lsig - LogicSig (optional)</param>
 /// <param name="txid">Lookup the specific transaction by ID. (optional)</param>
 /// <param name="round">Include results for the specified round. (optional)</param>
 /// <param name="minRound">Include results at or after the specified min-round. (optional)</param>
 /// <param name="maxRound">Include results at or before the specified max-round. (optional)</param>
 /// <param name="assetId">Asset ID (optional)</param>
 /// <param name="beforeTime">Include results before the given time. Must be an RFC 3339 formatted string. (optional)</param>
 /// <param name="afterTime">Include results after the given time. Must be an RFC 3339 formatted string. (optional)</param>
 /// <param name="currencyGreaterThan">Results should have an amount greater than this value. MicroAlgos are the default currency unless an asset-id is provided, in which case the asset will be used. (optional)</param>
 /// <param name="currencyLessThan">Results should have an amount less than this value. MicroAlgos are the default currency unless an asset-id is provided, in which case the asset will be used. (optional)</param>
 /// <param name="address">Only include transactions with this address in one of the transaction fields. (optional)</param>
 /// <param name="addressRole">Combine with the address parameter to define what type of address to search for. (optional)</param>
 /// <param name="excludeCloseTo">Combine with address and address-role parameters to define what type of address to search for. The close to fields are normally treated as a receiver, if you would like to exclude them set this parameter to true. (optional)</param>
 /// <param name="rekeyTo">Include results which include the rekey-to field. (optional)</param>
 /// <param name="applicationId">Application ID (optional)</param>
 /// <returns>TransactionsResponse</returns>
 public TransactionsResponse SearchForTransactions(long?limit = null, string next = null, string notePrefix = null, string txType = null, string sigType = null, string txid = null, long?round = null, long?minRound = null, long?maxRound = null, long?assetId = null, DateTime?beforeTime = null, DateTime?afterTime = null, long?currencyGreaterThan = null, long?currencyLessThan = null, string address = null, string addressRole = null, bool?excludeCloseTo = null, bool?rekeyTo = null, long?applicationId = null)
 {
     if (_searchapi is null)
     {
         _searchapi = new SearchApi(_config);
     }
     return(_searchapi.SearchForTransactions(limit, next, notePrefix, txType, sigType, txid, round, minRound, maxRound, assetId, beforeTime, afterTime, currencyGreaterThan, currencyLessThan, address, addressRole, excludeCloseTo, rekeyTo, applicationId));
 }
コード例 #16
0
 /// <summary>
 ///  Search for applications
 /// </summary>
 /// <exception cref="Algorand.Client.ApiException">Thrown when fails to make API call</exception>
 /// <param name="applicationId">Application ID (optional)</param>
 /// <param name="limit">Maximum number of results to return. (optional)</param>
 /// <param name="next">The next page of results. Use the next token provided by the previous results. (optional)</param>
 /// <returns>ApplicationsResponse</returns>
 public ApplicationsResponse SearchForApplications(long?applicationId = null, long?limit = null, string next = null)
 {
     if (_searchapi is null)
     {
         _searchapi = new SearchApi(_config);
     }
     return(_searchapi.SearchForApplications(applicationId, limit, next));
 }
コード例 #17
0
 public GitHubApiRateLimits ToGitHubApiRateLimits()
 {
     return(new GitHubApiRateLimits(RestApi?.ToRateLimitStatus() ?? throw new NullReferenceException(),
                                    SearchApi?.ToRateLimitStatus() ?? throw new NullReferenceException(),
                                    GraphQLApi?.ToRateLimitStatus() ?? throw new NullReferenceException(),
                                    SourceImport?.ToRateLimitStatus() ?? throw new NullReferenceException(),
                                    AppManifestConfiguration?.ToRateLimitStatus() ?? throw new NullReferenceException(),
                                    CodeScanningUpload?.ToRateLimitStatus() ?? throw new NullReferenceException()));
 }
コード例 #18
0
        public void SearchApiIsCalled()
        {
            var parameter = new Dictionary <string, string> {
                { "q", _searchTerm }, { "lang", "en-GB" }, { "currency", "GBP" }, { "store", "1" }
            };

            _searchResult   = SearchApi.SendRequest(parameter, HttpMethod.Get);
            _resultAsString = SearchApi.ReadContentAsString(_searchResult);
        }
コード例 #19
0
ファイル: SearchApiTests.cs プロジェクト: denis-peshkov/slack
        public void SearchMessagesShouldCallCorrectEndpoint()
        {
            var requestHandlerMock = PathAndExecRequestMock <SearchResponse>("/search.messages?query=foo");

            var subject = new SearchApi(requestHandlerMock.Object);
            var result  = subject.Messages(queryString: "foo");

            requestHandlerMock.Verify();
            Assert.NotNull(result);
        }
コード例 #20
0
        public void InMemorySearch_KeywordWithOnlyLastName_ReturnsError_NotingFirstNameIsMandatory(WireDataFormat format)
        {
            var client       = TestContext.CreateClientNoCredentials(format);
            var searchClient = new SearchApi(client.HttpChannel);

            var exception = Assert.Throws <ErrorResponseException>(() => searchClient.InMemorySearch(null, null, "Morrison", null));

            Assert.That(exception.Errors.Count, Is.EqualTo(1));
            Assert.That(exception.Errors[0].Id, Is.EqualTo("InvalidFirstName"));
            Assert.That(exception.Errors[0].Description, Is.EqualTo("The first name of the person you're remembering cannot be empty."));
        }
コード例 #21
0
 protected void Application_End()
 {
     if (ConfigurationManager.AppSettings["IsNode"] == "1")
     {
         SearchApi.Dispose();
     }
     else
     {
         logdb.Dispose();
     }
 }
コード例 #22
0
 public static object popularSearchUser()
 {
     return(new ThunkAction <AppState>((dispatcher, getState) => {
         return SearchApi.PopularSearchUser()
         .Then(popularSearchUsers => {
             dispatcher.dispatch(new PopularSearchUserSuccessAction {
                 popularSearchUsers = popularSearchUsers
             });
         })
         .Catch(onRejected: Debuger.LogError);
     }));
 }
コード例 #23
0
        public void FundraiserSearch_KeywordWithKnownResult_SearchResultPresent(WireDataFormat format)
        {
            //arrange
            var client          = TestContext.CreateClientNoCredentials(format);
            var searchResources = new SearchApi(client.HttpChannel);

            //act
            var result = searchResources.FundraiserSearch("pawel");

            //assert
            Assert.IsTrue(result.SearchResults.Any());
        }
コード例 #24
0
 public static object popularSearch()
 {
     return(new ThunkAction <AppState>((dispatcher, getState) => {
         return SearchApi.PopularSearch()
         .Then(popularSearch => {
             dispatcher.dispatch(new PopularSearchSuccessAction {
                 popularSearch = popularSearch
             });
         })
         .Catch(error => { Debug.Log(error); });
     }));
 }
コード例 #25
0
        public void InMemorySearch_KeywordWithKnownResults_SearchResultsPresent(WireDataFormat format)
        {
            //arrange
            var client       = TestContext.CreateClientNoCredentials(format);
            var searchClient = new SearchApi(client.HttpChannel);

            //act
            var items = searchClient.InMemorySearch(null, "test", "test", null);

            //assert
            Assert.IsTrue(items.Results.Any());
        }
コード例 #26
0
 public static object popularSearchUser()
 {
     return(new ThunkAction <AppState>((dispatcher, getState) => {
         return SearchApi.PopularSearchUser()
         .Then(popularSearchUsers => {
             dispatcher.dispatch(new PopularSearchUserSuccessAction {
                 popularSearchUsers = popularSearchUsers
             });
         })
         .Catch(error => Debug.Log($"{error}"));
     }));
 }
コード例 #27
0
ファイル: Program.cs プロジェクト: cbelyaev/search-assessment
        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());
            }
        }
コード例 #28
0
ファイル: Function.cs プロジェクト: brett005/TEDStats-cli
        public static async Task <string> GetStats(string query, string from, string to)
        {
            var api = new SearchApi();

            var full_query = String.Format("({0}) AND PD=[{1} <> {2}]", query, from.Replace("-", ""), to.Replace("-", ""));
            var request    = new SearchRequest(full_query)
            {
                Scope  = SearchScope.All,
                Fields = new List <Fields>()
                {
                    Fields.PublicationDate, Fields.EditionNumber
                },
                PageSize = 1
            };

            System.Console.WriteLine(request.ToJson());

            var results = new List <NoticeResult>();

            // One request to get the total number of results
            var res = await api.Search(request);

            System.Console.WriteLine("Results count: " + res.Total);

            request.PageSize = 100;
            int last_page = (int)Math.Ceiling((double)res.Total / request.PageSize);

            for (int i = 1; i < last_page + 1; i++)
            {
                request.PageNum = i;
                res             = await api.Search(request);

                results.AddRange(res.Results);
            }

            var records = results.GroupBy(r => new Projection(r))
                          .Select(gr => new { Key = gr.Key, Count = gr.Count() })
                          .OrderBy(gr => gr.Key);

            using (var writer = new StringWriter())
                using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
                {
                    var options = new TypeConverterOptions {
                        Formats = new[] { "yyyy-MM-dd" }
                    };
                    csv.Configuration.TypeConverterOptionsCache.AddOptions <DateTime>(options);
                    csv.WriteRecords(records);

                    return(writer.ToString());
                }
        }
コード例 #29
0
        public void SearchWithoutVariables()
        {
            var searchApi = new SearchApi("http://localhost:9800");

            var query = new SearchQuery()
            {
                IndexName = "country",
                QueryName = "agrisearch"
            };

            var response = searchApi.Search("country", query);

            InterpretResponse(response);
        }
コード例 #30
0
        public void Search()
        {
            var searchApi = new SearchApi("http://localhost:9800");

            var queryString = "gt(population, '100000000') AND allOf(countryname, 'United')";
            var query       = new SearchQuery("country", queryString)
            {
                Columns = new string[] { "*" }
            };

            var response = searchApi.Search("country", query);

            InterpretResponse(response);
        }