-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bing.csx
646 lines (526 loc) · 21.3 KB
/
bing.csx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
#r "nuget: Newtonsoft.Json, 13.0.1"
#r "nuget: System.Net.Http, 4.3.4"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Newtonsoft.Json;
public class Bing
{
readonly string apiKey = Environment.GetEnvironmentVariable("BingApiKey");
const string ENDPOINT = "https://api.bing.microsoft.com/";
// In production, make sure you're pulling the subscription key from secured storage.
string _subscriptionKey => apiKey;
readonly string _baseUri = $"{ENDPOINT}v7.0/search";
// The user's search string.
string searchString = "coronavirus vaccine";
// Bing uses the X-MSEdge-ClientID header to provide users with consistent
// behavior across Bing API calls. See the reference documentation
// for usage.
const string QUERY_PARAMETER = "?q="; // Required
const string MKT_PARAMETER = "&mkt="; // Strongly suggested
const string RESPONSE_FILTER_PARAMETER = "&responseFilter=";
const string COUNT_PARAMETER = "&count=";
const string OFFSET_PARAMETER = "&offset=";
const string FRESHNESS_PARAMETER = "&freshness=";
const string SAFE_SEARCH_PARAMETER = "&safeSearch=";
const string TEXT_DECORATIONS_PARAMETER = "&textDecorations=";
const string TEXT_FORMAT_PARAMETER = "&textFormat=";
const string ANSWER_COUNT = "&answerCount=";
const string PROMOTE = "&promote=";
public async Task RunAsync(params string[] args)
{
try
{
var max = args.FirstOrDefault(a => a.StartsWith("--max="));
if(args.Length > 0)
{
var aa = new List<string>(args);
if(max is not null)
{
aa.Remove(max);
max = max.Split('=').Last();
}
searchString = string.Join(' ', aa);
}
// Remember to encode query parameters like q, responseFilters, promote, etc.
var queryString = QUERY_PARAMETER + Uri.EscapeDataString(searchString);
queryString += MKT_PARAMETER + "en-us";
// queryString += RESPONSE_FILTER_PARAMETER + Uri.EscapeDataString("webpages,news");
queryString += TEXT_DECORATIONS_PARAMETER + Boolean.TrueString;
queryString += COUNT_PARAMETER + max;
//Console.WriteLine(queryString);
var response = await MakeRequestAsync(queryString);
// This example uses dictionaries instead of objects to access the response data.
var contentString = await response.Content.ReadAsStringAsync();
Dictionary<string, object> searchResponse = JsonConvert.DeserializeObject<Dictionary<string, object>>(contentString);
if (response.IsSuccessStatusCode)
{
PrintResponse(searchResponse);
}
else
{
PrintErrors(response.Headers, searchResponse);
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
// Console.WriteLine("\nPress ENTER to exit...");
// Console.ReadLine();
}
// Makes the request to the Web Search endpoint.
async Task<HttpResponseMessage> MakeRequestAsync(string queryString)
{
var client = new HttpClient();
// Request headers. The subscription key is the only required header but you should
// include User-Agent (especially for mobile), X-MSEdge-ClientID, X-Search-Location
// and X-MSEdge-ClientIP (especially for local aware queries).
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", _subscriptionKey);
return (await client.GetAsync(_baseUri + queryString));
}
// Prints the JSON response data for pole, mainline, and sidebar.
void PrintResponse(Dictionary<string, object> response)
{
// Console.WriteLine("The response contains the following answers:\n");
var ranking = response["rankingResponse"] as Newtonsoft.Json.Linq.JToken;
Newtonsoft.Json.Linq.JToken position;
if ((position = ranking["pole"]) != null)
{
// Console.WriteLine("Pole Position:\n");
DisplayAnswersByRank(position["items"], response);
}
if ((position = ranking["mainline"]) != null)
{
// Console.WriteLine("Mainline Position:\n");
DisplayAnswersByRank(position["items"], response);
}
// if ((position = ranking["sidebar"]) != null)
// {
// Console.WriteLine("Sidebar Position:\n");
// DisplayAnswersByRank(position["items"], response);
// }
}
// Displays each result based on ranking. Ranking contains the results for
// the pole, mainline, or sidebar section of the search results.
void DisplayAnswersByRank(Newtonsoft.Json.Linq.JToken items, Dictionary<string, object> response)
{
foreach (Newtonsoft.Json.Linq.JToken item in items)
{
var answerType = (string)item["answerType"];
Newtonsoft.Json.Linq.JToken index = -1;
// If the ranking item doesn't include an index of the result to
// display, then display all the results for that answer.
if ("WebPages" == answerType)
{
if ((index = item["resultIndex"]) == null)
{
DisplayAllWebPages(((Newtonsoft.Json.Linq.JToken)response["webPages"])["value"]);
}
else
{
DisplayWegPage(((Newtonsoft.Json.Linq.JToken)response["webPages"])["value"].ElementAt((int)index));
}
}
// else if ("Images" == answerType)
// {
// if ((index = item["resultIndex"]) == null)
// {
// DisplayAllImages(((Newtonsoft.Json.Linq.JToken)response["images"])["value"]);
// }
// else
// {
// DisplayImage(((Newtonsoft.Json.Linq.JToken)response["images"])["value"].ElementAt((int)index));
// }
// }
// else if ("Videos" == answerType)
// {
// if ((index = item["resultIndex"]) == null)
// {
// DisplayAllVideos(((Newtonsoft.Json.Linq.JToken)response["videos"])["value"]);
// }
// else
// {
// DisplayVideo(((Newtonsoft.Json.Linq.JToken)response["videos"])["value"].ElementAt((int)index));
// }
// }
else if ("News" == answerType)
{
if ((index = item["resultIndex"]) == null)
{
DisplayAllNews(((Newtonsoft.Json.Linq.JToken)response["news"])["value"]);
}
else
{
DisplayArticle(((Newtonsoft.Json.Linq.JToken)response["news"])["value"].ElementAt((int)index));
}
}
// else if ("RelatedSearches" == answerType)
// {
// if ((index = item["resultIndex"]) == null)
// {
// DisplayAllRelatedSearches(((Newtonsoft.Json.Linq.JToken)response["relatedSearches"])["value"]);
// }
// else
// {
// DisplayRelatedSearch(((Newtonsoft.Json.Linq.JToken)response["relatedSearches"])["value"].ElementAt((int)index));
// }
// }
else if ("Entities" == answerType)
{
if ((index = item["resultIndex"]) == null)
{
DisplayAllEntities(((Newtonsoft.Json.Linq.JToken)response["entities"])["value"]);
}
else
{
DisplayEntity(((Newtonsoft.Json.Linq.JToken)response["entities"])["value"].ElementAt((int)index));
}
}
// else if ("Places" == answerType)
// {
// if ((index = item["resultIndex"]) == null)
// {
// DisplayAllPlaces(((Newtonsoft.Json.Linq.JToken)response["places"])["value"]);
// }
// else
// {
// DisplayPlace(((Newtonsoft.Json.Linq.JToken)response["places"])["value"].ElementAt((int)index));
// }
// }
else if ("Computation" == answerType)
{
DisplayComputation((Newtonsoft.Json.Linq.JToken)response["computation"]);
}
else if ("Translations" == answerType)
{
DisplayTranslations((Newtonsoft.Json.Linq.JToken)response["translations"]);
}
else if ("TimeZone" == answerType)
{
DisplayTimeZone((Newtonsoft.Json.Linq.JToken)response["timeZone"]);
}
// else
// {
// Console.WriteLine("\nUnknown answer type: {0}\n", answerType);
// }
}
}
// Displays all webpages in the Webpages answer.
void DisplayAllWebPages(Newtonsoft.Json.Linq.JToken webpages)
{
foreach (Newtonsoft.Json.Linq.JToken webpage in webpages)
{
DisplayWegPage(webpage);
}
}
// Displays a single webpage.
void DisplayWegPage(Newtonsoft.Json.Linq.JToken webpage)
{
string rule = null;
// Some webpages require attribution. Checks if this page requires
// attribution and gets the list of attributions to apply.
Dictionary<string, string> rulesByField = null;
rulesByField = GetRulesByField(webpage["contractualRules"]);
Console.WriteLine("\tWebpage\n");
Console.WriteLine("\t\tName: " + webpage["name"]);
Console.WriteLine("\t\tUrl: " + webpage["url"]);
Console.WriteLine("\t\tDisplayUrl: " + webpage["displayUrl"]);
Console.WriteLine("\t\tSnippet: " + webpage["snippet"]);
// Apply attributions if they exist.
if (null != rulesByField)
{
if (rulesByField.TryGetValue("snippet", out rule))
{
Console.WriteLine("\t\t\tData from: " + rulesByField["snippet"]);
}
}
Console.WriteLine();
}
// Displays all images in the Images answer.
void DisplayAllImages(Newtonsoft.Json.Linq.JToken images)
{
foreach (Newtonsoft.Json.Linq.JToken image in images)
{
DisplayImage(image);
}
}
// Displays a single image.
void DisplayImage(Newtonsoft.Json.Linq.JToken image)
{
Console.WriteLine("\tImage\n");
Console.WriteLine("\t\tThumbnail: " + image["thumbnailUrl"]);
Console.WriteLine();
}
// Displays all videos in the Videos answer.
void DisplayAllVideos(Newtonsoft.Json.Linq.JToken videos)
{
foreach (Newtonsoft.Json.Linq.JToken video in videos)
{
DisplayVideo(video);
}
}
// Displays a single video.
void DisplayVideo(Newtonsoft.Json.Linq.JToken video)
{
Console.WriteLine("\tVideo\n");
Console.WriteLine("\t\tEmbed HTML: " + video["embedHtml"]);
Console.WriteLine();
}
// Displays all news articles in the News answer.
void DisplayAllNews(Newtonsoft.Json.Linq.JToken news)
{
foreach (Newtonsoft.Json.Linq.JToken article in news)
{
DisplayArticle(article);
}
}
// Displays a single news article.
void DisplayArticle(Newtonsoft.Json.Linq.JToken article)
{
// News articles require attribution. Gets the list of attributions to apply.
Dictionary<string, string> rulesByField = null;
rulesByField = GetRulesByField(article["contractualRules"]);
Console.WriteLine("\tArticle\n");
Console.WriteLine("\t\tName: " + article["name"]);
Console.WriteLine("\t\tURL: " + article["url"]);
Console.WriteLine("\t\tDescription: " + article["description"]);
Console.WriteLine("\t\tArticle from: " + rulesByField["global"]);
Console.WriteLine();
}
// Displays all related search in the RelatedSearches answer.
void DisplayAllRelatedSearches(Newtonsoft.Json.Linq.JToken searches)
{
foreach (Newtonsoft.Json.Linq.JToken search in searches)
{
DisplayRelatedSearch(search);
}
}
// Displays a single related search query.
void DisplayRelatedSearch(Newtonsoft.Json.Linq.JToken search)
{
Console.WriteLine("\tRelatedSearch\n");
Console.WriteLine("\t\tName: " + search["displayText"]);
Console.WriteLine("\t\tURL: " + search["webSearchUrl"]);
Console.WriteLine();
}
// Displays all entities in the Entities answer.
void DisplayAllEntities(Newtonsoft.Json.Linq.JToken entities)
{
foreach (Newtonsoft.Json.Linq.JToken entity in entities)
{
DisplayEntity(entity);
}
}
// Displays a single entity.
void DisplayEntity(Newtonsoft.Json.Linq.JToken entity)
{
string rule = null;
// Entities require attribution. Gets the list of attributions to apply.
Dictionary<string, string> rulesByField = null;
rulesByField = GetRulesByField(entity["contractualRules"]);
Console.WriteLine("\tEntity\n");
Console.WriteLine("\t\tName: " + entity["name"]);
if (entity["image"] != null)
{
Console.WriteLine("\t\tImage: " + entity["image"]["thumbnail"]);
if (rulesByField.TryGetValue("image", out rule))
{
Console.WriteLine("\t\t\tImage from: " + rule);
}
}
if (entity["description"] != null)
{
Console.WriteLine("\t\tDescription: " + entity["description"]);
if (rulesByField.TryGetValue("description", out rule))
{
Console.WriteLine("\t\t\tData from: " + rulesByField["description"]);
}
}
else
{
// See if presentation info can shed light on what this entity is.
var hintCount = entity["entityPresentationInfo"]["entityTypeHints"].Count();
Console.WriteLine("\t\tEntity hint: " + entity["entityPresentationInfo"]["entityTypeHints"][hintCount - 1]);
}
Console.WriteLine();
}
// Displays all places in the Places answer.
void DisplayAllPlaces(Newtonsoft.Json.Linq.JToken places)
{
foreach (Newtonsoft.Json.Linq.JToken place in places)
{
DisplayPlace(place);
}
}
// Displays a single place.
void DisplayPlace(Newtonsoft.Json.Linq.JToken place)
{
Console.WriteLine("\tPlace\n");
Console.WriteLine("\t\tName: " + place["name"]);
Console.WriteLine("\t\tPhone: " + place["telephone"]);
Console.WriteLine("\t\tWebsite: " + place["url"]);
Console.WriteLine();
}
// Displays the Computation answer.
void DisplayComputation(Newtonsoft.Json.Linq.JToken expression)
{
Console.WriteLine("\tComputation\n");
Console.WriteLine("\t\t{0} is {1}", expression["expression"], expression["value"]);
Console.WriteLine();
}
// Displays the Translation answer.
void DisplayTranslations(Newtonsoft.Json.Linq.JToken translation)
{
// Some webpages require attribution. Checks if this page requires
// attribution and gets the list of attributions to apply.
Dictionary<string, string> rulesByField = null;
rulesByField = GetRulesByField(translation["contractualRules"]);
// The translatedLanguageName field contains a 2-character language code,
// so you might want to provide the means to print Spanish instead of es.
Console.WriteLine("\tTranslation\n");
Console.WriteLine("\t\t\"{0}\" translates to \"{1}\" in {2}", translation["originalText"], translation["translatedText"], translation["translatedLanguageName"]);
Console.WriteLine("\t\tTranslation by " + rulesByField["global"]);
Console.WriteLine();
}
// Displays the TimeZone answer. This answer has multiple formats, so you need to figure
// out which fields exist in order to format the answer.
void DisplayTimeZone(Newtonsoft.Json.Linq.JToken timeZone)
{
Console.WriteLine("\tTime zone\n");
if (timeZone["primaryCityTime"] != null)
{
var time = DateTime.Parse((string)timeZone["primaryCityTime"]["time"]);
Console.WriteLine("\t\tThe time in {0} is {1}:", timeZone["primaryCityTime"]["location"], time);
if (timeZone["otherCityTimes"] != null)
{
Console.WriteLine("\t\tThere are {0} other time zones", timeZone["otherCityTimes"].Count());
}
}
if (timeZone["date"] != null)
{
Console.WriteLine("\t\t" + timeZone["date"]);
}
if (timeZone["primaryResponse"] != null)
{
Console.WriteLine("\t\t" + timeZone["primaryResponse"]);
}
if (timeZone["timeZoneDifference"] != null)
{
Console.WriteLine("\t\t{0} {1}", timeZone["description"], timeZone["timeZoneDifference"]["text"]);
}
if (timeZone["primaryTimeZone"] != null)
{
Console.WriteLine("\t\t" + timeZone["primaryTimeZone"]["timeZoneName"]);
}
Console.WriteLine();
}
// Checks if the result includes contractual rules and builds a dictionary of
// the rules.
Dictionary<string, string> GetRulesByField(Newtonsoft.Json.Linq.JToken contractualRules)
{
if (null == contractualRules)
{
return null;
}
var rules = new Dictionary<string, string>();
foreach (Newtonsoft.Json.Linq.JToken rule in contractualRules as Newtonsoft.Json.Linq.JToken)
{
var index = ((string)rule["_type"]).LastIndexOf('/');
var ruleType = ((string)rule["_type"]).Substring(index + 1);
string attribution = null;
if (ruleType == "LicenseAttribution")
{
attribution = (string)rule["licenseNotice"];
}
else if (ruleType == "LinkAttribution")
{
attribution = string.Format("{0}({1})", (string)rule["text"], (string)rule["url"]);
}
else if (ruleType == "MediaAttribution")
{
attribution = (string)rule["url"];
}
else if (ruleType == "TextAttribution")
{
attribution = (string)rule["text"];
}
// Use the rule's type as the key.
string key;
string value;
// If the rule targets specific data in the result; for example, the
// snippet field, use the target's name as the key. Multiple rules
// can apply to the same field.
if ((key = (string)rule["targetPropertyName"]) != null)
{
if (rules.TryGetValue(key, out value))
{
rules[key] = value + " | " + attribution;
}
else
{
rules.Add(key, attribution);
}
}
else
{
// Otherwise, the rule applies to the result. Uses 'global' as the key
// value for this case.
key = "global";
if (rules.TryGetValue(key, out value))
{
rules[key] = value + " | " + attribution;
}
else
{
rules.Add(key, attribution);
}
}
}
return rules;
}
// Print any errors that occur. Depending on which part of the service is
// throwing the error, the response may contain different error formats.
void PrintErrors(HttpResponseHeaders headers, Dictionary<String, object> response)
{
Console.WriteLine("The response contains the following errors:\n");
object value;
if (response.TryGetValue("error", out value)) // typically 401, 403
{
PrintError(response["error"] as Newtonsoft.Json.Linq.JToken);
}
else if (response.TryGetValue("errors", out value))
{
// Bing API error
foreach (Newtonsoft.Json.Linq.JToken error in response["errors"] as Newtonsoft.Json.Linq.JToken)
{
PrintError(error);
}
// Included only when HTTP status code is 400; not included with 401 or 403.
IEnumerable<string> headerValues;
if (headers.TryGetValues("BingAPIs-TraceId", out headerValues))
{
Console.WriteLine("\nTrace ID: " + headerValues.FirstOrDefault());
}
}
}
void PrintError(Newtonsoft.Json.Linq.JToken error)
{
string value = null;
Console.WriteLine("Code: " + error["code"]);
Console.WriteLine("Message: " + error["message"]);
if ((value = (string)error["parameter"]) != null)
{
Console.WriteLine("Parameter: " + value);
}
if ((value = (string)error["value"]) != null)
{
Console.WriteLine("Value: " + value);
}
}
}
//Console.WriteLine($"Args.Count: {Args.Count}");
new Bing().RunAsync(Args.ToArray()).Wait();