Building Xamarin Mobile Application With Bing News Search Using Cognitive Services

Introduction

 
The Bing News Search API returns a list of global news from a search query that can customize trending news from around the world by category and region. Results include information such as news title, description, URL, provider, and images. This API provides a list of categorized news searches by topics such as World, Politics, Sports, and more. The News Search API uses JSON format for data exchange and API keys for authentication.
 
Cognitive Services
 
In this article, I will show you 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
 
Click “+ Create a resource “ and 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 New 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 News Search API will return Json object value so make sure you have added the Newtonsoft JSON NuGet Package to your all projects. Right-click on Solution > Manage NuGet Package > Install Newtonsoft JSON.
 
Cognitive Services
 
Install Microsoft.Csharp
 
This step is optional. If you get an error "Microsoft.CSharp.RuntimeBinder.Binder.Convert not found by the compiler for dynamic type",  adding a reference as Microsoft.CSharp to the .NET Standard /PCL project, the issue will get resolved.
 
Cognitive Services
 
Design View
 
After successfully installing the above two NuGet Packages, let us start designing the UI design from .NET Standard /PCL project. In PCL Project > open MainPage.Xaml page and add the 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:XamarinBingNewsSearch"  
  5.              x:Class="XamarinBingNewsSearch.MainPage">  
  6.   
  7.     <ContentPage.Content>  
  8.         <StackLayout>  
  9.             <Label Text="Search News" ></Label>  
  10.         <Entry x:Name="entrysearch" Placeholder="Type Your text"  TextChanged="OnTextChangesEvent" />  
  11.         <ListView x:Name="lstnews" BackgroundColor="Azure">  
  12.             <ListView.ItemTemplate>  
  13.                 <DataTemplate>  
  14.   
  15.                     <ViewCell>  
  16.                         <StackLayout Orientation="Horizontal" >  
  17.                                  
  18.                                 <StackLayout Orientation="Vertical">  
  19.                                 <Label Text="{Binding Title}" Font="18"></Label>  
  20.                                 <Label Text="{Binding Description}" TextColor="Gray"></Label>  
  21.                                 <Label Text="{Binding Provider}" TextColor="Gray"></Label>  
  22.                             </StackLayout>  
  23.                                 <Image Source="{Binding ThumbnailUrl}" HeightRequest="30" WidthRequest="50" HorizontalOptions="EndAndExpand"></Image>  
  24.                             </StackLayout>  
  25.                         </ViewCell>  
  26.                 </DataTemplate>  
  27.             </ListView.ItemTemplate>  
  28.   
  29.         </ListView>  
  30.     </StackLayout>  
  31.         </ContentPage.Content>  
  32. </ContentPage> 
Bing News Search will return the title and description, URL, and images so create a model class for news articles.
  1. namespace XamarinBingNewsSearch.Model  
  2. {  
  3.     public class NewsArticle  
  4.     {  
  5.         public string Title { get; set; }  
  6.         public string Description { get; set; }  
  7.         public string Url { get; set; }  
  8.         public string ThumbnailUrl { get; set; }  
  9.         public string Provider { get; set; }  
  10.     }  
  11. }  
Configure the project
 
We need to get the news only in the search results so send a GET request to the following endpoint and replace the subscription key from Mainpage.xaml.cs.
  1. private  string NewsSearchEndPoint = "https://api.cognitive.microsoft.com/bing/v7.0/news/search";  
  2.         public HttpClient BingNewsSearchClient  
  3.         {  
  4.             get;  
  5.             set;  
  6.         }  
  7.         public MainPage()  
  8.         {  
  9.             InitializeComponent();  
  10.             BingNewsSearchClient = new HttpClient();  
  11.             BingNewsSearchClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key""YOUR API KEY");  
  12.         } 
Get and Parse Json Data
 
The HttpClient class provides a base class for 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 gets all the JSON data using Bing suggestions API URL, and parses the JSON and binds 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 run the application. You can select any platform iOS, Android, Windows. Now, click on Run (f5) the application.
 
 
You can find the source code in the attachment or on the GitHub XamarinBingAutoSuggest repository as Microsoft-Cognitive-Service.
 

Summary

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