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

Cognitive Service Bing Web Search API using UWP with Azure, XAML AND C#

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

  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. Microsoft Cognitive Services lets 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 Web Search API

Get enhanced search details from billions of web documents. Retrieve web documents indexed by Bing and narrow down the results by result type, freshness and more.

Reading this article, you can learn how to use Cognitive Service Bing Web 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.

Step1


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

Bing Web Search

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

Bing Web Search

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

Bing Web Search

Step 2

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

Bing Web Search

Add a Button Control and set the Name and add the search icon for Find operation

Bing Web Search

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 (UWPCogBingWeb) and Select Manage Nuget Packages.

Bing Web Search

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

Bing Web Search

Reference added your project

Bing Web Search

Step 4

Add GridView Resources using the following code,

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

Add a GridView Control and set the ItemSource properties
  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 Item Template for Search result details.
  1. <GridView.ItemTemplate>  
  2.     <DataTemplate>  
  3.         <Border Background="AliceBlue" Width="599" Height="73" Margin="8">  
  4.             <Grid>  
  5.                 <Grid.ColumnDefinitions>  
  6.                     <ColumnDefinition Width="auto" />  
  7.                     <ColumnDefinition/>  
  8.                 </Grid.ColumnDefinitions>  
  9.                 <Grid Grid.Column="1" Margin="3,3,3,10">  
  10.                     <Grid.RowDefinitions>  
  11.                         <RowDefinition Height="auto" />  
  12.                     </Grid.RowDefinitions>  
  13.                     <StackPanel>  
  14.                         <HyperlinkButton NavigateUri="{Binding WSer.Url}" Foreground="Black">  
  15.                             <TextBlock TextWrapping="Wrap" Text="{Binding WSer.Name}" Style="{StaticResource CaptionTextBlockStyle}" />  
  16.                         </HyperlinkButton>  
  17.                         <TextBlock TextWrapping="Wrap" Text="{Binding WSer.DisplayUrl}" Style="{StaticResource CaptionTextBlockStyle}" />  
  18.                         <TextBlock TextWrapping="Wrap" Text="{Binding WSer.Snippet}" Style="{StaticResource CaptionTextBlockStyle}" />  
  19.                     </StackPanel>  
  20.                 </Grid>  
  21.             </Grid>  
  22.         </Border>  
  23.     </DataTemplate>  
  24. </GridView.ItemTemplate>  
Bing Web Search

Step 5

Add the Click event method for Search button

Bing Web Search

Note

Automatically the following code will be generated in XAML code view, while we are done in the design view.
  1. <Page x:Class="UWPCogBingWeb.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:UWPCogBingWeb" 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="textBlock" HorizontalAlignment="Left" Margin="155,51,0,0" TextWrapping="Wrap" Text="UWP Cognitive Service Websearch API Demo" VerticalAlignment="Top" FontWeight="Bold" />  
  7.         <AutoSuggestBox x:Name="asbWebSearch" HorizontalAlignment="Left" Margin="99,96,0,0" VerticalAlignment="Top" Width="318" PlaceholderText="Enter Search Text Here....." />  
  8.         <Button x:Name="btnSearch" HorizontalAlignment="Left" Margin="424,96,0,0" VerticalAlignment="Top" Height="32" Width="49" Click="btnSearch_Click">  
  9. <SymbolIcon Symbol="Find"/>  
  10. </Button>  
  11.         <GridView x:Name="gvWeb" ItemsSource="{Binding Source={StaticResource SearchResultsCol}}" SelectionMode="None" IsItemClickEnabled="False" HorizontalAlignment="Left" Height="217" Margin="10,133,0,0" VerticalAlignment="Top" Width="620">  
  12.             <GridView.ItemTemplate>  
  13.                 <DataTemplate>  
  14.                     <Border Background="AliceBlue" Width="599" Height="73" Margin="8">  
  15.                         <Grid>  
  16.                             <Grid.ColumnDefinitions>  
  17.                                 <ColumnDefinition Width="auto" />  
  18.                                 <ColumnDefinition/>  
  19.                             </Grid.ColumnDefinitions>  
  20.                             <Grid Grid.Column="1" Margin="3,3,3,10">  
  21.                                 <Grid.RowDefinitions>  
  22.                                     <RowDefinition Height="auto" />  
  23.                                 </Grid.RowDefinitions>  
  24.                                 <StackPanel>  
  25.                                     <HyperlinkButton NavigateUri="{Binding WSer.Url}" Foreground="Black">  
  26.                                         <TextBlock TextWrapping="Wrap" Text="{Binding WSer.Name}" Style="{StaticResource CaptionTextBlockStyle}" />  
  27.                                     </HyperlinkButton>  
  28.                                     <TextBlock TextWrapping="Wrap" Text="{Binding WSer.DisplayUrl}" Style="{StaticResource CaptionTextBlockStyle}" />  
  29.                                     <TextBlock TextWrapping="Wrap" Text="{Binding WSer.Snippet}" Style="{StaticResource CaptionTextBlockStyle}" />  
  30.                                 </StackPanel>  
  31.                             </Grid>  
  32.                         </Grid>  
  33.                     </Border>  
  34.                 </DataTemplate>  
  35.             </GridView.ItemTemplate>  
  36.         </GridView>  
  37.     </Grid>  
  38. </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 Searchclient keys use Azure service and Generate it (For More Information, Please refer to the article How To Create Microsoft Cognitive Service Bing Search APIs On Azure Portal)

