Cognitive Service Bing News Search 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. How To Create Microsoft Cognitive Service Bing Search APIs On Azure Portal

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. These 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 Search APIs make our apps, webpages and other experiences smarter and more engaging with the Bing Search APIs. Harness the same knowledge used by hundreds of millions of people, as well as the industry’s technology leaders, today.

Bing News Search API searches the web for news articles. Results include details like authoritative images of the news article, related news and categories, provider info, article URL, and date added.

Reading this article, you can learn how to use Cognitive Service Bing News Search 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 Search APIs Key (using azure How To Create Microsoft Cognitive Service Bing Search APIs On Azure Portal)

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 a suitable name for your app (UWPCogBingSearch) -> OK.



After choosing the target and minimum platform version that your app 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

Open (double click) the file MainPage.xaml in the Solution Explorer and add the Newtonsoft.Json reference in the project. Right click your project (UWPCogBingSearch) and select "Manage NuGet Packages".



For adding Newtonsoft.Json Reference, choose Browse and search Newtonsoft.Json. Select the package and install it.



Reference is added to your project.



Step 3

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



Add a Button control,set the name, and add the search icon for Find operation.



Step 4

Add Grid Resources using the following code for GridView.

  1. <Grid.Resources>  
  2.    <CollectionViewSource x:Name="SearchResultsCol" Source="{x:Bind SearchResults}" IsSourceGrouped="False" />  
  3. </Grid.Resources> 


Add a GridView Control and set the ItemSource properties for displaying News Result,
  1. <GridView x:Name="gridView" ItemsSource="{Binding Source={StaticResource SearchResultsCol}}" SelectionMode="None" IsItemClickEnabled="False" HorizontalAlignment="Left" Height="228" Margin="10,122,0,0" VerticalAlignment="Top" Width="620">  


Add the following code for Grid View Data Template for News details.
  1. <GridView.ItemTemplate>  
  2.     <DataTemplate>  
  3.         <Border Background="Green" Width="300" Height="105" Margin="8">  
  4.             <Grid>  
  5.                 <Grid.ColumnDefinitions>  
  6.                     <ColumnDefinition Width="auto" />  
  7.                     <ColumnDefinition/> </Grid.ColumnDefinitions>  
  8.                 <Image Source="{Binding Article.ThumbnailUrl}" VerticalAlignment="Center" Margin="6" />  
  9.                 <Grid Grid.Column="1" Margin="4">  
  10.                     <Grid.RowDefinitions>  
  11.                         <RowDefinition Height="auto" />  
  12.                         <RowDefinition/>  
  13.                         <RowDefinition Height="auto" /> </Grid.RowDefinitions>  
  14.                     <HyperlinkButton NavigateUri="{Binding Article.Url}" Foreground="White">  
  15.                         <TextBlock TextWrapping="Wrap" Text="{Binding Article.Title}" Style="{StaticResource CaptionTextBlockStyle}" />  
  16.                     </HyperlinkButton>  
  17.                 </Grid>  
  18.             </Grid>  
  19.         </Border>  
  20.     </DataTemplate>  
  21. </GridView.ItemTemplate>  
Step 5

Add the Textchanged event method in Auto Suggest Box for getting suggestions for  the text from Bing



Add the Click event method for Search button



Note

Automatically the following code will be generated in XAML code view, when we are done in the design view.
  1. <Page x:Class="UWPCogBingSearch.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:UWPCogBingSearch" 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.         <Grid.Resources>  
  4.             <CollectionViewSource x:Name="SearchResultsCol" Source="{x:Bind SearchResults}" IsSourceGrouped="False" />  
  5.         </Grid.Resources>  
  6.         <TextBlock x:Name="tblTitle" HorizontalAlignment="Left" Margin="163,43,0,0" TextWrapping="Wrap" Text="UWP Cognitive Service Bing News Search API Demo" VerticalAlignment="Top" Foreground="#FF2B2A2A" FontWeight="Bold" />  
  7.         <AutoSuggestBox x:Name="asbBingsearch" HorizontalAlignment="Left" Margin="64,88,0,0" VerticalAlignment="Top" Height="29" Width="409" PlaceholderText="Enter search term............." TextChanged="asbBingsearch_TextChanged" />  
  8.         <Button x:Name="btnSearch" HorizontalAlignment="Left" Margin="478,88,0,0" VerticalAlignment="Top" Height="29" Width="41" FontSize="14" Click="btnSearch_Click">  
  9. <SymbolIcon Symbol="Find"/>  
  10. </Button>  
  11.         <GridView x:Name="gridView" ItemsSource="{Binding Source={StaticResource SearchResultsCol}}" SelectionMode="None" IsItemClickEnabled="False" HorizontalAlignment="Left" Height="228" Margin="10,122,0,0" VerticalAlignment="Top" Width="620">  
  12.             <GridView.ItemTemplate>  
  13.                 <DataTemplate>  
  14.                     <Border Background="Green" Width="300" Height="105" Margin="8">  
  15.                         <Grid>  
  16.                             <Grid.ColumnDefinitions>  
  17.                                 <ColumnDefinition Width="auto" />  
  18.                                 <ColumnDefinition/> </Grid.ColumnDefinitions>  
  19.                             <Image Source="{Binding Article.ThumbnailUrl}" VerticalAlignment="Center" Margin="6" />  
  20.                             <Grid Grid.Column="1" Margin="4">  
  21.                                 <Grid.RowDefinitions>  
  22.                                     <RowDefinition Height="auto" />  
  23.                                     <RowDefinition/>  
  24.                                     <RowDefinition Height="auto" /> </Grid.RowDefinitions>  
  25.                                 <HyperlinkButton NavigateUri="{Binding Article.Url}" Foreground="White">  
  26.                                     <TextBlock TextWrapping="Wrap" Text="{Binding Article.Title}" Style="{StaticResource CaptionTextBlockStyle}" />  
  27.                                 </HyperlinkButton>  
  28.                             </Grid>  
  29.                         </Grid>  
  30.                     </Border>  
  31.                 </DataTemplate>  
  32.             </GridView.ItemTemplate>  
  33.         </GridView>  
  34.     </Grid>  
  35. </Page>  
