Building Xamarin Mobile Application With Bing Web Search Using Cognitive Services

Introduction

 
The Bing Web Search API provides an experience similar to Bing.com/Search by returning search results that Bing determines are relevant to the user's query. The API results include Web pages, images, videos, news, and entities, along with related search queries, spelling corrections, time zones, unit conversion, translations, and calculations. The web Search API uses JSON format for data exchange and API Keys for authentication.
 
Cognitive Services
 
In this article, I will show how to generate the Bing Search subscription key and integrate it into the Xamarin application.
 
Register Bing Search on Azure Portal
 
You need to create an Azure account and generate a subscription key for implementation to the Xamarin Mobile application.
 
Step 1
 
Sign in to the Azure portal.
 
Step 2
 
Create On “+ Create a resource “> Under Azure Marketplace, select AI + Cognitive Services, and discover the list of available APIs. > Select “ Bing Search v7 APIs”
 
Cognitive Services
 
Step 3
 
On the create page, provide the name, pricing, resource group and click on Create
 
Cognitive Services
 
Step 4
 
Wait for a few seconds. After the Cognitive Services account is successfully deployed, click the notification or tile in the dashboard to view the account information. You can copy the Endpoint URL in the Overview section and keys in the Keys section to start making API calls in our Xamarin applications.
 
Cognitive Services
 
Create a Bing Web Search Xamarin Application
 
Let's start with creating a new Xamarin Forms Project using Visual Studio. Open Run >> Type “Devenev.Exe” and enter >> New Project (Ctrl+Shift+N) >> select Blank XAML App (Xamarin.Forms) template.
 
Cognitive Services
 
It will automatically create multiple projects, like .NET Standard, Android, iOS, and UWP.
 
Install Newtonsoft.Json
 
Bing Web Search API will return JSON object value so make sure you have added the Newtonsoft JSON NuGet Package to your all project. Right Click on Solution > Manage Nuget Package > Install Newtonsoft JSON.
 
Cognitive Services
 
Install Microsoft.Csharp
 
This step is optional. If you get the error "Microsoft.CSharp.RuntimeBinder.Binder.Convert" is not found by the compiler for dynamic type,  by adding a reference as Microsoft.CSharp to the Dotnet Standard /PCL project, the issue will get resolved.
 
Cognitive Services
 
Design View
 
After successfully installing the above two nuget packages, let's start designing the UI design from Dot Standard /PCL project. In PCL Project > Open MainPage.Xaml page and add design Entry and list view control with item template in Xaml
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <ContentPage xmlns="https://xamarin.com/schemas/2014/forms"  
  3.              xmlns:x="https://schemas.microsoft.com/winfx/2009/xaml"  
  4.              xmlns:local="clr-namespace:XamarinBingWebSearch"  
  5.              x:Class="XamarinBingWebSearch.MainPage">  
  6.   
  7.     <ContentPage.Content>  
  8.         <StackLayout>  
  9.             <Label Text="Search" ></Label>  
  10.             <Entry x:Name="entrysearch" Placeholder="Type Your text"  TextChanged="OnTextChangesEvent" />  
  11.             <ListView x:Name="lstwebsearch" BackgroundColor="Azure">  
  12.                 <ListView.ItemTemplate>  
  13.                     <DataTemplate>  
  14.                         <ViewCell>  
  15.                             <StackLayout Orientation="Vertical">  
  16.                                 <Label Text="{Binding Snippet}">  
  17.                                     </Label>  
  18.                                 <Label Text="{Binding DisplayUrl}">  
  19.                                 </Label>  
  20.                                 <Label Text="{Binding Name}" TextColor="Gray"></Label>  
  21.                                 <Label Text="{Binding Url}" TextColor="Gray"></Label>  
  22.                             </StackLayout>  
  23.                         </ViewCell>  
  24.                     </DataTemplate>  
  25.                 </ListView.ItemTemplate>  
  26.   
  27.             </ListView>  
  28.         </StackLayout>  
  29.     </ContentPage.Content>  
  30.   
  31. </ContentPage>  
