Building Xamarin Mobile Application With Bing AutoSuggest Using Cognitive Services

Introduction

 
The Bing Autosuggest API returns a list of suggested queries based on what the user enters in the search box. Also, it displays the suggestions in the search box's drop-down list. The suggested terms are based on suggested queries that other users have searched for.
 
Xamarin
 
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 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”.
 
Xamarin
 
Step 3
 
On the "Create" page, provide the name, pricing, resource group, and click on "Create".
 
Xamarin
 
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.
 
Xamarin
 
Create a Xamarin Application with Bing AutoSuggest
 
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.
 
Xamarin
 
It will automatically create multiple projects, like .NET Standard, Android, iOS, and UWP.
 
Install Newtonsoft.Json
 
Bing Autosuggest will return JSON object value so as to make sure you have added the Newtonsoft JSON NuGet Package to your all projects. Right-click on Solution > Manage Nuget Package > Install Newtonsoft JSON.
 
Xamarin
 
Install Microsoft.Csharp
 
This step is optional. If you get the error  "Microsoft.CSharp.RuntimeBinder.Binder.Convert" not found by the compiler for dynamic type, adding a reference to Microsoft.CSharp to the project will resolve the issue.
 
Xamarin
 
Design View
 
After successfully installing the above two nuGet packages, let us start designing UI design from Dot Standard /PCL project. In PCL Project > Open MainPage.Xaml page and add design Entry and list view control 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:XamarinBingAutoSuggest"  
  5.              x:Class="XamarinBingAutoSuggest.MainPage">  
  6.   
  7.     <StackLayout>  
  8.         <Entry x:Name="entrysearch" Placeholder="Type Your text"  TextChanged="OnTextChangesEvent" />  
  9.         <ListView x:Name="lstautosug" BackgroundColor="Azure"  SelectedItem="{Binding Source={x:Reference entrysearch},  
  10.  Path=Text}"></ListView>  
  11.     </StackLayout>  
  12.   
  13. </ContentPage> 
Configure the project
 
Open the MainPage.xaml.cs file from the PCL project and replace your subscription key and Endpoint URL.
  1. private string AutoSuggestionEndPoint = "https://api.cognitive.microsoft.com/bing/v7.0/suggestions";  
  2.       public HttpClient AutoSuggestionClient  
  3.       {  
  4.           get;  
  5.           set;  
  6.       }  
  7.       public MainPage()  
  8. {  
  9.     InitializeComponent();  
  10.           AutoSuggestionClient = new HttpClient();  
  11.           AutoSuggestionClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key""<Key>");  
  12.       } 
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 Bing suggestions API URL and parse the JSON and binding into the list view for autocomplete
  1. private async void OnTextChangesEvent(object sender, TextChangedEventArgs e)  
  2.         {  
  3.             try  
  4.             {  
  5.                 if(entrysearch!=null)  
  6.                 lstautosug.ItemsSource = await GetAutoSuggestResults(this.entrysearch.Text);  
  7.             }  
  8.             catch (HttpRequestException)  
  9.             {  
  10.                   
  11.             }  
  12.   
  13.         }  
  14.         public async  Task<List<string>> GetAutoSuggestResults(string query)  
  15.         {  
  16.             List<string> suggestions = new List<string>();  
  17.             string market = "en-US";  
  18.             var result = await AutoSuggestionClient.GetAsync(string.Format("{0}/?q={1}&mkt={2}", AutoSuggestionEndPoint, WebUtility.UrlEncode(query), market));  
  19.             result.EnsureSuccessStatusCode();  
  20.             var json = await result.Content.ReadAsStringAsync();  
  21.             dynamic data = JObject.Parse(json);  
  22.             if (data.suggestionGroups != null && data.suggestionGroups.Count > 0 && data.suggestionGroups[0].searchSuggestions != null)  
  23.             {  
  24.                 for (int i = 0; i < data.suggestionGroups[0].searchSuggestions.Count; i++)  
  25.                 {  
  26.                     suggestions.Add(data.suggestionGroups[0].searchSuggestions[i].displayText.Value);  
  27.                 }  
  28.             }  
  29.             return suggestions;  
  30.         } 
Run the Application
 
We have completed the coding. Now, let us start running the application. You can select the platform iOS, Android, or Windows, and click on Run (f5) the application.
 
 
You can find the source code in the attachment and on GitHub XamarinBingAutoSuggest repository as Microsoft-Cognitive-Service.
 

Summary

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