Add the following code with an Azure generated key,
  1. public class WebSer  
  2. {  
  3. public string Id { get; set; }  
  4. public string Name { get; set; }  
  5. public string Url { get; set; }  
  6. public string Snippet { get; set; }  
  7. public string DisplayUrl { get; set; }  
  8. }  
  9. public class ws  
  10. {  
  11. public WebSer WSer { get; set; }  
  12. }  
  13. public string q;  
  14. public ObservableCollection<ws> SearchResults { get; set; } = new ObservableCollection<ws>();  
  15. private async void btnSearch_Click(object sender, RoutedEventArgs e)  
  16. {  
  17. q = asbWebSearch.Text.Trim();  
  18. var res = await MakeRequest();  
  19. for (int i = 0; i < res.Count(); i++)  
  20. {  
  21. WebSer webser = res.ElementAt(i);  
  22. SearchResults.Add(new ws { WSer = webser });  
  23. }  
  24. }  
  25. async Task<IEnumerable<WebSer>> MakeRequest()  
  26. {  
  27. List<WebSer> sres = new List<WebSer>();  
  28. var client = new HttpClient();  
  29. // Request headers  
  30. client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key""<Your Key>");  
  31. // Request parameters  
  32. string count = "10";  
  33. string offset = "0";  
  34. string mkt = "en-us";  
  35. var WebSearchEndPoint = "https://api.cognitive.microsoft.com/bing/v5.0/search?";  
  36. var result = await client.GetAsync(string.Format("{0}q={1}&count={2}&offset={3}&mkt={4}", WebSearchEndPoint, WebUtility.UrlEncode(q), count, offset, mkt));  
  37. result.EnsureSuccessStatusCode();  
  38. var json = await result.Content.ReadAsStringAsync();  
  39. dynamic data = JObject.Parse(json);  
  40. for (int i = 0; i < 10; i++)  
  41. {  
  42. sres.Add(new WebSer  
  43. {  
  44. Id = data.webPages.value[i].id,  
  45. Name = data.webPages.value[i].name,  
  46. Url = data.webPages.value[i].url,  
  47. Snippet = data.webPages.value[i].snippet,  
  48. DisplayUrl = data.webPages.value[i].displayUrl  
  49. });  
  50. }  
  51. return sres;  
  52. }  


Bing Web Search

Step 8

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



Summary

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

If interested Please read the UWP Cognitive Service articles,
  1. Cognitive Service Bing News Search API Using UWP With Azure, XAML And C#
  2. Cognitive Service Bing AutoSuggest API Using UWP With Azure, XAML And C#
  3. Multiple People Emotions In UWP With Cognitive Service Emotion API, Azure, XAML And C#
  4. Cognitive Service Emotion API In UWP With Azure, XAML And C#
  5. Retrieving Face Attributes Using Cognitive Service Face API In UWP With Azure, XAML And C#
  6. Cognitive Service Face API, Using UWP With Azure, XAML And C#

Up Next
    Ebook Download
    View all
    Learn
    View all