New Fresh deep-dives on cloud, AI, mobile & web now publish on blog.msdevbuild.com Read the latest → Install the app
Azure

Building Xamarin Mobile Application with Bing Web Search using Cognitive Services

By   Saturday, March 17, 2018 comments
reads
React:
The Bing Web Search API provides an experience similar to Bing.com/Search by returning search results that Bing determines are relevant to the user's query. The API results include Web pages, images, videos, news, and entities, along with related search queries, spelling corrections, time zones, unit conversion, translations, and calculations. The web Search API uses JSON format for data exchange, and API Keys for authentication.



In this article, I will show how to generate Bing Search subscription key and integrate into the Xamarin application.

Register Bing Search in Azure Portal:

You need to create an Azure account and generate subscription key for implementation to the Xamarin Mobile application.

Step 1: 

 Sign in to Azure portal .

Step 2: 

Create On “+ Create a resource “> Under Azure Marketplace, select AI + Cognitive Services and discover the list of available APIs. > Select “ Bing Search v7 APIs”


Step 3: 

on the create page, Provide the name, pricing, resource group a click on Create


Step 4: 

 wait for few seconds, After the Cognitive Services account is successfully deployed, click the notification or tile in the dashboard to view the account information. You can copy the Endpoint URL in the Overview section and keys in the Keys section to start making API calls in our Xamarin applications.


Create Bing Web Search Xamarin Application:

Let's start with creating a new Xamarin Forms Project using Visual Studio. Open Run >> Type “Devenev.Exe” and enter >> New Project (Ctrl+Shift+N) >> select Blank Xaml App (Xamarin.Forms) template.


It will automatically create multiple projects, like .NET Standard, Android, iOS, and UWP.

Install Newtonsoft.Json :

Bing Web Search API will return Json object value so make sure you have added the Newtonsoft JSON NuGet Package to your all project. Right Click on Solution > Manage Nuget Package > Install Newtonsoft Json


Install Microsoft.Csharp :

This steps is optional, if you get Error "Microsoft.CSharp.RuntimeBinder.Binder.Convert" not found by the compiler for dynamic type so adding a reference as Microsoft.CSharp to the Dotnet Standard /PCL project , issue will get resolve .


Design View:

After successfully install above two nuget package. Let start design UI design from Dot Standard /PCL project. In PCL Project > Open MainPage.Xaml page and add design Entry and list view control with item template in Xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:XamarinBingWebSearch"
:Class="XamarinBingWebSearch.MainPage">
<ContentPage.Content>
<StackLayout>
<Label Text="Search" ></Label>
<Entry x:Name="entrysearch" Placeholder="Type Your text" TextChanged="OnTextChangesEvent" />
<ListView x:Name="lstwebsearch" BackgroundColor="Azure">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Vertical">
<Label Text="{Binding Snippet}">
</Label>
<Label Text="{Binding DisplayUrl}">
</Label>
<Label Text="{Binding Name}" TextColor="Gray"></Label>
<Label Text="{Binding Url}" TextColor="Gray"></Label>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage.Content>
</ContentPage>

Bing web search will return ID ,Name, URL ,Snippet and DispalyUrl so create model class for web search .

namespace XamarinBingWebSearch.Model
{
public class WebSearch
{
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; }
}
}

Configure the project:

We need to get web search result so send a GET request to the following endpoint and replace subscription key from Mainpage.xaml.cs
private string WebSearchEndPoint = "https://api.cognitive.microsoft.com/bing/v7.0/search?";
public HttpClient WebSearchClient
{
get;
set;
}
public MainPage()
{
InitializeComponent();
WebSearchClient = new HttpClient();
WebSearchClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "YOUR API KEY");
}

Get and Parse Json Data:

HttpClient class provides a base class for get/Post the HTTP requests/responses from a URL. It is a supported async feature of .NET framework. HttpClient is able to process multiple concurrent requests. The following code showing get all Json data using Bing web Search API url and Parse the json and binding into the list view for display search result

