Xamarin.Forms - Bing Web Search Using Cognitive Service

Introduction
 
Xamarin.Forms - Bing Web Search Using Cognitive Service 
 
Xamarin.Forms code runs on multiple platforms - each of which has its own filesystem. This means that reading and writing files is most easily done using the native file APIs on each platform. Alternatively, embedded resources are a simpler solution to distribute data files with an app.
 
Cognitive Services
Xamarin.Forms - Bing Web Search Using Cognitive Service
Xamarin and Cognitive Services together can infuse your apps, websites, and bots with intelligent algorithms to see, hear, speak, understand and interpret your user needs through natural methods of communication. Also, they help you transform your business with AI today.
 
Use AI to solve business problems
  • Vision
  • Speech
  • Knowledge
  • Search
  • Language
Bing Web Search
  1. Bing Web Search API is a RESTful service that provides an experience similar to Bing by returning the search results that Bing determines are relevant to a user's questions. Search results are easily configured to include web pages, images, videos, news, translations, and more.
  2. Bing Web Search API is easy to call from any programming language that can make HTTP requests and parse JSON responses.
Prerequisites
  • Visual Studio 2017 or Later (Windows or Mac)
  • Bing Search API Key
Setting up a Xamarin.Forms Project
 
Start by creating a new Xamarin.Forms project. You’ll learn more by going through the steps yourself.
 
Visual Studio 2019 has more options in the opening window. Clone or check out the code from any repository or, open a project or solution for your computer.
 
Now, you need to click "Create a new project".
 
Xamarin.Forms - Bing Web Search Using Cognitive Service 
 
Now, filter by Project Type: Mobile
 
Choose the Mobile App (Xamarin. forms) project under C# and Mobile.
 
Xamarin.Forms - Bing Web Search Using Cognitive Service 
 
Name your app. You probably want your project and solution to use the same name as your app. Put it on your preferred location for projects and click "Create".
 
Xamarin.Forms - Bing Web Search Using Cognitive Service 
 
Now, select the blank app and target platforms - Android, iOS and Windows (UWP).
 
Xamarin.Forms - Bing Web Search Using Cognitive Service
 
Subsequently, go to the solution. In there, you get all the files and sources of your project (.NET Standard). Now, select XAML page and double-click to open the MainPage.Xaml page.
 
You now have a basic Xamarin.Forms app. Click the Play button to try it out.
 
Xamarin.Forms - Bing Web Search Using Cognitive Service
 
Get Bing Search API Key
 
In this step, get Bing Search API Key. Go to the following link.
 
https://azure.microsoft.com/en-in/services/cognitive-services/
 
Click "Try Cognitive Services for free".
 
Xamarin.Forms - Bing Web Search Using Cognitive Service 

Now, you can choose Bing Search APIs under Search APIs. Afterward, click "Get API Key".
 
Xamarin.Forms - Bing Web Search Using Cognitive Service 
Read the terms, and select your country/region. Afterward, click "Next".
 
Xamarin.Forms - Bing Web Search Using Cognitive Service
 
Now, log in using your preferred account.
 
Xamarin.Forms - Bing Web Search Using Cognitive Service
 
Now, the API key is activated. You can use it now.
 
Note
The trial key is available only for 7 days.
 
Xamarin.Forms - Bing Web Search Using Cognitive Service
 
Setting up the User Interface
 
Go to MainPage.Xaml and write the following code.
 
MainPage.xaml
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"  
  3.              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"  
  4.              xmlns:local="clr-namespace:XamarinCognitive"  
  5.              x:Class="XamarinCognitive.MainPage">  
  6.   
  7.     <StackLayout>  
  8.         <StackLayout>  
  9.             <StackLayout HorizontalOptions="Center" VerticalOptions="Start">  
  10.                 <Image x:Name="imgBanner" Source="banner.png" ></Image>  
  11.                 <Image Margin="0,0,0,10" x:Name="imgEmail" HeightRequest="100" Source="cognitiveservice.png" ></Image>  
  12.                 <Label Margin="0,0,0,10" Text="Bing Web Search" FontAttributes="Bold" FontSize="Large" TextColor="Gray" HorizontalTextAlignment="Center" ></Label>  
  13.                 <Entry x:Name="txtSearch" Placeholder="Type here.."></Entry>  
  14.                 <Button x:Name="btnSearch" WidthRequest="50" Text="Search" Clicked="BtnSearch_Clicked" />  
  15.                 <StackLayout HorizontalOptions="CenterAndExpand" Margin="10,0,0,10">  
  16.                     <ListView x:Name="listWebpage">  
  17.                           
  18.                     </ListView>  
  19.                 </StackLayout>  
  20.             </StackLayout>  
  21.         </StackLayout>  
  22.     </StackLayout>  
  23.   
  24. </ContentPage>   
