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

Cognitive Service Bing Image 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 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 Image Search API

Search for images and get comprehensive results, and scour the web for images. Results include thumbnails, full image URLs, publishing website info, image metadata and more.

Reading this article, you can learn how to use Cognitive Service Bing Image 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 the Suitable Name for your App (UWPCogBingImage)->OK.

UWPCogBingImage

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

UWPCogBingImage

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

UWPCogBingImage

Step 2


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

UWPCogBingImage

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

UWPCogBingImage

Step 3

Add GridView Resources using the following code,

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

Add a GridView Control and set the ItemSource properties
  1. <GridView x:Name="gvImgSearch" 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 News details.
  1. <GridView.ItemTemplate>  
  2.     <DataTemplate>  
  3.         <Border Background="AliceBlue" Width="139" Height="102" 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" /> </Grid.RowDefinitions>  
  12.                     <StackPanel Margin="0,0,0,-89">  
  13.                         <HyperlinkButton NavigateUri="{Binding imco.ContentUrl}" Foreground="Black">  
  14.                             <Image Source="{Binding imco.ContentUrl}" VerticalAlignment="Center" Margin="6" />  
  15.                         </HyperlinkButton>  
  16.                         <TextBlock TextWrapping="Wrap" Text="{Binding imco.Name}" Style="{StaticResource CaptionTextBlockStyle}" />  
  17.                     </StackPanel>  
  18.                 </Grid>  
  19.             </Grid>  
  20.         </Border>  
  21.     </DataTemplate>  
  22. </GridView.ItemTemplate>  
UWPCogBingImage

Step 4

Open (double Click) the file MainPage.xaml in the Solution Explorer and add the Newtonsoft.Json reference in the project. RightClick Your Project (UWPCogBingImage) and Select Manage Nuget Packages.

UWPCogBingImage

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

UWPCogBingImage

Reference added to your project

UWPCogBingImage

Step 5

Add the Click event method for Search button

UWPCogBingImage

Note

Automatically the following code will be generated in XAML code view, while we are done in the design view.
  1. <Page x:Class="UWPCogBingImage.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:UWPCogBingImage" 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="132,51,0,0" TextWrapping="Wrap" Text="UWP Cognitive Service Bing Image Search API Demo " VerticalAlignment="Top" FontWeight="Bold" />  
  7.         <AutoSuggestBox x:Name="asbImage" HorizontalAlignment="Left" Margin="96,91,0,0" VerticalAlignment="Top" Width="319" />  
  8.         <Button x:Name="btnImgSearch" HorizontalAlignment="Left" Margin="420,91,0,0" VerticalAlignment="Top" Width="40" Click="btnImgSearch_Click">  
  9. <SymbolIcon Symbol="Find"></SymbolIcon>  
  10. </Button>  
  11.         <GridView x:Name="gvImgSearch" 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="AliceBlue" Width="139" Height="102" 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" /> </Grid.RowDefinitions>  
  23.                             <StackPanel Margin="0,0,0,-89">  
  24.                                 <HyperlinkButton NavigateUri="{Binding imco.ContentUrl}" Foreground="Black">  
  25.                                     <Image Source="{Binding imco.ContentUrl}" VerticalAlignment="Center" Margin="6" />  
  26.                                 </HyperlinkButton>  
  27.                                 <TextBlock TextWrapping="Wrap" Text="{Binding imco.Name}" Style="{StaticResource CaptionTextBlockStyle}" />  
  28.                             </StackPanel>  
  29.                         </Grid>  
  30.                     </Grid>  
  31.                 </Border>  
  32.             </DataTemplate>  
  33.             </GridView.ItemTemplate>  
  34.         </GridView>  
  35.     </Grid>  
  36. </Page>  
Step 6

Add the following namespaces in Mainpage.xaml.cs for Bing Image search

 

  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 Search client keys use Azure service and Generate it (For More Information, Please refer the article How To Create Microsoft Cognitive Service Bing Search APIs On Azure Portal)

Image search EndPoint is :

var ImgSearchEndPoint = "https://api.cognitive.microsoft.com/bing/v5.0/images/search?";

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

Step 8

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

UWPCogBingImage

Summary

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

If you are 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#