Bing web search will return ID, Name, URL, Snippet, and DispalyUrl so create a model class for web search.
  1. namespace XamarinBingWebSearch.Model  
  2. {  
  3.     public class WebSearch  
  4.     {  
  5.         public string Id { get; set; }  
  6.         public string Name { get; set; }  
  7.         public string Url { get; set; }  
  8.         public string Snippet { get; set; }  
  9.         public string DisplayUrl { get; set; }  
  10.     }  
  11. }  
Configure the project
 
We need to get web search results so send a GET request to the following endpoint and replace subscription key from Mainpage.xaml.cs
  1. private string WebSearchEndPoint = "https://api.cognitive.microsoft.com/bing/v7.0/search?";  
  2.        
  3.      public HttpClient WebSearchClient  
  4.      {  
  5.          get;  
  6.          set;  
  7.      }  
  8.      public MainPage()  
  9.      {  
  10.          InitializeComponent();  
  11.          WebSearchClient = new HttpClient();  
  12.          WebSearchClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key""YOUR API KEY");  
  13.      }  
Get and Parse Json Data
 
HttpClient class provides a base class to get/Post the HTTP requests/responses from a URL. It is a supported async feature of .NET framework. HttpClient is able to process multiple concurrent requests. The following code shows how to get all JSON data using the Bing web Search API URL and Parse the JSON and binding into the list view for displaying the search result.
  1. private async void OnTextChangesEvent(object sender, TextChangedEventArgs e)  
  2.      {  
  3.           try  
  4.           {  
  5.               if (entrysearch != null)  
  6.                   lstwebsearch.ItemsSource = await SearchBingWeb(entrysearch.Text);  
  7.           }  
  8.           catch (Exception)  
  9.           {  
  10.   
  11.           }  
  12.   
  13.       }  
  14.       async Task<IEnumerable<WebSearch>> SearchBingWeb(string searchText)  
  15.       {  
  16.           List<WebSearch> websearch = new List<WebSearch>();  
  17.   
  18.           string count = "10";  
  19.           string offset = "0";  
  20.           string mkt = "en-us";  
  21.           var result = await RequestAndAutoRetryWhenThrottled(() => WebSearchClient.GetAsync(string.Format("{0}q={1}&count={2}&offset={3}&mkt={4}", WebSearchEndPoint, WebUtility.UrlEncode(searchText), count, offset, mkt)));  
  22.           result.EnsureSuccessStatusCode();  
  23.           var json = await result.Content.ReadAsStringAsync();  
  24.           dynamic data = JObject.Parse(json);  
  25.           for (int i = 0; i < 10; i++)  
  26.           {  
  27.               websearch.Add(new WebSearch  
  28.               {  
  29.                   Id = data.webPages.value[i].id,  
  30.                   Name = data.webPages.value[i].name,  
  31.                   Url = data.webPages.value[i].url,  
  32.                   Snippet = data.webPages.value[i].snippet,  
  33.                   DisplayUrl = data.webPages.value[i].displayUrl  
  34.               });  
  35.           }  
  36.           return websearch;  
  37.       }  
  38.       private async Task<HttpResponseMessage> RequestAndAutoRetryWhenThrottled(Func<Task<HttpResponseMessage>> action)  
  39.       {  
  40.           int retriesLeft = 6;  
  41.           int delay = 500;  
  42.   
  43.           HttpResponseMessage response = null;  
  44.   
  45.           while (true)  
  46.           {  
  47.               response = await action();  
  48.   
  49.               if ((int)response.StatusCode == 429 && retriesLeft > 0)  
  50.               {  
  51.                   await Task.Delay(delay);  
  52.                   retriesLeft--;  
  53.                   delay *= 2;  
  54.                   continue;  
  55.               }  
  56.               else  
  57.               {  
  58.                   break;  
  59.               }  
  60.           }  
  61.   
  62.           return response;  
  63.       } 
Run the Application
 
We have completed the coding now start running the application. You can select the platform iOS, Android, or Windows and Click on Run (f5) the application.
 
Cognitive Services
 
You can find the source code at C# Corner attachment and Github XamarinBingWebSearch repository as Microsoft-Cognitive-Service.
 

Summary

 
In this article, you learned about how to generate a Bing Search subscription key and integrate it into the Bing web search in a Xamarin application. If you have any questions/ feedback/ issues, please write in the comment box.


Similar Articles