Step 6

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;  
  5. using System.Collections.ObjectModel;  
Step 7

Add the autoSuggestionClient and autoSearchclient keys, use Azure service and Generate it (For more information, please refer the article Getting Started With Microsoft Azure Cognitive Services - Bing Autosuggest API to learn how To create Microsoft Cognitive Service Bing Search APIs on Azure Portal ).

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 string NewsSearchEndPoint = "https://api.cognitive.microsoft.com/bing/v5.0/news/search";  
  3. private static HttpClient autoSuggestionClient {  
  4.     get;  
  5.     set;  
  6. }  
  7. private static HttpClient searchClient {  
  8.     get;  
  9.     set;  
  10. }  
  11. private List < News > latestSearchResult = new List < News > ();  
  12. public ObservableCollection < News > SearchResults {  
  13.     get;  
  14.     set;  
  15. } = new ObservableCollection < News > ();  
  16. private static void InitializeBingClients() {  
  17.         autoSuggestionClient = new HttpClient();  
  18.         autoSuggestionClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key""<Your Key>");  
  19.         searchClient = new HttpClient();  
  20.         searchClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key""<Your Key>");  
  21.     }  
  22.     //Auto Suggest  
  23. private async void asbBingsearch_TextChanged(AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args) {  
  24.     if (args.Reason == AutoSuggestionBoxTextChangeReason.UserInput) {  
  25.         try {  
  26.             asbBingsearch.ItemsSource = await GetAutoSuggestResults(asbBingsearch.Text);  
  27.         } catch (HttpRequestException) {  
  28.             // default to no suggestions  
  29.             asbBingsearch.ItemsSource = null;  
  30.         }  
  31.     }  
  32. }  
  33. public static async Task < IEnumerable < string >> GetAutoSuggestResults(string query) {  
  34.         List < string > suggestions = new List < string > ();  
  35.         string market = "en-US";  
  36.         var result = await autoSuggestionClient.GetAsync(string.Format("{0}/?q={1}&mkt={2}", AutoSuggestionEndPoint, WebUtility.UrlEncode(query), market));  
  37.         result.EnsureSuccessStatusCode();  
  38.         var json = await result.Content.ReadAsStringAsync();  
  39.         dynamic data = JObject.Parse(json);  
  40.         if (data.suggestionGroups != null && data.suggestionGroups.Count > 0 &&  
  41.             data.suggestionGroups[0].searchSuggestions != null) {  
  42.             for (int i = 0; i < data.suggestionGroups[0].searchSuggestions.Count; i++) {  
  43.                 suggestions.Add(data.suggestionGroups[0].searchSuggestions[i].displayText.Value);  
  44.             }  
  45.         }  
  46.         return suggestions;  
  47.     }  
  48.     //News Search  
  49. private async void btnSearch_Click(object sender, RoutedEventArgs e) {  
  50.     var news = await GetNewsSearchResults(this.asbBingsearch.Text, count: 50, offset: 0, market: "en-US");  
  51.     for (int i = 0; i < news.Count(); i++) {  
  52.         NewsArticle article = news.ElementAt(i);  
  53.         SearchResults.Add(new News {  
  54.             Article = article  
  55.         });  
  56.     }  
  57. }  
  58. public static async Task < IEnumerable < NewsArticle >> GetNewsSearchResults(string query, int count = 20, int offset = 0, string market = "en-US") {  
  59.     List < NewsArticle > articles = new List < NewsArticle > ();  
  60.     var result = await searchClient.GetAsync(string.Format("{0}/?q={1}&count={2}&offset={3}&mkt={4}", NewsSearchEndPoint, WebUtility.UrlEncode(query), count, offset, market));  
  61.     result.EnsureSuccessStatusCode();  
  62.     var json = await result.Content.ReadAsStringAsync();  
  63.     dynamic data = JObject.Parse(json);  
  64.     if (data.value != null && data.value.Count > 0) {  
  65.         for (int i = 0; i < data.value.Count; i++) {  
  66.             articles.Add(new NewsArticle {  
  67.                 Title = data.value[i].name,  
  68.                     Url = data.value[i].url,  
  69.                     Description = data.value[i].description,  
  70.                     ThumbnailUrl = data.value[i].image ? .thumbnail ? .contentUrl,  
  71.                     Provider = data.value[i].provider ? [0].name  
  72.             });  
  73.         }  
  74.     }  
  75.     return articles;  
  76. }  


Step 8

Deploy your app in Local Machine. The output of the UWPCogBingSearch app is given below.



After clicking the Search Button.



Summary

Now, you have successfully tested Cognitive Service Bing News Search API using Azure, XAML AND C# with UWP environment.


Similar Articles