private async void OnTextChangesEvent(object sender, TextChangedEventArgs e)
{
try
{
if (entrysearch != null)
lstwebsearch.ItemsSource = await SearchBingWeb(entrysearch.Text);
}
catch (Exception)
{

}

}
async Task<IEnumerable<WebSearch>> SearchBingWeb(string searchText)
{
List<WebSearch> websearch = new List<WebSearch>();
string count = "10";
string offset = "0";
string mkt = "en-us";
var result = await RequestAndAutoRetryWhenThrottled(() => WebSearchClient.GetAsync(string.Format("{0}q={1}&count={2}&offset={3}&mkt={4}", WebSearchEndPoint, WebUtility.UrlEncode(searchText), count, offset, mkt)));
result.EnsureSuccessStatusCode();
var json = await result.Content.ReadAsStringAsync();
dynamic data = JObject.Parse(json);
for (int i = 0; i < 10; i++)
{
websearch.Add(new WebSearch
{
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 websearch;
}
private async Task<HttpResponseMessage> RequestAndAutoRetryWhenThrottled(Func<Task<HttpResponseMessage>> action)
{
int retriesLeft = 6;
int delay = 500;
HttpResponseMessage response = null;
while (true)
{
response = await action();
if ((int)response.StatusCode == 429 && retriesLeft > 0)
{
await Task.Delay(delay);
retriesLeft--;
delay *= 2;
continue;
}
else
{
break;
}
}
return response;
}

Run the Application:

We have completed the coding now start run the application so you can select the platform iOS,Android , Windows and Click on Run (f5) the application .



You can find the source code at C# Corner attachment and Github XamarinBingWebSearch repository as Microsoft-Cognitive-Service.



Summary

In this article, you learned about how to generate Bing search subscription key and integrate into the Bing web search Xamarin application. If you have any questions/ feedback/ issues, please write in the comment box.


SJ
Suthahar Jegatheesan

Cloud, AI & Mobile Solutions Architect · 18+ years across Azure, Google Cloud and Firebase, C#, Python, .NET MAUI and Flutter. Author of the Xamarin Q&A Book.

More in this series

2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Nice blog..i was really impressed by seeing this blog, it was very interesting and it is very useful for me.also the information which you have mentioned here is correct and impressive. Really appreciate.
    Hire Xamarin Developer
    Xamarin Development Company

    ReplyDelete

sponsored

What Colleagues Say

“Suthahar is one of the most thorough and knowledgeable cloud architects I’ve worked with. His depth on Azure and ability to make complex mobile solutions work cross-platform is remarkable. He always delivers beyond expectations.”

AT Arun T. Senior Engineering Manager · Direct Manager

“I’ve followed Suthahar’s MSDEVBUILD blog for years — practical, deep, always current. Working alongside him confirmed what I suspected: he’s as sharp in person as on paper, and a genuinely generous mentor and architect.”

RK Rajesh K. Lead Developer · Mindtree

Certifications & Recognition

AZ-300 · Azure Architect Technologies AZ-301 · Azure Architect Design AZ-104 · Azure Administrator Associate AI-100 · Designing Azure AI Solutions DP-900 · Azure Data Fundamentals MCPD · Windows Phone Certified SAFe® 4 Scrum Master

Technical Expertise

☁ Cloud Platforms Microsoft Azure — Expert · 18 yrs App Services · AKS · Functions · Cosmos DB · APIM · Entra ID AWS & Google Cloud — Advanced
πŸ€– AI & Automation Azure OpenAI / GenAI — Advanced · 5 yrs RAG Pipelines · Bot Framework · Cognitive Services · Vision & Speech AI · ML.NET
πŸ“± Mobile Architecture .NET MAUI & Xamarin — Expert · 12 yrs Flutter · Native iOS/Android · Offline-First · Secure Storage & Auth
πŸ”’ Identity & Security Microsoft Entra ID — Expert OAuth 2.0 · OIDC · Zero Trust · Conditional Access · RBAC · Key Vault

Speaking & Community

Microsoft User Group Malaysia Recurring speaker on Azure architecture, AI integration and .NET mobile development across Malaysia and APAC.
Global Azure Bootcamp — Chennai Presented “AI into Xamarin Mobile Apps” at GAB Chennai, part of the worldwide Global Azure community event.
AI & Azure OpenAI Community Events Workshops and live demos on RAG pipelines, AI agents and intelligent workflow automation since 2023.
Mobile & Cloud Workshops — Coimbatore Multi-day deep-dive sessions at GRG Computer Technology, KG Microsoft Innovation Center and RVS College of Arts and Science.
500+Blog Articles
50+Conference Talks
10K+Monthly Readers
30Public Repositories
3Continents Delivered
New home

MSDEVBUILD now publishes on blog.msdevbuild.com

Every new article lands there first — cloud and Azure, AI and GitHub Copilot, .NET MAUI and Flutter, web and Firebase. It installs as an app, opens like a native one and keeps working offline.

MSDEVBUILD Assistant Ask about Suthahar, Azure, AI or mentorship
Hi! I’m a simple FAQ bot for MSDEVBUILD. Tap a question below or type your own.