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. <StackLayout>
  7. <StackLayout>
  8. <StackLayout HorizontalOptions="Center" VerticalOptions="Start">
  9. <Image x:Name="imgBanner" Source="banner.png" ></Image>
  10. <Image Margin="0,0,0,10" x:Name="imgEmail" HeightRequest="100" Source="cognitiveservice.png" ></Image>
  11. <Label Margin="0,0,0,10" Text="Bing Web Search" FontAttributes="Bold" FontSize="Large" TextColor="Gray" HorizontalTextAlignment="Center" ></Label>
  12. <Entry x:Name="txtSearch" Placeholder="Type here.."></Entry>
  13. <Button x:Name="btnSearch" WidthRequest="50" Text="Search" Clicked="BtnSearch_Clicked" />
  14. <StackLayout HorizontalOptions="CenterAndExpand" Margin="10,0,0,10">
  15. <ListView x:Name="listWebpage">
  16. </ListView>
  17. </StackLayout>
  18. </StackLayout>
  19. </StackLayout>
  20. </StackLayout>
  21. </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 { get; set; }
  6. public QueryContext queryContext { get; set; }
  7. public WebPages webPages { get; set; }
  8. public Entities entities { get; set; }
  9. public RelatedSearches relatedSearches { get; set; }
  10. public Videos videos { get; set; }
  11. public RankingResponse rankingResponse { get; set; }
  12. }
  13. public class QueryContext
  14. {
  15. public string originalQuery { get; set; }
  16. }
  17. public class About
  18. {
  19. public string name { get; set; }
  20. }
  21. public class DeepLink
  22. {
  23. public string name { get; set; }
  24. public string url { get; set; }
  25. public string snippet { get; set; }
  26. }
  27. public class License
  28. {
  29. public string name { get; set; }
  30. public string url { get; set; }
  31. }
  32. public class SnippetAttribution
  33. {
  34. public License license { get; set; }
  35. public string licenseNotice { get; set; }
  36. }
  37. public class Item
  38. {
  39. public string _type { get; set; }
  40. public string text { get; set; }
  41. public string url { get; set; }
  42. }
  43. public class ListItem
  44. {
  45. public List<Item> items { get; set; }
  46. }
  47. public class ListData
  48. {
  49. public List<ListItem> listItems { get; set; }
  50. }
  51. public class Section
  52. {
  53. public string _type { get; set; }
  54. public string name { get; set; }
  55. public string siteName { get; set; }
  56. public string description { get; set; }
  57. public List<ListData> listData { get; set; }
  58. }
  59. public class RichCaption
  60. {
  61. public string _type { get; set; }
  62. public List<Section> sections { get; set; }
  63. }
  64. public class SearchTag
  65. {
  66. public string name { get; set; }
  67. public string content { get; set; }
  68. }
  69. public class Value
  70. {
  71. public string id { get; set; }
  72. public string name { get; set; }
  73. public string url { get; set; }
  74. public List<About> about { get; set; }
  75. public bool isFamilyFriendly { get; set; }
  76. public string displayUrl { get; set; }
  77. public string snippet { get; set; }
  78. public List<DeepLink> deepLinks { get; set; }
  79. public DateTime dateLastCrawled { get; set; }
  80. public string language { get; set; }
  81. public bool isNavigational { get; set; }
  82. public SnippetAttribution snippetAttribution { get; set; }
  83. public RichCaption richCaption { get; set; }
  84. public List<SearchTag> searchTags { get; set; }
  85. }
  86. public class WebPages
  87. {
  88. public string webSearchUrl { get; set; }
  89. public int totalEstimatedMatches { get; set; }
  90. public List<Value> value { get; set; }
  91. }
  92. public class License2
  93. {
  94. public string name { get; set; }
  95. public string url { get; set; }
  96. }
  97. public class ContractualRule
  98. {
  99. public string _type { get; set; }
  100. public string targetPropertyName { get; set; }
  101. public bool mustBeCloseToContent { get; set; }
  102. public License2 license { get; set; }
  103. public string licenseNotice { get; set; }
  104. public string text { get; set; }
  105. public string url { get; set; }
  106. }
  107. public class Provider
  108. {
  109. public string _type { get; set; }
  110. public string url { get; set; }
  111. }
  112. public class Image
  113. {
  114. public string name { get; set; }
  115. public string thumbnailUrl { get; set; }
  116. public List<Provider> provider { get; set; }
  117. public string hostPageUrl { get; set; }
  118. public int width { get; set; }
  119. public int height { get; set; }
  120. public int sourceWidth { get; set; }
  121. public int sourceHeight { get; set; }
  122. }
  123. public class EntityPresentationInfo
  124. {
  125. public string entityScenario { get; set; }
  126. public List<string> entityTypeHints { get; set; }
  127. public string entityTypeDisplayHint { get; set; }
  128. }
  129. public class Value2
  130. {
  131. public string id { get; set; }
  132. public List<ContractualRule> contractualRules { get; set; }
  133. public string webSearchUrl { get; set; }
  134. public string name { get; set; }
  135. public string url { get; set; }
  136. public Image image { get; set; }
  137. public string description { get; set; }
  138. public EntityPresentationInfo entityPresentationInfo { get; set; }
  139. public string bingId { get; set; }
  140. }
  141. public class Entities
  142. {
  143. public List<Value2> value { get; set; }
  144. }
  145. public class Value3
  146. {
  147. public string text { get; set; }
  148. public string displayText { get; set; }
  149. public string webSearchUrl { get; set; }
  150. }
  151. public class RelatedSearches
  152. {
  153. public string id { get; set; }
  154. public List<Value3> value { get; set; }
  155. }
  156. public class Publisher
  157. {
  158. public string name { get; set; }
  159. }
  160. public class Thumbnail
  161. {
  162. public int width { get; set; }
  163. public int height { get; set; }
  164. }
  165. public class Value4
  166. {
  167. public string webSearchUrl { get; set; }
  168. public string name { get; set; }
  169. public string description { get; set; }
  170. public string thumbnailUrl { get; set; }
  171. public DateTime datePublished { get; set; }
  172. public List<Publisher> publisher { get; set; }
  173. public bool isAccessibleForFree { get; set; }
  174. public string contentUrl { get; set; }
  175. public string hostPageUrl { get; set; }
  176. public string encodingFormat { get; set; }
  177. public string hostPageDisplayUrl { get; set; }
  178. public int width { get; set; }
  179. public int height { get; set; }
  180. public string duration { get; set; }
  181. public string motionThumbnailUrl { get; set; }
  182. public string embedHtml { get; set; }
  183. public bool allowHttpsEmbed { get; set; }
  184. public int viewCount { get; set; }
  185. public Thumbnail thumbnail { get; set; }
  186. public bool allowMobileEmbed { get; set; }
  187. public bool isSuperfresh { get; set; }
  188. }
  189. public class Videos
  190. {
  191. public string id { get; set; }
  192. public string readLink { get; set; }
  193. public string webSearchUrl { get; set; }
  194. public bool isFamilyFriendly { get; set; }
  195. public List<Value4> value { get; set; }
  196. public string scenario { get; set; }
  197. }
  198. public class Value5
  199. {
  200. public string id { get; set; }
  201. }
  202. public class Item2
  203. {
  204. public string answerType { get; set; }
  205. public int resultIndex { get; set; }
  206. public Value5 value { get; set; }
  207. }
  208. public class Mainline
  209. {
  210. public List<Item2> items { get; set; }
  211. }
  212. public class Value6
  213. {
  214. public string id { get; set; }
  215. }
  216. public class Item3
  217. {
  218. public string answerType { get; set; }
  219. public int? resultIndex { get; set; }
  220. public Value6 value { get; set; }
  221. }
  222. public class Sidebar
  223. {
  224. public List<Item3> items { get; set; }
  225. }
  226. public class RankingResponse
  227. {
  228. public Mainline mainline { get; set; }
  229. public Sidebar sidebar { get; set; }
  230. }
  231. }
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. List<string> webResults = new List<string>();
  20. public MainPage()
  21. {
  22. InitializeComponent();
  23. }
  24. private void BtnSearch_Clicked(object sender, EventArgs e)
  25. {
  26. SearchResult bingResult=BingWebSearch(txtSearch.Text);
  27. var res = JsonConvert.DeserializeObject<ResponseModel>(bingResult.jsonResult);
  28. for(int i=0;i<res.webPages.value.Count;i++)
  29. {
  30. webResults.Add(res.webPages.value[i].name);
  31. }
  32. listWebpage.ItemsSource = webResults;
  33. }
  34. //Bing Web Search
  35. static SearchResult BingWebSearch(string searchQuery)
  36. {
  37. var uriQuery = baseURl + "?q=" + Uri.EscapeDataString(searchQuery);
  38. WebRequest request = HttpWebRequest.Create(uriQuery);
  39. request.Headers["Ocp-Apim-Subscription-Key"] = APIKey;
  40. HttpWebResponse response = (HttpWebResponse)request.GetResponseAsync().Result;
  41. string json = new StreamReader(response.GetResponseStream()).ReadToEnd();
  42. var searchResult = new SearchResult()
  43. {
  44. jsonResult = json,
  45. relevantHeaders = new Dictionary<String, String>()
  46. };
  47. foreach (String header in response.Headers)
  48. {
  49. if (header.StartsWith("BingAPIs-") || header.StartsWith("X-MSEdge-"))
  50. searchResult.relevantHeaders[header] = response.Headers[header];
  51. }
  52. return searchResult;
  53. }
  54. }
  55. }
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 :)