Getting the news

Using the Bing News Search API, we can search for news in several ways. There are three endpoints we can use for this API:

  • /news: Get top news articles, based on category
  • /news/search: Get news articles based on a search query
  • /news/trendingtopics: Get top trending news topics

In our smart-house application, we will add the first two, while we will only cover the last one theoretically.

Note

If you have not already done so, sign up for the Bing News Search API at https://portal.azure.com.

News from queries

A lot of the groundwork for query-based news searches has already been done in the web search sample. To search for news based on given queries, we need to add a new function in the BingSearch class.

Open the BingSearch.cs file and add a new function called SearchNews. This should accept a string and a SafeSearch parameter. The function should be marked as async, and return a Task<BingNewsResponse> object:

public async Task<BingNewsResponse> SearchNews(string query, SafeSearch safeSearch)
{
    string endpoint = string.Format("{0}{1}&safeSearch={2}&count=5&mkt=en-US","https://api.cognitive.microsoft.com/bing/v7.0/news/search?q=", query,safeSearch.ToString());

We will construct an endpoint consisting of the URL, the search query, and the safeSearch parameter. Notice how we specify the market, mkt, while limiting the count to 5. Both of these parameters will be described presently in this chapter.

The only required parameter is the query string, q. Apart from parameters described for web searches (setLang, textDecorations, and textFormat), we can also specify a parameter called originalImg. This is a Boolean value, which, if set to true, will provide a URL to the original image (for any image in the article). If that is set to false, which is the default, a URL for the thumbnail is provided.

With an endpoint in place, we can call the API:

    try {
        BingNewsResponse response = await _webRequest.MakeRequest<BingNewsResponse>(endpoint);

        return response;
    }
catch (Exception ex) {
        Debug.WriteLine(ex.Message);
    }

    return null;

We call MakeRequest, on the _webRequest object, passing on the endpoint as a parameter.

A successful call will result in a JSON response, which we deserialize into a BingNewsResponse object. This object needs to be created as a data contract.

The BingNewsResponse object will contain an array of news articles. Each item in this array will contain the article name, URL, image, description, publishing date, and more.

Note

For full details of each item in the news article array, visit https://msdn.microsoft.com/en-us/library/dn760793.aspx#newsarticle.

With that in place, we can head back into the BingSearchViewModel.cs file and modify the Search function. We do so by adding a case for BingSearchType.News inside the switch statement:

    case BingSearchType.News:
        var newsResponse = await _bingSearch.SearchNews(SearchQuery, SelectedSafeSearchFilter);
        ParseNewsResponse(newsResponse as BingNewsResponse);
        break;

A successful response will be parsed and displayed in the UI:

private void ParseNewsResponse(BingNewsResponse bingNewsResponse) {
    StringBuilder sb = new StringBuilder();

    foreach(Value news in bingNewsResponse.value) { 
        sb.AppendFormat("{0}
", news.name);
        sb.AppendFormat("Published: {0}
", news.datePublished);
        sb.AppendFormat("{0}

", news.description);
    }

    SearchResults = sb.ToString();
}

We are mostly interested in the news article name, the date it is published, and a description.

A good test run of this should present us with the following result:

News from queries

News from categories

When we want to get the top articles for certain categories, we go through a similar procedure as we did for regular news queries. The difference lies in the endpoint we construct.

Let's create a new function, SearchNewsCategory, in the BingSearch class:

public async Task<BingNewsResponse> SearchNewsCategory(string query)
{
    string endpoint = string.Format("{0}{1}&mkt=en-US", "https://api.cognitive.microsoft.com/bing/v5.0/news?category=", query);

Here, we have a category parameter, with the topic we wish to search for. This is an optional parameter. If it is empty, we will get the top news article for all categories.

For this search, we can specify two different markets, en-GB and en-US. Each of these comes with a list of pre-defined categories that are currently supported:

Note

For a complete list of supported categories, visit https://msdn.microsoft.com/en-us/library/dn760793.aspx#categoriesbymarket.

    try {
        BingNewsResponse response = await _webRequest.MakeRequest<BingNewsResponse>(endpoint);

        return response;
    }
catch (Exception ex) {
        Debug.WriteLine(ex.Message);
    }

    return null;

With the newly constructed endpoint, we call MakeRequest on the _webRequest object. This should result in the same response object as for regular news queries. In our ViewModel, we add a case for this search type in the Search function. With the response, we utilize the already created ParseNewsResponse to get the data we want.

Trending news

The search for trending news is only available for the en-US and zh-CN markets. To execute this search, make a request to the following URL: https://api.cognitive.microsoft.com/bing/v7.0/news/trendingtopics.

No parameters are required by this call, but you can add filters, such as the common filters we will discuss later. The only exception is the freshness filter, which will not work for this request.

A successful call to this endpoint will result in a TrendingTopicAnswer object that will contain an array of trending topics. Each item in this array will contain the following data:

Data field

Description

image

A link to a related image

isBreakingNews

A Boolean indicating whether this topic is considered breaking news

name

The title of the topic

query

A query string that will return this topic

webSearchUrl

A URL to the Bing search results for this topic

webSearchUrlPingSuffix

A query string fragment to identify the webSearchUrl

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.199.181