Cognitive Service Bing AutoSuggest API Using UWP With Azure, XAML And C#

Before reading this article, please go through the following article.

  1. Introduction To Universal Windows Platform (UWP) App Development Using Windows 10 And Visual Studio 2015
  2. Getting Started With Microsoft Azure Cognitive Services - Bing Autosuggest API

Microsoft Cognitive Services (formerly Project Oxford) are a set of APIs, SDKs and services available to developers to make their applications more intelligent, engaging and discoverable. Microsoft Cognitive Services expands on Microsoft’s evolving portfolio of machine learning APIs and enables developers to easily add intelligent features. Microsoft Cognitive Services let you build apps with powerful algorithms using just a few lines of code. They work across devices and platforms such as iOS, Android, and Windows, keep improving, and are easy to set up.

Bing Autosuggest API, as described by Microsoft, gives the app intelligent Autosuggest options, so the users can type less and get to what they want faster. It helps the users to complete the queries faster by adding the intelligent type-ahead capabilities to apps or Websites. Also, it empowers the users to type less and do more with the automated and complete search suggestions.

Reading this article, you can learn how to use Cognitive Service Bing AutoSuggest API in Universal Windows Apps development with Azure, XAML and Visual C#.

The following important tools are required for developing UWP,

  1. Windows 10 (Recommended)
  2. Visual Studio 2015 Community Edition (It is a free software available online)
  3. Cognitive Service Bing AutoSuggest API Key (using azure Getting Started With Microsoft Azure Cognitive Services - Bing Autosuggest API)

Now we can discuss step by step App development.

Step 1

Open Visual studio 2015 -> Start -> New Project-> Select Universal (under Visual C#->Windows)-> Blank App -> Give the Suitable Name for your App (UWPCogBingAutoSuggest)->OK.



After Choosing the Target and minimum platform version for your Windows Universal Application will support and the Project creates App.xaml and MainPage.xaml.



Add TextBlock control and change the Name and text property for title,



Step 2

Add AutoSuggestBox control and set the Name, PlaceholderText and Text Properties



Add the TextChanged event method for getting Auto Suggest text from Bing



Step 3

Open (double Click) the file MainPage.xaml in the Solution Explorer and add the Newtonsoft.Json reference in the project.

RightClick Your Project (UWPCogBingAutoSuggest) and Select Manage Nuget Packages.



For adding Newtonsoft.Json Reference, Choose Browse and Search Newtonsoft.Json select the package and install it.



Reference added your project



Note

Automatically the following code will be generated in XAML code view, while we are done in the design view.

  1. <Page x:Class="UWPCogBingAutoSuggest.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:UWPCogBingAutoSuggest" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d">  
  2.     <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">  
  3.         <TextBlock x:Name="tblTitle" HorizontalAlignment="Left" Margin="145,52,0,0" TextWrapping="Wrap" Text="UWP Cognitive Services - Bing Autosuggest API" VerticalAlignment="Top" Height="32" Width="373" FontSize="16" FontWeight="Bold" />  
  4.         <AutoSuggestBox x:Name="asbBing" HorizontalAlignment="Left" Margin="145,152,0,0" VerticalAlignment="Top" Height="34" Width="373" PlaceholderText="Enter Search Text" TextChanged="asbBing_TextChanged" />  
  5.     </Grid>  
  6. </Page>  
Step 4

Add the following namespaces in Mainpage.xaml.cs for Bing Autosuggest,
  1. using System.Net.Http;  
  2. using System.Threading.Tasks;  
  3. using Newtonsoft.Json.Linq;  
  4. using System.Net;  
Step 5

Add the autoSuggestionClient key use Azure service and Generate it (For More Information, Please refer the article Getting Started With Microsoft Azure Cognitive Services - Bing Autosuggest API)

Add the following code with azure generated key,
  1. private static string AutoSuggestionEndPoint = "https://api.cognitive.microsoft.com/bing/v5.0/suggestions";  
  2. private static HttpClient autoSuggestionClient {  
  3.     get;  
  4.     set;  
  5. }  
  6.   
  7. autoSuggestionClient = new HttpClient();  
  8. autoSuggestionClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key""<Your Bing Auto suggest Key>");  
  9.   
  10. private async void asbBing_TextChanged(AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args) {  
  11.     if (args.Reason == AutoSuggestionBoxTextChangeReason.UserInput) {  
  12.         try {  
  13.             this.asbBing.ItemsSource = await GetAutoSuggestResults(this.asbBing.Text);  
  14.         } catch (HttpRequestException) {  
  15.             // default to no suggestions  
  16.             this.asbBing.ItemsSource = null;  
  17.         }  
  18.     }  
  19. }  
  20. public static async Task < IEnumerable < string >> GetAutoSuggestResults(string query) {  
  21.     List < string > suggestions = new List < string > ();  
  22.     string market = "en-US";  
  23.     var result = await autoSuggestionClient.GetAsync(string.Format("{0}/?q={1}&mkt={2}", AutoSuggestionEndPoint, WebUtility.UrlEncode(query), market));  
  24.     result.EnsureSuccessStatusCode();  
  25.     var json = await result.Content.ReadAsStringAsync();  
  26.     dynamic data = JObject.Parse(json);  
  27.     if (data.suggestionGroups != null && data.suggestionGroups.Count > 0 && data.suggestionGroups[0].searchSuggestions != null) {  
  28.         for (int i = 0; i < data.suggestionGroups[0].searchSuggestions.Count; i++) {  
  29.             suggestions.Add(data.suggestionGroups[0].searchSuggestions[i].displayText.Value);  
  30.         }  
  31.     }  
  32.     return suggestions;  
  33. }  


Step 6

Deploy of your App in Local Machine, and The output of the UWPCogBingAutoSuggest App is,



Another Suggestion is,



Summary

Now you are successfully tested Cognitive Service Bing AutoSuggest API using Azure, XAML AND C# with UWP environment.