Click the Play button to try it out.
 
Xamarin.Forms - Bing Web Search Using Cognitive Service
 
NuGet Packages
 
Now, add the following NuGet Package.
  1. Newtonsoft.Json
Add Newtonsoft.Json NuGet
 
Go to Solution Explorer and select your solution. Right-click and select "Manage NuGet Packages for Solution". Search for "Newtonsoft.Json" and add Package. Remember to install it for each project (.NET Standard, Android, iOS, and UWP).
 
Create a Model
 
In this step, you can create a model for deserializing your response.
 
ResponseModel.cs
  1. namespace XamarinCognitive  
  2. {  
  3.     public class ResponseModel  
  4.     {  
  5.         public string _type { getset; }  
  6.         public QueryContext queryContext { getset; }  
  7.         public WebPages webPages { getset; }  
  8.         public Entities entities { getset; }  
  9.         public RelatedSearches relatedSearches { getset; }  
  10.         public Videos videos { getset; }  
  11.         public RankingResponse rankingResponse { getset; }  
  12.     }  
  13.     public class QueryContext  
  14.     {  
  15.         public string originalQuery { getset; }  
  16.     }  
  17.   
  18.     public class About  
  19.     {  
  20.         public string name { getset; }  
  21.     }  
  22.   
  23.     public class DeepLink  
  24.     {  
  25.         public string name { getset; }  
  26.         public string url { getset; }  
  27.         public string snippet { getset; }  
  28.     }  
  29.   
  30.     public class License  
  31.     {  
  32.         public string name { getset; }  
  33.         public string url { getset; }  
  34.     }  
  35.   
  36.     public class SnippetAttribution  
  37.     {  
  38.         public License license { getset; }  
  39.         public string licenseNotice { getset; }  
  40.     }  
  41.   
  42.     public class Item  
  43.     {  
  44.         public string _type { getset; }  
  45.         public string text { getset; }  
  46.         public string url { getset; }  
  47.     }  
  48.   
  49.     public class ListItem  
  50.     {  
  51.         public List<Item> items { getset; }  
  52.     }  
  53.   
  54.     public class ListData  
  55.     {  
  56.         public List<ListItem> listItems { getset; }  
  57.     }  
  58.   
  59.     public class Section  
  60.     {  
  61.         public string _type { getset; }  
  62.         public string name { getset; }  
  63.         public string siteName { getset; }  
  64.         public string description { getset; }  
  65.         public List<ListData> listData { getset; }  
  66.     }  
  67.   
  68.     public class RichCaption  
  69.     {  
  70.         public string _type { getset; }  
  71.         public List<Section> sections { getset; }  
  72.     }  
  73.   
  74.     public class SearchTag  
  75.     {  
  76.         public string name { getset; }  
  77.         public string content { getset; }  
  78.     }  
  79.   
  80.     public class Value  
  81.     {  
  82.         public string id { getset; }  
  83.         public string name { getset; }  
  84.         public string url { getset; }  
  85.         public List<About> about { getset; }  
  86.         public bool isFamilyFriendly { getset; }  
  87.         public string displayUrl { getset; }  
  88.         public string snippet { getset; }  
  89.         public List<DeepLink> deepLinks { getset; }  
  90.         public DateTime dateLastCrawled { getset; }  
  91.         public string language { getset; }  
  92.         public bool isNavigational { getset; }  
  93.         public SnippetAttribution snippetAttribution { getset; }  
  94.         public RichCaption richCaption { getset; }  
  95.         public List<SearchTag> searchTags { getset; }  
  96.     }  
  97.   
  98.     public class WebPages  
  99.     {  
  100.         public string webSearchUrl { getset; }  
  101.         public int totalEstimatedMatches { getset; }  
  102.         public List<Value> value { getset; }  
  103.     }  
  104.   
  105.     public class License2  
  106.     {  
  107.         public string name { getset; }  
  108.         public string url { getset; }  
  109.     }  
  110.   
  111.     public class ContractualRule  
  112.     {  
  113.         public string _type { getset; }  
  114.         public string targetPropertyName { getset; }  
  115.         public bool mustBeCloseToContent { getset; }  
  116.         public License2 license { getset; }  
  117.         public string licenseNotice { getset; }  
  118.         public string text { getset; }  
  119.         public string url { getset; }  
  120.     }  
  121.   
  122.     public class Provider  
  123.     {  
  124.         public string _type { getset; }  
  125.         public string url { getset; }  
  126.     }  
  127.   
  128.     public class Image  
  129.     {  
  130.         public string name { getset; }  
  131.         public string thumbnailUrl { getset; }  
  132.         public List<Provider> provider { getset; }  
  133.         public string hostPageUrl { getset; }  
  134.         public int width { getset; }  
  135.         public int height { getset; }  
  136.         public int sourceWidth { getset; }  
  137.         public int sourceHeight { getset; }  
  138.     }  
  139.   
  140.     public class EntityPresentationInfo  
  141.     {  
  142.         public string entityScenario { getset; }  
  143.         public List<string> entityTypeHints { getset; }  
  144.         public string entityTypeDisplayHint { getset; }  
  145.     }  
  146.   
  147.     public class Value2  
  148.     {  
  149.         public string id { getset; }  
  150.         public List<ContractualRule> contractualRules { getset; }  
  151.         public string webSearchUrl { getset; }  
  152.         public string name { getset; }  
  153.         public string url { getset; }  
  154.         public Image image { getset; }  
  155.         public string description { getset; }  
  156.         public EntityPresentationInfo entityPresentationInfo { getset; }  
  157.         public string bingId { getset; }  
  158.     }  
  159.   
  160.     public class Entities  
  161.     {  
  162.         public List<Value2> value { getset; }  
  163.     }  
  164.   
  165.     public class Value3  
  166.     {  
  167.         public string text { getset; }  
  168.         public string displayText { getset; }  
  169.         public string webSearchUrl { getset; }  
  170.     }  
  171.   
  172.     public class RelatedSearches  
  173.     {  
  174.         public string id { getset; }  
  175.         public List<Value3> value { getset; }  
  176.     }  
  177.   
  178.     public class Publisher  
  179.     {  
  180.         public string name { getset; }  
  181.     }  
  182.   
  183.     public class Thumbnail  
  184.     {  
  185.         public int width { getset; }  
  186.         public int height { getset; }  
  187.     }  
  188.   
  189.     public class Value4  
  190.     {  
  191.         public string webSearchUrl { getset; }  
  192.         public string name { getset; }  
  193.         public string description { getset; }  
  194.         public string thumbnailUrl { getset; }  
  195.         public DateTime datePublished { getset; }  
  196.         public List<Publisher> publisher { getset; }  
  197.         public bool isAccessibleForFree { getset; }  
  198.         public string contentUrl { getset; }  
  199.         public string hostPageUrl { getset; }  
  200.         public string encodingFormat { getset; }  
  201.         public string hostPageDisplayUrl { getset; }  
  202.         public int width { getset; }  
  203.         public int height { getset; }  
  204.         public string duration { getset; }  
  205.         public string motionThumbnailUrl { getset; }  
  206.         public string embedHtml { getset; }  
  207.         public bool allowHttpsEmbed { getset; }  
  208.         public int viewCount { getset; }  
  209.         public Thumbnail thumbnail { getset; }  
  210.         public bool allowMobileEmbed { getset; }  
  211.         public bool isSuperfresh { getset; }  
  212.     }  
  213.   
  214.     public class Videos  
  215.     {  
  216.         public string id { getset; }  
  217.         public string readLink { getset; }  
  218.         public string webSearchUrl { getset; }  
  219.         public bool isFamilyFriendly { getset; }  
  220.         public List<Value4> value { getset; }  
  221.         public string scenario { getset; }  
  222.     }  
  223.   
  224.     public class Value5  
  225.     {  
  226.         public string id { getset; }  
  227.     }  
  228.   
  229.     public class Item2  
  230.     {  
  231.         public string answerType { getset; }  
  232.         public int resultIndex { getset; }  
  233.         public Value5 value { getset; }  
  234.     }  
  235.   
  236.     public class Mainline  
  237.     {  
  238.         public List<Item2> items { getset; }  
  239.     }  
  240.   
  241.     public class Value6  
  242.     {  
  243.         public string id { getset; }  
  244.     }  
  245.   
  246.     public class Item3  
  247.     {  
  248.         public string answerType { getset; }  
  249.         public int? resultIndex { getset; }  
  250.         public Value6 value { getset; }  
  251.     }  
  252.   
  253.     public class Sidebar  
  254.     {  
  255.         public List<Item3> items { getset; }  
  256.     }  
  257.   
  258.     public class RankingResponse  
  259.     {  
  260.         public Mainline mainline { getset; }  
  261.         public Sidebar sidebar { getset; }  
  262.     }  
  263.   
  264.       
  265. }  
