Integrate Search Function to Your App using Bing Search API

Search function may be essential when you are looking for meaningful information. But often, people will ask, “how can we create a good search engine or algorithm by ourselves?”, “It may be too complicated?”. Why don’t we just use the well-known search engine, like Bing and its intelligent algorithm to integrate into our app? That will be so much easier!

Today, we will learn how to develop our app to consume Bing Search API, the engine behind Bing search!

Pre-requisites

Let’s Start!

  1. First, we need to obtain the API key for Bing Search APIs v7. To learn how to get one, click here.
    IntegrateSearchFunctionToYourApp
  2. Secondly, we need to create a Xamarin Cross Platform Mobile App. Don’t have one yet? Click to learn how to create one!
  3. Thirdly, we need to add a NuGet Packages – Newtonsoft.Json, right click Solution in the Solution Explorer -> Manage NuGet Packages for Solution…
    IntegrateSearchFunctionToYourApp
  4. Let’s search Newtonsoft.Json and install it to all the projects.
    IntegrateSearchFunctionToYourApp
  5. Now, we need to add some Search Bar components to MainPage.xaml as specified below.
    IntegrateSearchFunctionToYourApp
  6. Down below the Grid component, let’s add a list view to show the returned search result.
    IntegrateSearchFunctionToYourApp
  7. Create a folder named Models. We will create few classes under this folder later.
    IntegrateSearchFunctionToYourApp
  8. Right Click “Models” folder -> Add -> select Class from the list. Name the new class as SearchTagObj.cs.
    IntegrateSearchFunctionToYourApp
  9. Create two variables for SearchTagsObj class as below.
    public class SearchTagsObj
    {
         public string name { get; set; }
         public string content { get; set; }
    }
  10. We need to create another new class and name it as WebResultsList.cs.
    IntegrateSearchFunctionToYourApp
  11. Make sure you have the following variables for WebResultsList class.
    public class WebResultsList
    {
        public string name { get; set; }
        public string webSearchUrl { get; set; }
        public uint totalEstimatedMatches { get; set; }
        public ObservableCollection<WebValueObject> value { get; set; }
        public bool someResultsRemoved { get; set; }
    }
  12. Create another new class and name it as WebValueObject.cs.
    IntegrateSearchFunctionToYourApp
  13. Moving on, create the following variables for WebValueObject class.
    public class WebValueObject
    {
       public string id { get; set; }
       public string name { get; set; }
       public string url { get; set; }
       public string displayUrl { get; set; }
       public string snippet { get; set; }
       public string dateLastCrawled { get; set; }
       public List<SearchTagsObj> searchTags { get; set; }
    }
  14. Next, create another class under .Core project, name it as AppConstants.cs and add three variables as shown below.
    public class AppConstants
    {
       public const string OcpApimSubscriptionKey = "Ocp-Apim-Subscription-Key";
       public const string BingWebSearchApiUrl = "https://api.cognitive.microsoft.com/bing/v7.0/search?";
       public static string BingWebSearchApiKey = "<YOUR_API_KEY_HERE>";
    }
  15. Now, head to MainPage.xaml.cs, we need to declare few variables.
    ObservableCollection<WebValueObject> values;
    string queryTerm;
    HttpClient searchApiClient;
  16. Then, in the MainPage constructor, add click event handler for btnSearch & HttpClient to call WebApi later.
    public MainPage()
    {
       InitializeComponent();
       btnSearch.Clicked += BtnSearch_Clicked;
       searchApiClient = new HttpClient();
       searchApiClient.DefaultRequestHeaders.Add(AppConstants.OcpApimSubscriptionKey, AppConstants.BingWebSearchApiKey);
    } 
    private async void BtnSearch_Clicked(object sender, EventArgs e)
    {
       this.queryTerm = txtKeyword.Text;
       await LoadData();
    }
  17. Let’s create LoadData function with following codes.
    protected async Task LoadData()
    {
       LoadingIndicator.IsVisible = true;
       LoadingIndicator.IsRunning = true;
       // Try loading the results, show error message if necessary.
       WebResultsList webResults = null;
       Boolean error = false;
       try
       {
          webResults = await GetQueryResults();
       }
       catch
       {
          error = true;
       }
    
       // Hide the spinner, show the table
       LoadingIndicator.IsVisible = false;
       LoadingIndicator.IsRunning = false;
       DataTable.IsVisible = true;
    
       if (error)
       {
          await ErrorAndPop("Error", "Error fetching results", "OK");
       }
       else if (webResults?.totalEstimatedMatches > 0)
       {
          values = webResults.value;
          DataTable.ItemsSource = values;
       }
       else
       {
          await ErrorAndPop("Error", "No results found", "OK");
       }
    }
  18. After that, create ErrorAndPop function with following codes.
    protected async Task ErrorAndPop(string title, string text, string button)
    {
       await DisplayAlert(title, text, button);
       Console.WriteLine($"ERROR: {text}");
       await Task.Delay(TimeSpan.FromSeconds(0.1d));
       await Navigation.PopAsync(true);
    }
  19. Followed by, create an asynchronous function GetQueryResults() to call the Bing Search API and returned the search results.
    async Task<WebResultsList> GetQueryResults()
    {
       string uri = AppConstants.BingWebSearchApiUrl + $"count=20&mkt=en-US&q={queryString}&responseFilter=Webpages&setLang=en";
       // Make the HTTP Request
       WebResultsList webResults = null;
       HttpResponseMessage httpResponseMessage = await searchApiClient.GetAsync(uri);
       var responseContentString = await httpResponseMessage.Content.ReadAsStringAsync();
       JObject json = JObject.Parse(responseContentString);
       JToken resultBlock = json.SelectToken("$.webPages");
       if (resultBlock != null)
       {
          webResults = JsonConvert.DeserializeObject<WebResultsList>(resultBlock.ToString());
       }
       return webResults;
    }
  20. Last but not least, create an event handler – ItemSelectedEventHandler for showing the selected web result when user clicked the result item.
    async void ItemSelectedEventHandler(object sender, SelectedItemChangedEventArgs e)
    {
        if (e.SelectedItem == null) { return; }
        WebView webView = new WebView
        {
           Source = new UrlWebViewSource { Url = ((WebValueObject)e.SelectedItem).url },
           VerticalOptions = LayoutOptions.FillAndExpand
        };
    
        await Navigation.PushAsync(new ContentPage
        {
            Content = webView,
            Title = ((WebValueObject)e.SelectedItem).name
        });
        ((ListView)sender).SelectedItem = null;
    }
  21. Let’s compile and run it on your mobile device. Try to see what would happen when enter some keywords to search!
    IntegrateSearchFunctionToYourApp

IntegrateSearchFunctionToYourApp

Get your Sample Source Code  & Offline Slide for Learning too.

Don’t forget to follow me @
Twitter: @hmheng
More slides @ SlideShare: https://www.slideshare.net/HiangMengHengMarvin
Blog: http://hmheng.pinsland.com

You may also like...

1 Response

  1. June 21, 2018

    […] Search Application with Bing Search API […]

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: