Similar Bing News Example

The Similar Documents Results Processor code example based on the received similar documents request, uses the first X metadata values to execute searches via the Bing News Search API.

The end-to-end mechanism returns news results related to the most frequent entities (metadata values) present in the user query results set:

Example
Copy
try
{
string accessKey = "yourBingNewsAPIKeyHere";
// Verify the endpoint URI. At this writing, only one endpoint is used for Bing
// search APIs. In the future, regional endpoints may be available. If you
// encounter unexpected authorization errors, double-check this value against
// the endpoint for your Bing News search instance in your Azure dashboard.
string uriBase = "https://api.cognitive.microsoft.com/bing/v7.0/news/search";

SimilarDocumentsRequest similarDocRequest;
string newsEntity = "DOCUMENTENTITIES";
try
{
similarDocRequest = SimilarDocumentsUtil.GetSimilarDocumentsRequestFromQuery(Results.ExecutedQuery);
if (similarDocRequest.CallerId != "News")
return;
}
catch (Exception e)
{
return;
}
if (!similarDocRequest.SimilarityProperties.ContainsKey(newsEntity) || similarDocRequest.SimilarityProperties[newsEntity].Count < 1)
return;
foreach (var bestEntity in similarDocRequest.SimilarityProperties[newsEntity])
{
if (bestEntity == null)
return;
var uriQuery = uriBase + "?q=" + Uri.EscapeDataString(bestEntity);
// Perform the Web request and get the response
WebRequest request = HttpWebRequest.Create(uriQuery);
request.Headers["Ocp-Apim-Subscription-Key"] = accessKey;
HttpWebResponse response = (HttpWebResponse)request.GetResponseAsync().Result;
string json = new StreamReader(response.GetResponseStream()).ReadToEnd();
var schema = new { Value = new[] { new { name = string.Empty, url = string.Empty, description = string.Empty } } };
var person = JsonConvert.DeserializeAnonymousType(json, schema);
if (Results.RelevantResults == null)
return;
if (person == null || person.Value == null)
return;
foreach (var value in person.Value.Take(1))
{
try
{
var title = value.name;
var summary = value.description;
var url = value.url;
var result = new SearchResult();

result.AddOrChangeProperty("title", bestEntity + ": " + title, typeof(System.String));
result.AddOrChangeProperty("clickUri", url, typeof(System.String));
result.AddOrChangeProperty("filetype", "html");

Results.RelevantResults.Add(result);
}
catch (Exception e)
{ //handle exception here }
}
}
}
catch (Exception ex)
{
return;
}

Referenced Assemblies

  • Newtonsoft.Json.dll
  • System.Net.Http.dll

Imported Namespaces

  • System
  • System.Net
  • Newtonsoft.Json