Bing Web Search
 
In this step, write the following code for Bing Web Search.
  
MainPage.xaml.cs
  1. using System.IO;  
  2. using System.Linq;  
  3. using System.Net;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using Xamarin.Forms;  
  7. using Newtonsoft.Json;  
  8. namespace XamarinCognitive  
  9. {  
  10.     public partial class MainPage : ContentPage  
  11.     {  
  12.         public static string APIKey = "a30148ca5fc*********49b554fc4f683";  
  13.         public static string baseURl = "https://api.cognitive.microsoft.com/bing/v7.0/search";  
  14.         struct SearchResult  
  15.         {  
  16.             public String jsonResult;  
  17.             public Dictionary<String, String> relevantHeaders;  
  18.         }  
  19.   
  20.         List<string> webResults = new List<string>();  
  21.         public MainPage()  
  22.         {  
  23.             InitializeComponent();  
  24.         }  
  25.   
  26.         private void BtnSearch_Clicked(object sender, EventArgs e)  
  27.         {  
  28.             SearchResult bingResult=BingWebSearch(txtSearch.Text);  
  29.             var res = JsonConvert.DeserializeObject<ResponseModel>(bingResult.jsonResult);  
  30.             for(int i=0;i<res.webPages.value.Count;i++)  
  31.             {  
  32.                 webResults.Add(res.webPages.value[i].name);  
  33.             }  
  34.             listWebpage.ItemsSource = webResults;  
  35.         }  
  36.   
  37.         //Bing Web Search   
  38.         static SearchResult BingWebSearch(string searchQuery)  
  39.         {  
  40.             var uriQuery = baseURl + "?q=" + Uri.EscapeDataString(searchQuery);  
  41.             WebRequest request = HttpWebRequest.Create(uriQuery);  
  42.             request.Headers["Ocp-Apim-Subscription-Key"] = APIKey;  
  43.             HttpWebResponse response = (HttpWebResponse)request.GetResponseAsync().Result;  
  44.             string json = new StreamReader(response.GetResponseStream()).ReadToEnd();  
  45.             var searchResult = new SearchResult()  
  46.             {  
  47.                 jsonResult = json,  
  48.                 relevantHeaders = new Dictionary<String, String>()  
  49.             };  
  50.             foreach (String header in response.Headers)  
  51.             {  
  52.                 if (header.StartsWith("BingAPIs-") || header.StartsWith("X-MSEdge-"))  
  53.                     searchResult.relevantHeaders[header] = response.Headers[header];  
  54.             }  
  55.             return searchResult;  
  56.         }  
  57.     }  
  58. }  
Click the Play button to try it out.
 
Android 
 
Xamarin.Forms - Bing Web Search Using Cognitive Service
 
UWP 
 
Xamarin.Forms - Bing Web Search Using Cognitive Service
 
I hope you have understood how to search web pages using Cognitive Service Bing Search API in Xamarin.Forms. Thanks for reading. Please share your comments and feedback.
 
Happy Coding :)


Similar Articles