Introduction
The Bing News Search API returns a list of global news from a search query that can customize trending news from around the world by category and region. Results include information such as news title, description, URL, provider, and images. This API provides a list of categorized news searches by topics such as World, Politics, Sports, and more. The News Search API uses JSON format for data exchange and API keys for authentication.
In this article, I will show you how to generate the Bing Search subscription key and integrate it into the Xamarin application.
Register Bing Search on Azure Portal
You need to create an Azure account and generate a subscription key for implementation to the Xamarin Mobile application.
Step 2
Click “+ Create a resource “ and 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, and click on "Create".
Step 4
Wait for a 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 a Bing New 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 News Search API will return Json object value so make sure you have added the Newtonsoft JSON NuGet Package to your all projects. Right-click on Solution > Manage NuGet Package > Install Newtonsoft JSON.
Install Microsoft.Csharp
This step is optional. If you get an error "Microsoft.CSharp.RuntimeBinder.Binder.Convert not found by the compiler for dynamic type", adding a reference as Microsoft.CSharp to the .NET Standard /PCL project, the issue will get resolved.
Design View
After successfully installing the above two NuGet Packages, let us start designing the UI design from .NET Standard /PCL project. In PCL Project > open MainPage.Xaml page and add the design Entry and list view control with Item template in XAML.
- <?xml version="1.0" encoding="utf-8" ?>
- <ContentPage xmlns="https://xamarin.com/schemas/2014/forms"
- xmlns:x="https://schemas.microsoft.com/winfx/2009/xaml"
- xmlns:local="clr-namespace:XamarinBingNewsSearch"
- x:Class="XamarinBingNewsSearch.MainPage">
-
- <ContentPage.Content>
- <StackLayout>
- <Label Text="Search News" ></Label>
- <Entry x:Name="entrysearch" Placeholder="Type Your text" TextChanged="OnTextChangesEvent" />
- <ListView x:Name="lstnews" BackgroundColor="Azure">
- <ListView.ItemTemplate>
- <DataTemplate>
-
- <ViewCell>
- <StackLayout Orientation="Horizontal" >
-
- <StackLayout Orientation="Vertical">
- <Label Text="{Binding Title}" Font="18"></Label>
- <Label Text="{Binding Description}" TextColor="Gray"></Label>
- <Label Text="{Binding Provider}" TextColor="Gray"></Label>
- </StackLayout>
- <Image Source="{Binding ThumbnailUrl}" HeightRequest="30" WidthRequest="50" HorizontalOptions="EndAndExpand"></Image>
- </StackLayout>
- </ViewCell>
- </DataTemplate>
- </ListView.ItemTemplate>
-
- </ListView>
- </StackLayout>
- </ContentPage.Content>
- </ContentPage>
Bing News Search will return the title and description, URL, and images so create a model class for news articles.
- namespace XamarinBingNewsSearch.Model
- {
- public class NewsArticle
- {
- public string Title { get; set; }
- public string Description { get; set; }
- public string Url { get; set; }
- public string ThumbnailUrl { get; set; }
- public string Provider { get; set; }
- }
- }
Configure the project
We need to get the news only in the search results so send a GET request to the following endpoint and replace the subscription key from Mainpage.xaml.cs.
- private string NewsSearchEndPoint = "https://api.cognitive.microsoft.com/bing/v7.0/news/search";
- public HttpClient BingNewsSearchClient
- {
- get;
- set;
- }
- public MainPage()
- {
- InitializeComponent();
- BingNewsSearchClient = new HttpClient();
- BingNewsSearchClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "YOUR API KEY");
- }
Get and Parse Json Data
The 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 gets all the JSON data using Bing suggestions API URL, and parses the JSON and binds into the list view for autocomplete.
- private async void OnTextChangesEvent(object sender, TextChangedEventArgs e)
- {
- try
- {
- if(entrysearch!=null)
- lstautosug.ItemsSource = await GetAutoSuggestResults(this.entrysearch.Text);
- }
- catch (HttpRequestException)
- {
-
- }
-
- }
- public async Task<List<string>> GetAutoSuggestResults(string query)
- {
- List<string> suggestions = new List<string>();
- string market = "en-US";
- var result = await AutoSuggestionClient.GetAsync(string.Format("{0}/?q={1}&mkt={2}", AutoSuggestionEndPoint, WebUtility.UrlEncode(query), market));
- result.EnsureSuccessStatusCode();
- var json = await result.Content.ReadAsStringAsync();
- dynamic data = JObject.Parse(json);
- if (data.suggestionGroups != null && data.suggestionGroups.Count > 0 && data.suggestionGroups[0].searchSuggestions != null)
- {
- for (int i = 0; i < data.suggestionGroups[0].searchSuggestions.Count; i++)
- {
- suggestions.Add(data.suggestionGroups[0].searchSuggestions[i].displayText.Value);
- }
- }
- return suggestions;
- }
Run the Application
We have completed the coding. Now, let us run the application. You can select any platform iOS, Android, Windows. Now, click on Run (f5) the application.
You can find the source code in the attachment or on
the GitHub XamarinBingAutoSuggest repository as Microsoft-Cognitive-Service.
Summary
In this article, you learned how to generate Bing news Search subscription key and integrate it into the Xamarin application. If you have any questions/ feedback/ issues, please write in the comment box.