Cognitive Service Bing Web Search API using UWP with Azure, XAML AND C#
Before reading this article, please go through the following articles.
- Introduction To Universal Windows Platform (UWP) App Development Using Windows 10 And Visual Studio 2015
- 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,
- Windows 10 (Recommended)
- Visual Studio 2015 Community Edition (It is a free software available online)
- 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.
After Choosing the Target and minimum platform version your Windows Universal Application will support 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 a Button Control and set the Name and add the search icon for Find operation
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.
For adding Newtonsoft.Json Reference, Choose Browse and Search Newtonsoft.Json; select the package and install it.
Reference added your project
Step 4
Add GridView Resources using the following code,
- <Grid.Resources>
- <CollectionViewSource x:Name="SearchResultsCol" Source="{x:Bind SearchResults}" IsSourceGrouped="False" />
- </Grid.Resources>
Add a GridView Control and set the ItemSource properties
- <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.
- <GridView.ItemTemplate>
- <DataTemplate>
- <Border Background="AliceBlue" Width="599" Height="73" Margin="8">
- <Grid>
- <Grid.ColumnDefinitions>
- <ColumnDefinition Width="auto" />
- <ColumnDefinition/>
- </Grid.ColumnDefinitions>
- <Grid Grid.Column="1" Margin="3,3,3,10">
- <Grid.RowDefinitions>
- <RowDefinition Height="auto" />
- </Grid.RowDefinitions>
- <StackPanel>
- <HyperlinkButton NavigateUri="{Binding WSer.Url}" Foreground="Black">
- <TextBlock TextWrapping="Wrap" Text="{Binding WSer.Name}" Style="{StaticResource CaptionTextBlockStyle}" />
- </HyperlinkButton>
- <TextBlock TextWrapping="Wrap" Text="{Binding WSer.DisplayUrl}" Style="{StaticResource CaptionTextBlockStyle}" />
- <TextBlock TextWrapping="Wrap" Text="{Binding WSer.Snippet}" Style="{StaticResource CaptionTextBlockStyle}" />
- </StackPanel>
- </Grid>
- </Grid>
- </Border>
- </DataTemplate>
- </GridView.ItemTemplate>
Step 5
Add the Click event method for Search button
Note
Automatically the following code will be generated in XAML code view, while we are done in the design view.
- <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">
- <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
- <Grid.Resources>
- <CollectionViewSource x:Name="SearchResultsCol" Source="{x:Bind SearchResults}" IsSourceGrouped="False" />
- </Grid.Resources>
- <TextBlock x:Name="textBlock" HorizontalAlignment="Left" Margin="155,51,0,0" TextWrapping="Wrap" Text="UWP Cognitive Service Websearch API Demo" VerticalAlignment="Top" FontWeight="Bold" />
- <AutoSuggestBox x:Name="asbWebSearch" HorizontalAlignment="Left" Margin="99,96,0,0" VerticalAlignment="Top" Width="318" PlaceholderText="Enter Search Text Here....." />
- <Button x:Name="btnSearch" HorizontalAlignment="Left" Margin="424,96,0,0" VerticalAlignment="Top" Height="32" Width="49" Click="btnSearch_Click">
- <SymbolIcon Symbol="Find"/>
- </Button>
- <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">
- <GridView.ItemTemplate>
- <DataTemplate>
- <Border Background="AliceBlue" Width="599" Height="73" Margin="8">
- <Grid>
- <Grid.ColumnDefinitions>
- <ColumnDefinition Width="auto" />
- <ColumnDefinition/>
- </Grid.ColumnDefinitions>
- <Grid Grid.Column="1" Margin="3,3,3,10">
- <Grid.RowDefinitions>
- <RowDefinition Height="auto" />
- </Grid.RowDefinitions>
- <StackPanel>
- <HyperlinkButton NavigateUri="{Binding WSer.Url}" Foreground="Black">
- <TextBlock TextWrapping="Wrap" Text="{Binding WSer.Name}" Style="{StaticResource CaptionTextBlockStyle}" />
- </HyperlinkButton>
- <TextBlock TextWrapping="Wrap" Text="{Binding WSer.DisplayUrl}" Style="{StaticResource CaptionTextBlockStyle}" />
- <TextBlock TextWrapping="Wrap" Text="{Binding WSer.Snippet}" Style="{StaticResource CaptionTextBlockStyle}" />
- </StackPanel>
- </Grid>
- </Grid>
- </Border>
- </DataTemplate>
- </GridView.ItemTemplate>
- </GridView>
- </Grid>
- </Page>
Step 6
Add the following namespaces in Mainpage.xaml.cs for Bing Autosuggest,
- using System.Net.Http;
- using System.Threading.Tasks;
- using Newtonsoft.Json.Linq;
- using System.Net;
- 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,
- public class WebSer
- {
- public string Id { get; set; }
- public string Name { get; set; }
- public string Url { get; set; }
- public string Snippet { get; set; }
- public string DisplayUrl { get; set; }
- }
- public class ws
- {
- public WebSer WSer { get; set; }
- }
- public string q;
- public ObservableCollection<ws> SearchResults { get; set; } = new ObservableCollection<ws>();
- private async void btnSearch_Click(object sender, RoutedEventArgs e)
- {
- q = asbWebSearch.Text.Trim();
- var res = await MakeRequest();
- for (int i = 0; i < res.Count(); i++)
- {
- WebSer webser = res.ElementAt(i);
- SearchResults.Add(new ws { WSer = webser });
- }
- }
- async Task<IEnumerable<WebSer>> MakeRequest()
- {
- List<WebSer> sres = new List<WebSer>();
- var client = new HttpClient();
-
- client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "<Your Key>");
-
- string count = "10";
- string offset = "0";
- string mkt = "en-us";
- var WebSearchEndPoint = "https://api.cognitive.microsoft.com/bing/v5.0/search?";
- var result = await client.GetAsync(string.Format("{0}q={1}&count={2}&offset={3}&mkt={4}", WebSearchEndPoint, WebUtility.UrlEncode(q), count, offset, mkt));
- result.EnsureSuccessStatusCode();
- var json = await result.Content.ReadAsStringAsync();
- dynamic data = JObject.Parse(json);
- for (int i = 0; i < 10; i++)
- {
- sres.Add(new WebSer
- {
- Id = data.webPages.value[i].id,
- Name = data.webPages.value[i].name,
- Url = data.webPages.value[i].url,
- Snippet = data.webPages.value[i].snippet,
- DisplayUrl = data.webPages.value[i].displayUrl
- });
- }
- return sres;
- }
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,
- Cognitive Service Bing News Search API Using UWP With Azure, XAML And C#
- Cognitive Service Bing AutoSuggest API Using UWP With Azure, XAML And C#
- Multiple People Emotions In UWP With Cognitive Service Emotion API, Azure, XAML And C#
- Cognitive Service Emotion API In UWP With Azure, XAML And C#
- Retrieving Face Attributes Using Cognitive Service Face API In UWP With Azure, XAML And C#
- Cognitive Service Face API, Using UWP With Azure, XAML And C#