This commit is contained in:
unknown 2020-11-19 14:25:43 +02:00
Родитель b4ccc92f70
Коммит 62293746f9
399 изменённых файлов: 48930 добавлений и 0 удалений

Просмотреть файл

@ -0,0 +1,55 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Newtonsoft.Json;
using System;
using System.Net.Http;
// This sample makes a call to the Bing Autosuggest API with a query word and returns autocomplete suggestions.
namespace BingAutosuggest
{
class Program
{
// Add your Bing Autosuggest subscription key to your environment variables.
static string key = Environment.GetEnvironmentVariable("BING_AUTOSUGGEST_SUBSCRIPTION_KEY");
// Add your Bing Autosuggest endpoint to your environment variables.
static string endpoint = Environment.GetEnvironmentVariable("BING_AUTOSUGGEST_ENDPOINT");
static string path = "/v7.0/Suggestions/";
static string market = "en-US";
static string query = "sail";
// These properties are used for optional headers (see below).
//static string ClientId = "<Client ID from Previous Response Goes Here>";
//static string ClientIp = "999.999.999.999";
//static string ClientLocation = "+90.0000000000000;long: 00.0000000000000;re:100.000000000000";
async static void Autosuggest()
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", key);
// The following headers are optional, but it is recommended they be treated as required.
// These headers help the service return more accurate results.
//client.DefaultRequestHeaders.Add("X-Search-Location", ClientLocation);
//client.DefaultRequestHeaders.Add("X-MSEdge-ClientID", ClientId);
//client.DefaultRequestHeaders.Add("X-MSEdge-ClientIP", ClientIp);
string uri = endpoint + path + "?mkt=" + market + "&query=" + System.Net.WebUtility.UrlEncode(query);
HttpResponseMessage response = await client.GetAsync(uri);
string contentString = await response.Content.ReadAsStringAsync();
dynamic parsedJson = JsonConvert.DeserializeObject(contentString);
Console.WriteLine(JsonConvert.SerializeObject(parsedJson, Formatting.Indented));
}
static void Main(string[] args)
{
Autosuggest();
Console.ReadLine();
}
}
}

Просмотреть файл

@ -0,0 +1,74 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <using>
using System;
using System.Net.Http;
using System.Web;
using Newtonsoft.Json;
// </using>
// This sample makes a call to the Bing Custom Search API with a query word and returns images with details.
namespace BingCustomSearch
{
class Program
{
static void Main(string[] args)
{
// <vars>
// Add your Bing Custom Search subscription key and endpoint to your environment variables.
var subscriptionKey = Environment.GetEnvironmentVariable("BING_CUSTOM_SEARCH_SUBSCRIPTION_KEY");
var endpoint = Environment.GetEnvironmentVariable("BING_CUSTOM_SEARCH_ENDPOINT");
var customConfigId = Environment.GetEnvironmentVariable("BING_CUSTOM_CONFIG"); // you can also use "1"
var searchTerm = args.Length > 0 ? args[0] : "microsoft";
// </vars>
// <url>
// Use your Azure Bing Custom Search endpoint to create the full request URL.
var url = endpoint + "/v7.0/custom/images/search?" + "q=" + searchTerm + "&customconfig=" + customConfigId;
// </url>
// <client>
var client = new HttpClient();
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
// </client>
// <sendRequest>
var httpResponseMessage = client.GetAsync(url).Result;
var responseContent = httpResponseMessage.Content.ReadAsStringAsync().Result;
BingCustomSearchResponse response = JsonConvert.DeserializeObject<BingCustomSearchResponse>(responseContent);
// </sendRequest>
// <iterateResponse>
for (int i = 0; i < response.value.Length; i++)
{
var webPage = response.value[i];
Console.WriteLine("Name: " + webPage.name);
Console.WriteLine("WebSearchUrl: " + webPage.webSearchUrl);
Console.WriteLine("HostPageUrl: " + webPage.hostPageUrl);
Console.WriteLine("Thumbnail: " + webPage.thumbnail.width + " width, " + webPage.thumbnail.height + " height");
Console.WriteLine();
}
//</iterateResponse>
}
}
// <responseClasses>
public class BingCustomSearchResponse
{
public string _type { get; set; }
public WebPage[] value { get; set; }
}
public class WebPage
{
public string name { get; set; }
public string webSearchUrl { get; set; }
public string hostPageUrl { get; set; }
public OpenGraphImage thumbnail { get; set; }
}
public class OpenGraphImage
{
public int width { get; set; }
public int height { get; set; }
}
// </responseClasses>
}

Просмотреть файл

@ -0,0 +1,42 @@
using Newtonsoft.Json;
using System;
using System.Net.Http;
// This sample makes a call to the Bing Entity Search v7 API with a query and returns details about it.
namespace BingEntitySearch
{
class Program
{
// Add your key and endpoint to your environment variables.
static string key = Environment.GetEnvironmentVariable("BING_ENTITY_SEARCH_SUBSCRIPTION_KEY");
static string endpoint = Environment.GetEnvironmentVariable("BING_ENTITY_SEARCH_ENDPOINT");
static string path = "/v7.0/entities/";
static string market = "en-US";
static string query = "italian restaurant near me";
async static void Search()
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", key);
string uri = endpoint + path + "?mkt=" + market + "&q=" + System.Net.WebUtility.UrlEncode(query);
HttpResponseMessage response = await client.GetAsync(uri);
string contentString = await response.Content.ReadAsStringAsync();
dynamic parsedJson = JsonConvert.DeserializeObject(contentString);
Console.WriteLine(parsedJson);
}
static void Main(string[] args)
{
Search();
Console.ReadLine();
}
}
}

Просмотреть файл

@ -0,0 +1,55 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Newtonsoft.Json;
using System;
using System.Text;
using System.Net;
using System.IO;
using System.Collections.Generic;
// This sample makes a call to the Bing Search API with a text query and returns relevant data from the web.
namespace BingImageSearch
{
class Program
{
// Add your Bing Search V7 subscription key and endpoint to your environment variables.
static string subscriptionKey = Environment.GetEnvironmentVariable("BING_SEARCH_V7_SUBSCRIPTION_KEY");
static string endpoint = Environment.GetEnvironmentVariable("BING_SEARCH_V7_ENDPOINT") + "/v7.0/images/search";
const string query = "puppies";
static void Main()
{
Console.OutputEncoding = Encoding.UTF8;
Dictionary<String, String> relevantHeaders = new Dictionary<String, String>();
Console.WriteLine("Searching images for: " + query);
// Construct the URI of the search request
var uriQuery = endpoint + "?q=" + Uri.EscapeDataString(query);
// Perform the Web request and get the response
WebRequest request = HttpWebRequest.Create(uriQuery);
request.Headers["Ocp-Apim-Subscription-Key"] = subscriptionKey;
HttpWebResponse response = (HttpWebResponse)request.GetResponseAsync().Result;
string json = new StreamReader(response.GetResponseStream()).ReadToEnd();
// Extract Bing HTTP headers
foreach (String header in response.Headers)
{
if (header.StartsWith("BingAPIs-") || header.StartsWith("X-MSEdge-"))
relevantHeaders[header] = response.Headers[header];
}
Console.WriteLine("\nRelevant HTTP Headers:\n");
foreach (var header in relevantHeaders)
Console.WriteLine(header.Key + ": " + header.Value);
Console.WriteLine("\nJSON Response:\n");
dynamic parsedJson = JsonConvert.DeserializeObject(json);
Console.WriteLine(JsonConvert.SerializeObject(parsedJson, Formatting.Indented));
}
}
}

Просмотреть файл

@ -0,0 +1,82 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
//Licensed under the MIT License.
using System;
using System.Net;
using System.IO;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
namespace BingSearchApisQuickstart
{
class Program
{
// Add your Bing Search V7 subscription key to your environment variables
const string subscriptionKey = Environment.GetEnvironmentVariable("BING_SEARCH_V7_SUBSCRIPTION_KEY");
// Add your Bing Search V7 endpoint to your environment variables
const string uriBase = Environment.GetEnvironmentVariable("BING_SEARCH_V7_ENDPOINT") + "/v7.0/images/search";
const string searchTerm = "tropical ocean";
// A struct to return image search results seperately from headers
struct SearchResult
{
public string jsonResult;
public Dictionary<String, String> relevantHeaders;
}
static void Main()
{
Console.OutputEncoding = System.Text.Encoding.UTF8;
Console.WriteLine("Searching images for: " + searchTerm + "\n");
//send a search request using the search term
SearchResult result = BingImageSearch(searchTerm);
//deserialize the JSON response from the Bing Image Search API
dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(result.jsonResult);
var firstJsonObj = jsonObj["value"][0];
Console.WriteLine("Title for the first image result: " + firstJsonObj["name"]+"\n");
//After running the application, copy the output URL into a browser to see the image.
Console.WriteLine("URL for the first image result: " + firstJsonObj["webSearchUrl"]+"\n");
Console.Write("\nPress Enter to exit ");
Console.ReadLine();
}
/// <summary>
/// Performs a Bing Image search and return the results as a SearchResult.
/// </summary>
static SearchResult BingImageSearch(string searchQuery)
{
// Construct the URI of the search request
var uriQuery = uriBase + "?q=" + Uri.EscapeDataString(searchQuery);
// Perform the Web request and get the response
WebRequest request = WebRequest.Create(uriQuery);
request.Headers["Ocp-Apim-Subscription-Key"] = subscriptionKey;
HttpWebResponse response = (HttpWebResponse)request.GetResponseAsync().Result;
string json = new StreamReader(response.GetResponseStream()).ReadToEnd();
// Create result object for return
var searchResult = new SearchResult()
{
jsonResult = json,
relevantHeaders = new Dictionary<String, String>()
};
// Extract Bing HTTP headers
foreach (String header in response.Headers)
{
if (header.StartsWith("BingAPIs-") || header.StartsWith("X-MSEdge-"))
searchResult.relevantHeaders[header] = response.Headers[header];
}
return searchResult;
}
}
}

Просмотреть файл

@ -0,0 +1,60 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Newtonsoft.Json;
using System;
using System.Text;
using System.Net;
using System.IO;
using System.Collections.Generic;
// This sample makes a call to the Bing News Search API with a query word and returns related news.
namespace BingNewsSearch
{
class Program
{
// Add your Bing Search V7 subscription key to your environment variables.
static string accessKey = Environment.GetEnvironmentVariable("BING_SEARCH_V7_SUBSCRIPTION_KEY");
// Add your Bing Search V7 endpoint to your environment variables.
static string endpoint = Environment.GetEnvironmentVariable("BING_SEARCH_V7_ENDPOINT") + "/v7.0/news/search";
const string query = "Microsoft";
static void Main()
{
// Create dictionary to store a few extracted headers
Dictionary<String, String> relevantHeaders = new Dictionary<String, String>();
Console.OutputEncoding = Encoding.UTF8;
Console.WriteLine("Searching news for: " + query);
// Construct the URI of the search request
var uriQuery = endpoint + "?q=" + Uri.EscapeDataString(query);
// 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();
// Extract Bing HTTP headers
foreach (String header in response.Headers)
{
if (header.StartsWith("BingAPIs-") || header.StartsWith("X-MSEdge-"))
relevantHeaders[header] = response.Headers[header];
}
Console.WriteLine("\nRelevant HTTP Headers:\n");
foreach (var header in relevantHeaders)
Console.WriteLine(header.Key + ": " + header.Value);
Console.WriteLine("\nJSON Response:\n");
dynamic parsedJson = JsonConvert.DeserializeObject(json);
Console.WriteLine(JsonConvert.SerializeObject(parsedJson, Formatting.Indented));
Console.ReadLine();
}
}
}

Просмотреть файл

@ -0,0 +1,72 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
// This sample uses the Bing Spell Check API to check the spelling of a query.
namespace BingSpellCheck
{
class Program
{
// Add your Bing Spell Check key and endpoint to your environment variables.
static string subscriptionKey = Environment.GetEnvironmentVariable("BING_SPELL_CHECK_SUBSCRIPTION_KEY");
static string endpoint = Environment.GetEnvironmentVariable("BING_SPELL_CHECK_ENDPOINT");
static string path = "/v7.0/spellcheck?";
static string market = "en-US";
static string mode = "proof";
static string query = "Hollo, wrld!";
// These properties are used for optional headers (see below).
// static string ClientId = "<Client ID from Previous Response Goes Here>";
// static string ClientIp = "999.999.999.999";
// static string ClientLocation = "+90.0000000000000;long: 00.0000000000000;re:100.000000000000";
public async static Task Main(string[] args)
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
// The following headers are optional, but it is recommended they be treated as required.
// These headers help the service return more accurate results.
// client.DefaultRequestHeaders.Add("X-Search-Location", ClientLocation);
// client.DefaultRequestHeaders.Add("X-MSEdge-ClientID", ClientId);
// client.DefaultRequestHeaders.Add("X-MSEdge-ClientIP", ClientIp);
HttpResponseMessage response = new HttpResponseMessage();
string uri = endpoint + path;
List<KeyValuePair<string, string>> values = new List<KeyValuePair<string, string>>();
values.Add(new KeyValuePair<string, string>("mkt", market));
values.Add(new KeyValuePair<string, string>("mode", mode));
values.Add(new KeyValuePair<string, string>("text", query));
using (FormUrlEncodedContent content = new FormUrlEncodedContent(values))
{
content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
response = await client.PostAsync(uri, content);
}
// Get the client ID header from your request (optional)
// string client_id;
// if (response.Headers.TryGetValues("X-MSEdge-ClientID", out IEnumerable<string> header_values))
// {
// client_id = header_values.First();
// Console.WriteLine("Client ID: " + client_id);
// }
string contentString = await response.Content.ReadAsStringAsync();
//Deserialize the JSON response from the API
dynamic jsonObj = JsonConvert.DeserializeObject(contentString);
Console.WriteLine(jsonObj);
}
}
}

Просмотреть файл

@ -0,0 +1,42 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Newtonsoft.Json;
using System;
using System.Text;
using System.Net;
using System.IO;
// This sample makes a call to the Bing Video Search API with a query and returns data about it.
namespace BingVideoSearch
{
class Program
{
// Add your Bing Search v7 key and endpoint to your environment variables.
static string subscriptionKey = Environment.GetEnvironmentVariable("BING_SEARCH_V7_SUBSCRIPTION_KEY");
static string endpoint = Environment.GetEnvironmentVariable("BING_SEARCH_V7_ENDPOINT") + "/v7.0/videos/search";
const string query = "kittens";
static void Main()
{
Console.OutputEncoding = Encoding.UTF8;
Console.WriteLine("Searching videos for: " + query);
// Construct the URI of the search request
var uriQuery = endpoint + "?q=" + Uri.EscapeDataString(query);
// Perform the Web request and get the response
WebRequest request = HttpWebRequest.Create(uriQuery);
request.Headers["Ocp-Apim-Subscription-Key"] = subscriptionKey;
HttpWebResponse response = (HttpWebResponse)request.GetResponseAsync().Result;
string json = new StreamReader(response.GetResponseStream()).ReadToEnd();
Console.WriteLine("\nJSON Response:\n");
dynamic parsedJson = JsonConvert.DeserializeObject(json);
Console.WriteLine(JsonConvert.SerializeObject(parsedJson, Formatting.Indented));
}
}
}

Просмотреть файл

@ -0,0 +1,89 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Newtonsoft.Json;
using System;
using System.Text;
using System.Net;
using System.IO;
// This sample makes a call to the Bing Visual Search API with a query image and returns similar images with details.
namespace BingVisualSearch
{
class Program
{
// Add your Bing Search V7 subscription key and endpoint to your environment variables.
static string subscriptionKey = Environment.GetEnvironmentVariable("BING_SEARCH_V7_SUBSCRIPTION_KEY");
static string endpoint = Environment.GetEnvironmentVariable("BING_SEARCH_V7_ENDPOINT") + "/v7.0/images/visualsearch";
// Set the path to the image that you want to get insights of.
static string imagePath = @"objects.jpg";
// Boundary strings for form data in body of POST.
const string CRLF = "\r\n";
static string BoundaryTemplate = "batch_{0}";
static string StartBoundaryTemplate = "--{0}";
static string EndBoundaryTemplate = "--{0}--";
const string CONTENT_TYPE_HEADER_PARAMS = "multipart/form-data; boundary={0}";
const string POST_BODY_DISPOSITION_HEADER = "Content-Disposition: form-data; name=\"image\"; filename=\"{0}\"" + CRLF + CRLF;
static void Main()
{
try
{
Console.OutputEncoding = Encoding.UTF8;
// Gets image.
var filename = new FileInfo(imagePath).FullName;
Console.WriteLine("Getting image insights for image: " + Path.GetFileName(filename));
var imageBinary = File.ReadAllBytes(imagePath);
// Sets up POST body.
var boundary = string.Format(BoundaryTemplate, Guid.NewGuid());
// Builds form start data.
var startBoundary = string.Format(StartBoundaryTemplate, boundary);
var startFormData = startBoundary + CRLF;
startFormData += string.Format(POST_BODY_DISPOSITION_HEADER, filename);
// Builds form end data.
var endFormData = CRLF + CRLF + string.Format(EndBoundaryTemplate, boundary) + CRLF;
var contentTypeHeaderValue = string.Format(CONTENT_TYPE_HEADER_PARAMS, boundary);
// Sets up the request for a visual search.
WebRequest request = HttpWebRequest.Create(endpoint);
request.ContentType = contentTypeHeaderValue;
request.Headers["Ocp-Apim-Subscription-Key"] = subscriptionKey;
request.Method = "POST";
// Writes the boundary and Content-Disposition header, then writes
// the image binary, and finishes by writing the closing boundary.
using (Stream requestStream = request.GetRequestStream())
{
StreamWriter writer = new StreamWriter(requestStream);
writer.Write(startFormData);
writer.Flush();
requestStream.Write(imageBinary, 0, imageBinary.Length);
writer.Write(endFormData);
writer.Flush();
writer.Close();
}
// Calls the Bing Visual Search endpoint and returns the JSON response.
HttpWebResponse response = (HttpWebResponse)request.GetResponseAsync().Result;
string json = new StreamReader(response.GetResponseStream()).ReadToEnd();
Console.WriteLine("\nJSON Response:\n");
dynamic parsedJson = JsonConvert.DeserializeObject(json);
Console.WriteLine(JsonConvert.SerializeObject(parsedJson, Formatting.Indented));
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}

Просмотреть файл

@ -0,0 +1,58 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Newtonsoft.Json;
using System;
using System.Text;
using System.Net;
using System.IO;
using System.Collections.Generic;
// This sample uses the Bing Web Search API v7 to retrieve different kinds of media from the web.
namespace BingWebSearch
{
class Program
{
// Add your Bing Search V7 subscription key and endpoint to your environment variables
static string subscriptionKey = Environment.GetEnvironmentVariable("BING_SEARCH_V7_SUBSCRIPTION_KEY");
static string endpoint = Environment.GetEnvironmentVariable("BING_SEARCH_V7_ENDPOINT") + "/v7.0/search";
const string query = "hummingbirds";
static void Main()
{
// Create a dictionary to store relevant headers
Dictionary<String, String> relevantHeaders = new Dictionary<String, String>();
Console.OutputEncoding = Encoding.UTF8;
Console.WriteLine("Searching the Web for: " + query);
// Construct the URI of the search request
var uriQuery = endpoint + "?q=" + Uri.EscapeDataString(query);
// Perform the Web request and get the response
WebRequest request = HttpWebRequest.Create(uriQuery);
request.Headers["Ocp-Apim-Subscription-Key"] = subscriptionKey;
HttpWebResponse response = (HttpWebResponse)request.GetResponseAsync().Result;
string json = new StreamReader(response.GetResponseStream()).ReadToEnd();
// Extract Bing HTTP headers
foreach (String header in response.Headers)
{
if (header.StartsWith("BingAPIs-") || header.StartsWith("X-MSEdge-"))
relevantHeaders[header] = response.Headers[header];
}
// Show headers
Console.WriteLine("\nRelevant HTTP Headers:\n");
foreach (var header in relevantHeaders)
Console.WriteLine(header.Key + ": " + header.Value);
Console.WriteLine("\nJSON Response:\n");
dynamic parsedJson = JsonConvert.DeserializeObject(json);
Console.WriteLine(JsonConvert.SerializeObject(parsedJson, Formatting.Indented));
}
}
}

Просмотреть файл

@ -0,0 +1,169 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Threading.Tasks;
using System.Linq;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace WebSearchQuickstart2
{
static class Program
{
// In production, make sure you're pulling the subscription key from secured storage.
private static string _subscriptionKey = "<YOUR SUBSCRIPTION KEY GOES HERE>";
private static string _baseUri = "https://api.bing.microsoft.com/v7.0/suggestions";
// Each of the query parameters you may specify.
private const string QUERY_PARAMETER = "?q="; // Required
private const string MKT_PARAMETER = "&mkt="; // Strongly suggested
// The user's search string.
private static string searchString = "coro";
// Bing uses the X-MSEdge-ClientID header to provide users with consistent
// behavior across Bing API calls. See the the reference documentation
// for usage.
private static string _clientIdHeader = null;
static void Main()
{
RunAsync().Wait();
}
static async Task RunAsync()
{
try
{
// Remember to encode the q query parameter.
var queryString = QUERY_PARAMETER + Uri.EscapeDataString(searchString);
queryString += MKT_PARAMETER + "en-us";
HttpResponseMessage response = await MakeRequestAsync(queryString);
_clientIdHeader = response.Headers.GetValues("X-MSEdge-ClientID").FirstOrDefault();
// 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)
{
PrintSuggestions(searchResponse);
}
else
{
PrintErrors(response.Headers, searchResponse);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine("\nPress ENTER to exit...");
Console.ReadLine();
}
// Makes the request to the Autosuggest endpoint.
static 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 list of search string suggestions from the JSON response.
static void PrintSuggestions(Dictionary<string, object> response)
{
Console.WriteLine("The response contains the following search string suggestions:\n");
var groups = response["suggestionGroups"] as Newtonsoft.Json.Linq.JToken;
foreach (Newtonsoft.Json.Linq.JToken group in groups)
{
if ((string)group["name"] == "Web")
{
foreach (Newtonsoft.Json.Linq.JToken suggestion in group["searchSuggestions"])
{
Console.WriteLine("Suggestion: {0} ({1})", suggestion["displayText"], suggestion["url"]);
// Use the suggestion in the query field if you want to call Web Search API and
// display the results yourself.
}
}
}
}
// Print any errors that occur. Depending on which part of the service is
// throwing the error, the response may contain different formats.
static 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());
}
}
}
static 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);
}
}
}
}

Просмотреть файл

@ -0,0 +1,321 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Threading.Tasks;
using System.Linq;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace WebCustomSearchQuickstart
{
static class Program
{
// In production, make sure you're pulling the subscription key from secured storage.
private static string _subscriptionKey = "<YOUR SUBSCRIPTION KEY GOES HERE>";
private static string _baseUri = "https://api.bing.microsoft.com/v7.0/custom/search";
private static string _customConfigId = "<YOUR INSTANCE CONFIGURATION ID GOES HERE>";
// Each of the query parameters you may specify.
private const string QUERY_PARAMETER = "?q="; // Required
private const string CUSTOM_CONFIG_PARAMETER = "&customConfig="; // Required
private const string MKT_PARAMETER = "&mkt="; // Strongly suggested
private const string COUNT_PARAMETER = "&count=";
private const string OFFSET_PARAMETER = "&offset=";
private const string SAFE_SEARCH_PARAMETER = "&safeSearch=";
private const string TEXT_DECORATIONS_PARAMETER = "&textDecorations=";
private const string TEXT_FORMAT_PARAMETER = "&textFormat=";
// The user's search string.
private static string searchString = "surface book 3";
// Bing uses the X-MSEdge-ClientID header to provide users with consistent
// behavior across Bing API calls. See the the reference documentation
// fo usage.
private static string _clientIdHeader = null;
static void Main()
{
RunAsync().Wait();
}
static async Task RunAsync()
{
try
{
// Remember to encode the q query parameter.
var queryString = QUERY_PARAMETER + Uri.EscapeDataString(searchString);
queryString += CUSTOM_CONFIG_PARAMETER + _customConfigId;
queryString += MKT_PARAMETER + "en-us";
queryString += TEXT_DECORATIONS_PARAMETER + Boolean.TrueString;
HttpResponseMessage response = await MakeRequestAsync(queryString);
_clientIdHeader = response.Headers.GetValues("X-MSEdge-ClientID").FirstOrDefault();
// 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.Message);
}
Console.WriteLine("\nPress ENTER to exit...");
Console.ReadLine();
}
// Makes the request to the Web Search endpoint.
static 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.
static 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.
static 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
{
Console.WriteLine("\nUnknown answer type: {0}\n", answerType);
}
}
}
// Displays all webpages in the Webpages answer.
static void DisplayAllWebPages(Newtonsoft.Json.Linq.JToken webpages)
{
foreach (Newtonsoft.Json.Linq.JToken webpage in webpages)
{
DisplayWegPage(webpage);
}
}
// Displays a single webpage.
static void DisplayWegPage(Newtonsoft.Json.Linq.JToken webpage)
{
// 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 && null != rulesByField["snippet"])
{
Console.WriteLine("\t\t\tData from: " + rulesByField["snippet"]);
}
Console.WriteLine();
}
// Checks if the result includes contractual rules and builds a dictionary of
// the rules.
static 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)
{
// Use the rule's type as the key.
string key = null;
string value = null;
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"];
}
// 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 formats.
static 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());
}
}
}
static 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);
}
}
}
}

Просмотреть файл

@ -0,0 +1,370 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Threading.Tasks;
using System.Linq;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace EntitiesQuickstart
{
static class Program
{
// In production, make sure you're pulling the subscription key from secured storage.
private static string _subscriptionKey = "<YOUR SUBSCRIPTION KEY GOES HERE>";
private static string _baseUri = "https://api.bing.microsoft.com/v7.0/entities";
// Each of the query parameters you may specify.
private const string QUERY_PARAMETER = "?q="; // Required
private const string MKT_PARAMETER = "&mkt="; // Strongly suggested
private const string RESPONSE_FILTER_PARAMETER = "&responseFilter=";
private const string SAFE_SEARCH_PARAMETER = "&safeSearch=";
// The user's search string.
private static string searchString = "bill gates";
// Bing uses the X-MSEdge-ClientID header to provide users with consistent
// behavior across Bing API calls. See the the reference documentation
// fo usage.
private static string _clientIdHeader = null;
static void Main()
{
RunAsync().Wait();
}
static async Task RunAsync()
{
try
{
// Remember to encode the query parameter.
var queryString = QUERY_PARAMETER + Uri.EscapeDataString(searchString);
queryString += MKT_PARAMETER + "en-us";
//queryString += RESPONSE_FILTER_PARAMETER + Uri.EscapeDataString("places");
HttpResponseMessage response = await MakeRequestAsync(queryString);
_clientIdHeader = response.Headers.GetValues("X-MSEdge-ClientID").FirstOrDefault();
// 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.Message);
}
Console.WriteLine("\nPress ENTER to exit...");
Console.ReadLine();
}
// Makes the request to the Web Search endpoint.
static 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.
static 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.
static 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 ("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
{
Console.WriteLine("\nUnknown answer type: {0}\n", answerType);
}
}
}
// Displays all entities in the Entities answer.
static void DisplayAllEntities(Newtonsoft.Json.Linq.JToken entities)
{
foreach (Newtonsoft.Json.Linq.JToken entity in entities)
{
DisplayEntity(entity);
}
}
// Displays a single entity.
static 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"]["thumbnailUrl"]);
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.
static void DisplayAllPlaces(Newtonsoft.Json.Linq.JToken places)
{
foreach (Newtonsoft.Json.Linq.JToken place in places)
{
DisplayPlace(place);
}
}
// Displays a single place.
static 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();
}
// Checks if the result includes contractual rules and builds a dictionary of
// the rules.
static 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)
{
// Use the rule's type as the key.
string key = null;
string value = null;
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"];
}
// 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 formats.
static 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());
}
}
}
static 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);
}
}
}
}

Просмотреть файл

@ -0,0 +1,205 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Threading.Tasks;
using System.Linq;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace ImageSearchQuickstart
{
class Program
{
// In production, make sure you're pulling the subscription key from secured storage.
private static string _subscriptionKey = "<YOUR SUBSCRIPTION KEY GOES HERE>";
private static string _baseUri = "https://api.bing.microsoft.com/v7.0/images/search";
// Each of the query parameters you may specify.
private const string QUERY_PARAMETER = "?q="; // Required
private const string MKT_PARAMETER = "&mkt="; // Strongly suggested
private const string COUNT_PARAMETER = "&count=";
private const string OFFSET_PARAMETER = "&offset=";
private const string ID_PARAMETER = "&id=";
private const string SAFE_SEARCH_PARAMETER = "&safeSearch=";
// Each of the filter query parameters you may specify.
private const string ASPECT_PARAMETER = "&aspect=";
private const string COLOR_PARAMETER = "&color=";
private const string FRESHNESS_PARAMETER = "&freshness=";
private const string HEIGHT_PARAMETER = "&height=";
private const string WIDTH_PARAMETER = "&width=";
private const string IMAGE_CONTENT_PARAMETER = "&imageContent=";
private const string IMAGE_TYPE_PARAMETER = "&imageType=";
private const string LICENSE_PARAMETER = "&license=";
private const string MAX_FILE_SIZE_PARAMETER = "&maxFileSize=";
private const string MIN_FILE_SIZE_PARAMETER = "&minFileSize=";
private const string MAX_HEIGHT_PARAMETER = "&maxHeight=";
private const string MIN_HEIGHT_PARAMETER = "&minHeight=";
private const string MAX_WIDTH_PARAMETER = "&maxWidth=";
private const string MIN_WIDTH_PARAMETER = "&minWidth=";
private const string SIZE_PARAMETER = "&size=";
// The user's search string.
private static string _searchString = "hummingbird";
// To page through images, you'll need the next offset that Bing returns.
private static long _nextOffset = 0;
// To get additional insights about the image, you'll need the image's
// insights token (see Visual Search API).
private static string _insightsToken = null;
// Bing uses the X-MSEdge-ClientID header to provide users with consistent
// behavior across Bing API calls. See the reference documentation
// for usage.
private static string _clientIdHeader = null;
static void Main()
{
RunAsync().Wait();
}
static async Task RunAsync()
{
try
{
// Remember to encode the q query parameter.
var queryString = QUERY_PARAMETER + Uri.EscapeDataString(_searchString);
queryString += MKT_PARAMETER + "en-us";
HttpResponseMessage response = await MakeRequestAsync(queryString);
_clientIdHeader = response.Headers.GetValues("X-MSEdge-ClientID").FirstOrDefault();
// 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)
{
PrintImages(searchResponse);
}
else
{
PrintErrors(response.Headers, searchResponse);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine("\nPress ENTER to exit...");
Console.ReadLine();
}
// Makes the request to the Image Search endpoint.
static 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 list of images in the JSON response.
static void PrintImages(Dictionary<string, object> response)
{
Console.WriteLine("The response contains the following images:\n");
// This example just prints the first page of images. If you want to page
// through the images, set the offset query parameter to the next offset
// value that Bing returns.
_nextOffset = (long) response["nextOffset"];
var images = response["value"] as Newtonsoft.Json.Linq.JToken;
foreach (Newtonsoft.Json.Linq.JToken image in images)
{
Console.WriteLine("Thumbnail: " + image["thumbnailUrl"]);
Console.WriteLine("Thumbnail size: {0} (w) x {1} (h) ", image["thumbnail"]["width"], image["thumbnail"]["height"]);
Console.WriteLine("Original image: " + image["contentUrl"]);
Console.WriteLine("Original image size: {0} (w) x {1} (h) ", image["width"], image["height"]);
Console.WriteLine("Host: {0} ({1})", image["hostPageDomainFriendlyName"], image["hostPageDisplayUrl"]);
Console.WriteLine();
// If you want to get additional insights about the image, capture the
// image token that you use when calling Visual Search API.
_insightsToken = (string) image["imageInsightsToken"];
}
}
// Print any errors that occur. Depending on which part of the service is
// throwing the error, the response may contain different formats.
static 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());
}
}
}
static 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);
}
}
}
}

Просмотреть файл

@ -0,0 +1,216 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Threading.Tasks;
using System.Linq;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace NewsSearchQuickstart
{
class Program
{
// In production, make sure you're pulling the subscription key from secured storage.
private static string _subscriptionKey = "<YOUR SUBSCRIPTION KEY GOES HERE>";
private static string _baseUri = "https://api.bing.microsoft.com/v7.0/news/search";
// Each of the query parameters you may specify.
private const string QUERY_PARAMETER = "?q="; // Required
private const string MKT_PARAMETER = "&mkt="; // Strongly suggested
private const string COUNT_PARAMETER = "&count=";
private const string OFFSET_PARAMETER = "&offset=";
private const string ORIGINAL_IMG_PARAMETER = "&originalImg=";
private const string SAFE_SEARCH_PARAMETER = "&safeSearch=";
private const string SORT_BY_PARAMETER = "&sortBy=";
private const string TEXT_DECORATIONS_PARAMETER = "&textDecorations=";
private const string TEXT_FORMAT_PARAMETER = "&textFormat=";
// Each of the filter query parameters you may specify.
private const string FRESHNESS_PARAMETER = "&freshness=";
// The user's search string.
private static string _searchString = "california wildfires";
// Bing uses the X-MSEdge-ClientID header to provide users with consistent
// behavior across Bing API calls. See the reference documentation
// for usage.
private static string _clientIdHeader = null;
static void Main()
{
RunAsync().Wait();
}
static async Task RunAsync()
{
try
{
// Remember to encode the q query parameter.
var queryString = QUERY_PARAMETER + Uri.EscapeDataString(_searchString);
queryString += MKT_PARAMETER + "en-us";
HttpResponseMessage response = await MakeRequestAsync(queryString);
_clientIdHeader = response.Headers.GetValues("X-MSEdge-ClientID").FirstOrDefault();
// 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)
{
PrintNews(searchResponse);
}
else
{
PrintErrors(response.Headers, searchResponse);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine("\nPress ENTER to exit...");
Console.ReadLine();
}
// Makes the request to the Video Search endpoint.
static 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 list of news articles in the JSON response. This example prints
// the first page of articles.
static void PrintNews(Dictionary<string, object> response)
{
Newtonsoft.Json.Linq.JToken value = null;
Console.WriteLine("The response contains the following news articles:\n");
var articles = response["value"] as Newtonsoft.Json.Linq.JToken;
foreach (Newtonsoft.Json.Linq.JToken article in articles)
{
Console.WriteLine("Title: " + article["name"]);
Console.WriteLine("URL to article: " + article["url"]);
Console.WriteLine("Description: " + article["description"]);
Console.WriteLine("Publisher: " + GetPublisherString(article["provider"]));
if ((value = article["image"]) != null)
{
Console.WriteLine("Thumbnail: " + value["thumbnail"]["contentUrl"]);
Console.WriteLine("Thumbnail size: {0} (w) x {1} (h) ", value["thumbnail"]["width"], value["thumbnail"]["height"]);
}
if ((value = article["video"]) != null)
{
if (value["motionThumbnailUrl"] != null)
{
Console.WriteLine("Title: " + value["name"]);
Console.WriteLine("Motion thumbnail: " + value["motionThumbnailUrl"]);
Console.WriteLine("Motion thumbnail size: {0} (w) x {1} (h) ", value["thumbnail"]["width"], value["thumbnail"]["height"]);
}
}
Console.WriteLine();
}
}
// Get a printable publisher string. The article's publisher field is an array
// of publishers. In practice, there's a single publisher, but...
static string GetPublisherString(Newtonsoft.Json.Linq.JToken publishers)
{
string publisherString = "";
Boolean isFirst = true;
foreach (Newtonsoft.Json.Linq.JToken publisher in publishers)
{
if (!isFirst)
{
publisherString += " | ";
}
publisherString += publisher["name"];
}
return publisherString;
}
// Print any errors that occur. Depending on which part of the service is
// throwing the error, the response may contain different formats.
static 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());
}
}
}
static 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);
}
}
}
}

Просмотреть файл

@ -0,0 +1,193 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Threading.Tasks;
using System.Linq;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace SpellCheckQuickstart
{
class Program
{
// In production, make sure you're pulling the subscription key from secured storage.
private static string _subscriptionKey = "<YOUR SUBSCRIPTION KEY GOES HERE>";
private static string _baseUri = "https://api.bing.microsoft.com/v7.0/spellcheck";
// The query parameters you're most likely to use.
private const string TEXT_PARAMETER = "?text="; // Required
private const string MKT_PARAMETER = "&mkt="; // Strongly suggested
private const string MODE_PARAMETER = "&mode="; // proof (default), spell
// The text to spell check.
private static string _spellCheckString = "when its your turn turn, john, come runing";
static void Main()
{
RunAsync().Wait();
}
static async Task RunAsync()
{
try
{
// Remember to encode the text query parameter.
var queryString = TEXT_PARAMETER + Uri.EscapeDataString(_spellCheckString);
queryString += MODE_PARAMETER + "proof"; // "spell";
queryString += MKT_PARAMETER + "en-us";
HttpResponseMessage 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)
{
PrintSpellCheckResults(searchResponse);
}
else
{
PrintErrors(response.Headers, searchResponse);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine("\nPress ENTER to exit...");
Console.ReadLine();
}
// Makes the request to the Spell Check endpoint.
static 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 list of spelling issues and the corrected string.
static void PrintSpellCheckResults(Dictionary<string, object> response)
{
string updatedTextString = _spellCheckString;
int adjustOffset = 0;
int tokenLength = 0;
bool isRemoveTokenCase = false;
Console.WriteLine("The response contains the following spelling issues:\n");
var tokens = response["flaggedTokens"] as Newtonsoft.Json.Linq.JToken;
foreach (Newtonsoft.Json.Linq.JToken token in tokens)
{
Console.WriteLine("Word: " + token["token"]);
Console.WriteLine("Suggestion: " + token["suggestions"][0]["suggestion"]);
Console.WriteLine("Offset: " + token["offset"]);
Console.WriteLine();
tokenLength = ((string)token["token"]).Length;
// Repeat token case
if ((string)(token["suggestions"][0]["suggestion"]) == string.Empty)
{
isRemoveTokenCase = true;
adjustOffset--;
tokenLength++;
}
updatedTextString = updatedTextString.Remove((int)token["offset"] + adjustOffset, tokenLength);
if (!isRemoveTokenCase)
{
updatedTextString = updatedTextString.Insert((int)token["offset"] + adjustOffset, (string)token["suggestions"][0]["suggestion"]);
}
else
{
isRemoveTokenCase = false;
adjustOffset++;
}
// The token offset value is the offset into the original string but
// we need the offset into the updated text string after applying the
// changes.
adjustOffset += ((string)token["suggestions"][0]["suggestion"]).Length - tokenLength;
}
Console.WriteLine("Original text: " + _spellCheckString);
Console.WriteLine("Updated text: " + updatedTextString);
}
// Print any errors that occur. Depending on which part of the service is
// throwing the error, the response may contain different formats.
static 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());
}
}
}
static 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);
}
}
}
}

Просмотреть файл

@ -0,0 +1,195 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Threading.Tasks;
using System.Linq;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace SpellCheckQuickstart
{
class Program
{
// In production, make sure you're pulling the subscription key from secured storage.
private static string _subscriptionKey = "<YOUR SUBSCRIPTION KEY GOES HERE>";
private static string _baseUri = "https://api.bing.microsoft.com/v7.0/spellcheck";
// The query parameters you're most likely to use.
private const string TEXT_PARAMETER = "text="; // Required
private const string MKT_PARAMETER = "&mkt="; // Strongly suggested
private const string MODE_PARAMETER = "&mode="; // proof (default), spell
// The text to spell check.
private static string _spellCheckString = "when its your turn turn, john, come runing";
static void Main()
{
RunAsync().Wait();
}
static async Task RunAsync()
{
try
{
// Remember to encode the q query parameter.
var queryString = TEXT_PARAMETER + Uri.EscapeDataString(_spellCheckString);
queryString += MODE_PARAMETER + "proof"; // "spell";
queryString += MKT_PARAMETER + "en-us";
HttpResponseMessage 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)
{
PrintSpellCheckResults(searchResponse);
}
else
{
PrintErrors(response.Headers, searchResponse);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine("\nPress ENTER to exit...");
Console.ReadLine();
}
// Makes the request to the Spell Check endpoint.
static 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);
var postContent = new StringContent(queryString, System.Text.Encoding.UTF8, "application/x-www-form-urlencoded");
return (await client.PostAsync(_baseUri, postContent));
}
// Prints the list of spelling issues and the corrected string.
static void PrintSpellCheckResults(Dictionary<string, object> response)
{
string updatedTextString = _spellCheckString;
int adjustOffset = 0;
int tokenLength = 0;
bool isRemoveTokenCase = false;
Console.WriteLine("The response contains the following spelling issues:\n");
var tokens = response["flaggedTokens"] as Newtonsoft.Json.Linq.JToken;
foreach (Newtonsoft.Json.Linq.JToken token in tokens)
{
Console.WriteLine("Word: " + token["token"]);
Console.WriteLine("Suggestion: " + token["suggestions"][0]["suggestion"]);
Console.WriteLine("Offset: " + token["offset"]);
Console.WriteLine();
tokenLength = ((string)token["token"]).Length;
// Repeat token case
if ((string)(token["suggestions"][0]["suggestion"]) == string.Empty)
{
isRemoveTokenCase = true;
adjustOffset--;
tokenLength++;
}
updatedTextString = updatedTextString.Remove((int)token["offset"] + adjustOffset, tokenLength);
if (!isRemoveTokenCase)
{
updatedTextString = updatedTextString.Insert((int)token["offset"] + adjustOffset, (string)token["suggestions"][0]["suggestion"]);
}
else
{
isRemoveTokenCase = false;
adjustOffset++;
}
// The token offset value is the offset into the original string but
// we need the offset into the updated text string after applying the
// changes.
adjustOffset += ((string)token["suggestions"][0]["suggestion"]).Length - tokenLength;
}
Console.WriteLine("Original text: " + _spellCheckString);
Console.WriteLine("Updated text: " + updatedTextString);
}
// Print any errors that occur. Depending on which part of the service is
// throwing the error, the response may contain different formats.
static 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());
}
}
}
static 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);
}
}
}
}

Просмотреть файл

@ -0,0 +1,246 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Xml;
using System.Threading.Tasks;
using System.Linq;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace VideoSearchQuickstart
{
class Program
{
// In production, make sure you're pulling the subscription key from secured storage.
private static string _subscriptionKey = "<YOUR SUBSCRIPTION KEY GOES HERE>";
private static string _baseUri = "https://api.bing.microsoft.com/v7.0/videos/search";
// Each of the query parameters you may specify.
private const string QUERY_PARAMETER = "?q="; // Required
private const string MKT_PARAMETER = "&mkt="; // Strongly suggested
private const string COUNT_PARAMETER = "&count=";
private const string OFFSET_PARAMETER = "&offset=";
private const string ID_PARAMETER = "&id=";
private const string SAFE_SEARCH_PARAMETER = "&safeSearch=";
// Each of the filter query parameters you may specify.
private const string ASPECT_PARAMETER = "&aspect=";
private const string EMBEDDED_PARAMETER = "&embedded=";
private const string FRESHNESS_PARAMETER = "&freshness=";
private const string PRICING_PARAMETER = "&pricing=";
private const string RESOLUTION_PARAMETER = "&resolution=";
private const string VIDEO_LENGTH_PARAMETER = "&videoLength=";
// The user's search string.
private static string _searchString = "hummingbird";
// To page through images, you'll need the next offset that Bing returns.
private static long _nextOffset = 0;
// Bing uses the X-MSEdge-ClientID header to provide users with consistent
// behavior across Bing API calls. See the reference documentation
// for usage.
private static string _clientIdHeader = null;
static void Main()
{
RunAsync().Wait();
}
static async Task RunAsync()
{
try
{
// Remember to encode the q query parameter.
var queryString = QUERY_PARAMETER + Uri.EscapeDataString(_searchString);
queryString += MKT_PARAMETER + "en-us";
HttpResponseMessage response = await MakeRequestAsync(queryString);
_clientIdHeader = response.Headers.GetValues("X-MSEdge-ClientID").FirstOrDefault();
// 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)
{
PrintVideos(searchResponse);
}
else
{
PrintErrors(response.Headers, searchResponse);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine("\nPress ENTER to exit...");
Console.ReadLine();
}
// Makes the request to the Video Search endpoint.
static 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 list of videos in the JSON response.
static void PrintVideos(Dictionary<string, object> response)
{
Newtonsoft.Json.Linq.JToken value = null;
Console.WriteLine("The response contains the following videos:\n");
// This example just prints the first page of videos. If you want to page
// through the videos, set the offset query parameter to the next offset
// value that Bing returns.
_nextOffset = (long)response["nextOffset"];
var videos = response["value"] as Newtonsoft.Json.Linq.JToken;
foreach (Newtonsoft.Json.Linq.JToken video in videos)
{
Console.WriteLine("Title: " + video["name"]);
Console.WriteLine("Thumbnail: " + video["thumbnailUrl"]);
Console.WriteLine("Thumbnail size: {0} (w) x {1} (h) ", video["thumbnail"]["width"], video["thumbnail"]["height"]);
Console.WriteLine("Source video: " + video["contentUrl"]);
Console.WriteLine("Source video size: {0} (w) x {1} (h) ", video["width"], video["height"]);
Console.WriteLine("Publisher: " + GetPublisherString(video["publisher"]));
if ((value = video["creator"]) != null)
{
Console.WriteLine("Creator: " + (string)value["name"]);
}
// Always good to indicate how many people watched the video
// on the source website, and how long the video is.
if ((value = video["viewCount"]) != null)
{
Console.WriteLine("Views: " + (long)value);
}
if ((value = video["duration"]) != null)
{
TimeSpan ts = XmlConvert.ToTimeSpan((string)value);
Console.WriteLine("Length: " + ts.ToString());
}
// If the video includes the motionThumbnailUrl, use it to play
// a preview of the video as the user hovers over the thumbnail.
if ((value = video["motionThumbnailUrl"]) != null)
{
Console.WriteLine("Motion thumbnail: " + (string)value);
}
if ((value = video["embedHtml"]) != null)
{
Console.WriteLine("Embed HTML: " + (string)value);
}
Console.WriteLine();
}
}
// Get a printable publisher string. The video's publisher field is an array
// of publishers. In practice, there's a single publisher, but...
static string GetPublisherString(Newtonsoft.Json.Linq.JToken publishers)
{
string publisherString = "";
Boolean isFirst = true;
foreach (Newtonsoft.Json.Linq.JToken publisher in publishers)
{
if (!isFirst)
{
publisherString += " | ";
}
publisherString += publisher["name"];
}
return publisherString;
}
// Print any errors that occur. Depending on which part of the service is
// throwing the error, the response may contain different formats.
static 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());
}
}
}
static 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);
}
}
}
}

Просмотреть файл

@ -0,0 +1,509 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Threading.Tasks;
using System.Linq;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Globalization;
namespace VisualSearchQuickstart
{
class Program
{
// In production, make sure you're pulling the subscription key from secured storage.
private static string _subscriptionKey = "<YOUR SUBSCRIPTION KEY GOES HERE>";
private static string _baseUri = "https://api.bing.microsoft.com/v7.0/images/visualsearch";
// Each of the query parameters you may specify.
private const string MKT_PARAMETER = "?mkt="; // Strongly suggested
private const string SAFE_SEARCH_PARAMETER = "&safeSearch=";
// To page through visually similar images, you'll need the next offset that Bing returns.
private static long _nextOffset = 0;
// To get additional insights about the image, you'll need the image's
// insights token (see Image Search API), URL, or binary.
private static string _insightsToken = null;
private static string _imageUrl = null;
// Bing uses the X-MSEdge-ClientID header to provide users with consistent
// behavior across Bing API calls. See the reference documentation
// for usage.
private static string _clientIdHeader = null;
static void Main()
{
RunAsync().Wait();
}
static async Task RunAsync()
{
try
{
var queryString = MKT_PARAMETER + "en-us";
// Build the form data. This example passes an insights token from
// an Image Search API result. It also includes the enable entity
// flag to include entity data in the response if applicable.
using (var postContent = new MultipartFormDataContent("boundary_" + DateTime.Now.ToString(CultureInfo.InvariantCulture)))
{
var visualSearchParams = new Dictionary<string, object>()
{
{"ImageInfo", new Dictionary<string, object>()
{
{"ImageInsightsToken", _insightsToken}
}
},
{"KnowledgeRequest", new Dictionary<string, object>()
{
{"InvokedSkillsRequestData", new Dictionary<string, object>()
{
{"EnableEntityData", true}
}
}
}
}
};
using (var jsonContent = new StringContent(JsonConvert.SerializeObject(visualSearchParams,
new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore })))
{
var dispositionHeader = new ContentDispositionHeaderValue("form-data");
dispositionHeader.Name = "knowledgeRequest";
jsonContent.Headers.ContentDisposition = dispositionHeader;
jsonContent.Headers.ContentType = null;
postContent.Add(jsonContent);
HttpResponseMessage response = await MakeRequestAsync(queryString, postContent);
// Get the client ID to use in the next request. See documentation for usage.
IEnumerable<string> values;
if (response.Headers.TryGetValues("X-MSEdge-ClientID", out values))
{
_clientIdHeader = values.FirstOrDefault();
}
// 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)
{
PrintInsights(searchResponse);
}
else
{
PrintErrors(response.Headers, searchResponse);
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine("\nPress ENTER to exit...");
Console.ReadLine();
}
// Makes the request to the Spell Check endpoint.
static async Task<HttpResponseMessage> MakeRequestAsync(string queryString, MultipartFormDataContent postContent)
{
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.PostAsync(_baseUri + queryString, postContent));
}
// Prints insights about the image.
static void PrintInsights(Dictionary<string, object> response)
{
Console.WriteLine("The response contains the following insights:\n");
var tags = response["tags"] as Newtonsoft.Json.Linq.JToken;
foreach (Newtonsoft.Json.Linq.JToken tag in tags)
{
var displayName = (string)tag["displayName"];
if (string.IsNullOrEmpty(displayName))
{
// Handle default insights.
PrintDefaultInsights(tag);
}
else
{
// Contains other tags related to the original search request that the
// user might want to discover. Most will contain URLs to images or
// web search results but there are a couple that you might want to
// pursue: text recognition and entity.
Console.WriteLine("\nTag: {0}\n", (string)tag["displayName"]);
PrintOtherInsights(tag);
}
}
}
// Prints the image's default insights.
static void PrintDefaultInsights(Newtonsoft.Json.Linq.JToken tag)
{
var actions = tag["actions"];
foreach (Newtonsoft.Json.Linq.JToken action in actions)
{
if ((string)action["actionType"] == "PagesIncluding")
{
Console.WriteLine("Webpages that include this image:\n");
DisplayPagesIncluding(action["data"]["value"]);
}
else if ((string)action["actionType"] == "VisualSearch")
{
Console.WriteLine("Images that are visually similar to this image:\n");
DisplaySimilarImages(action["data"]["value"]);
// Capture offset if you're going to page by visually
// similar images.
//_nextOffset = (long)action["data"]["nextOffset"];
}
else if ((string)action["actionType"] == "ProductVisualSearch")
{
Console.WriteLine("Images that have products that are visually similar to the products in this image:\n");
DisplaySimilarImages(action["data"]["value"]);
// Capture offset if you're going to page by images that have products that
// are visually similar to the products in this image.
//_nextOffset = (long)action["data"]["nextOffset"];
}
else if ((string)action["actionType"] == "ShoppingSources")
{
Console.WriteLine("Sites where you can buy the product seen in this image:\n");
DisplayShoppingSources(action["data"]["offers"]);
}
else if ((string)action["actionType"] == "RelatedSearches")
{
Console.WriteLine("Related search strings:\n");
DisplayRelatedSearches(action["data"]["value"]);
}
else
{
Console.WriteLine("{0} - Not parsing\n", (string)action["actionType"]);
}
}
}
// Displays all webpages that include the image.
static void DisplayPagesIncluding(Newtonsoft.Json.Linq.JToken pages)
{
foreach (Newtonsoft.Json.Linq.JToken page in pages)
{
Console.WriteLine("\tWebpage: " + (string)page["hostPageUrl"]);
}
Console.WriteLine();
}
// Displays images that are visually similar to the source image.
static void DisplaySimilarImages(Newtonsoft.Json.Linq.JToken images)
{
foreach (Newtonsoft.Json.Linq.JToken image in images)
{
DisplayImage(image);
}
Console.WriteLine();
}
// Displays websites where you can buy the product seen in the image.
static void DisplayShoppingSources(Newtonsoft.Json.Linq.JToken offers)
{
foreach (Newtonsoft.Json.Linq.JToken offer in offers)
{
Console.WriteLine("\tSeller: {0} ({1})", offer["seller"]["name"], offer["url"]);
Console.WriteLine("\tName: " + offer["name"]);
Console.WriteLine("\tDescription: " + offer["description"]);
Console.WriteLine("\tPrice: {0} {1}", offer["price"], offer["priceCurrency"]);
Console.WriteLine("\tAvailability: " + offer["availability"]);
}
Console.WriteLine();
}
// Displays a single image.
static void DisplayImage(Newtonsoft.Json.Linq.JToken image)
{
Console.WriteLine("\tThumbnail: " + image["thumbnailUrl"]);
Console.WriteLine("\tThumbnail size: {0} (w) x {1} (h) ", image["thumbnail"]["width"], image["thumbnail"]["height"]);
Console.WriteLine("\tOriginal image: " + image["contentUrl"]);
Console.WriteLine("\tOriginal image size: {0} (w) x {1} (h) ", image["width"], image["height"]);
Console.WriteLine("\tHost: {0} ({1})", image["hostPageDomainFriendlyName"], image["hostPageDisplayUrl"]);
Console.WriteLine();
}
// Displays all related searches.
static void DisplayRelatedSearches(Newtonsoft.Json.Linq.JToken relatedSearches)
{
foreach (Newtonsoft.Json.Linq.JToken relatedSearch in relatedSearches)
{
Console.WriteLine("\tSearch string: {0} ({1})", (string)relatedSearch["displayText"], (string)relatedSearch["webSearchUrl"]);
}
Console.WriteLine();
}
static void PrintOtherInsights(Newtonsoft.Json.Linq.JToken tag)
{
var actions = tag["actions"];
foreach (Newtonsoft.Json.Linq.JToken action in actions)
{
if ((string)action["actionType"] == "ImageResults")
{
Console.WriteLine("\tImage search URLs:");
Console.WriteLine("\t\tDisplay name: " + action["displayName"]);
Console.WriteLine("\t\tImage API URL: " + action["serviceUrl"]);
Console.WriteLine("\t\tBing search URL: " + action["webSearchUrl"]);
}
else if ((string)action["actionType"] == "TextResults")
{
Console.WriteLine("\tWeb search URLs:");
Console.WriteLine("\t\tDisplay name: " + action["displayName"]);
Console.WriteLine("\t\tWeb API URL: " + action["serviceUrl"]);
Console.WriteLine("\t\tBing search URL: " + action["webSearchUrl"]);
}
else if ((string)action["actionType"] == "Entity")
{
DisplayEntity(action["data"]);
}
else if ((string)action["actionType"] == "TextRecognition")
{
Console.WriteLine("\tRecognized text strings:\n");
DisplayRecognizedText(action["data"]["regions"]);
}
else
{
Console.WriteLine("\tUnknown action type: {0}\n", (string)action["actionType"]);
}
}
}
// Displays an entity.
static 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"]["thumbnailUrl"]);
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"]);
}
}
Console.WriteLine();
}
// Displays an entity.
static void DisplayRecognizedText(Newtonsoft.Json.Linq.JToken regions)
{
foreach (Newtonsoft.Json.Linq.JToken region in regions)
{
foreach (Newtonsoft.Json.Linq.JToken line in region["lines"])
{
Console.WriteLine("\t\tLine: " + line["text"]);
}
}
}
// Checks if the result includes contractual rules and builds a dictionary of
// the rules.
static 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)
{
// Use the rule's type as the key.
string key = null;
string value = null;
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"];
}
// 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 formats.
static 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());
}
}
}
static 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);
}
}
}
}

Просмотреть файл

@ -0,0 +1,635 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Threading.Tasks;
using System.Linq;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace WebSearchQuickstart
{
static class Program
{
// In production, make sure you're pulling the subscription key from secured storage.
private static string _subscriptionKey = "<YOUR SUBSCRIPTION KEY GOES HERE>";
private static string _baseUri = "https://api.bing.microsoft.com/v7.0/search";
// Each of the query parameters you may specify.
private const string QUERY_PARAMETER = "?q="; // Required
private const string MKT_PARAMETER = "&mkt="; // Strongly suggested
private const string RESPONSE_FILTER_PARAMETER = "&responseFilter=";
private const string COUNT_PARAMETER = "&count=";
private const string OFFSET_PARAMETER = "&offset=";
private const string FRESHNESS_PARAMETER = "&freshness=";
private const string SAFE_SEARCH_PARAMETER = "&safeSearch=";
private const string TEXT_DECORATIONS_PARAMETER = "&textDecorations=";
private const string TEXT_FORMAT_PARAMETER = "&textFormat=";
private const string ANSWER_COUNT = "&answerCount=";
private const string PROMOTE = "&promote=";
// The user's search string.
private static string searchString = "coronavirus vaccine";
// Bing uses the X-MSEdge-ClientID header to provide users with consistent
// behavior across Bing API calls. See the the reference documentation
// fo usage.
private static string _clientIdHeader = null;
static void Main()
{
RunAsync().Wait();
}
static async Task RunAsync()
{
try
{
// 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;
HttpResponseMessage response = await MakeRequestAsync(queryString);
_clientIdHeader = response.Headers.GetValues("X-MSEdge-ClientID").FirstOrDefault();
// 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.Message);
}
Console.WriteLine("\nPress ENTER to exit...");
Console.ReadLine();
}
// Makes the request to the Web Search endpoint.
static 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.
static 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.
static 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.
static void DisplayAllWebPages(Newtonsoft.Json.Linq.JToken webpages)
{
foreach (Newtonsoft.Json.Linq.JToken webpage in webpages)
{
DisplayWegPage(webpage);
}
}
// Displays a single webpage.
static 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.
static void DisplayAllImages(Newtonsoft.Json.Linq.JToken images)
{
foreach (Newtonsoft.Json.Linq.JToken image in images)
{
DisplayImage(image);
}
}
// Displays a single image.
static 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.
static void DisplayAllVideos(Newtonsoft.Json.Linq.JToken videos)
{
foreach (Newtonsoft.Json.Linq.JToken video in videos)
{
DisplayVideo(video);
}
}
// Displays a single video.
static 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.
static void DisplayAllNews(Newtonsoft.Json.Linq.JToken news)
{
foreach (Newtonsoft.Json.Linq.JToken article in news)
{
DisplayArticle(article);
}
}
// Displays a single news article.
static 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.
static void DisplayAllRelatedSearches(Newtonsoft.Json.Linq.JToken searches)
{
foreach (Newtonsoft.Json.Linq.JToken search in searches)
{
DisplayRelatedSearch(search);
}
}
// Displays a single related search query.
static 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.
static void DisplayAllEntities(Newtonsoft.Json.Linq.JToken entities)
{
foreach (Newtonsoft.Json.Linq.JToken entity in entities)
{
DisplayEntity(entity);
}
}
// Displays a single entity.
static 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"]["thumbnailUrl"]);
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.
static void DisplayAllPlaces(Newtonsoft.Json.Linq.JToken places)
{
foreach (Newtonsoft.Json.Linq.JToken place in places)
{
DisplayPlace(place);
}
}
// Displays a single place.
static 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.
static 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.
static 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.
static 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.
static 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)
{
// Use the rule's type as the key.
string key = null;
string value = null;
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"];
}
// 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 formats.
static 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());
}
}
}
static 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);
}
}
}
}

Просмотреть файл

@ -0,0 +1,743 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.AutoSuggest
{
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Autosuggest supplies search terms derived from a root text sent to the
/// service. The terms Autosuggest supplies are related to the root text
/// based on similarity and their frequency or ratings of usefulness in
/// other searches. For examples that show how to use Autosuggest, see
/// [Search using
/// AutoSuggest](https://docs.microsoft.com/en-us/bing/bing-autosuggest/overview).
/// </summary>
public partial class AutoSuggestClient : ServiceClient<AutoSuggestClient>, IAutoSuggestClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Subscription credentials which uniquely identify client subscription.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Initializes a new instance of the AutoSuggestClient class.
/// </summary>
/// <param name='httpClient'>
/// HttpClient to be used
/// </param>
/// <param name='disposeHttpClient'>
/// True: will dispose the provided httpClient on calling AutoSuggestClient.Dispose(). False: will not dispose provided httpClient</param>
protected AutoSuggestClient(HttpClient httpClient, bool disposeHttpClient) : base(httpClient, disposeHttpClient)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoSuggestClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AutoSuggestClient(params DelegatingHandler[] handlers) : base(handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoSuggestClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AutoSuggestClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoSuggestClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected AutoSuggestClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AutoSuggestClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected AutoSuggestClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AutoSuggestClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Subscription credentials which uniquely identify client subscription.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoSuggestClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoSuggestClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Subscription credentials which uniquely identify client subscription.
/// </param>
/// <param name='httpClient'>
/// HttpClient to be used
/// </param>
/// <param name='disposeHttpClient'>
/// True: will dispose the provided httpClient on calling AutoSuggestClient.Dispose(). False: will not dispose provided httpClient</param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoSuggestClient(ServiceClientCredentials credentials, HttpClient httpClient, bool disposeHttpClient) : this(httpClient, disposeHttpClient)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoSuggestClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Subscription credentials which uniquely identify client subscription.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoSuggestClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoSuggestClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Subscription credentials which uniquely identify client subscription.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoSuggestClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoSuggestClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Subscription credentials which uniquely identify client subscription.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoSuggestClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
///</summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
BaseUri = new System.Uri("https://api.bing.microsoft.com/v7.0");
SerializationSettings = new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
CustomInitialize();
}
/// <summary>
/// The AutoSuggest API lets you send a search query to Bing and get back a
/// list of query suggestions. This section provides technical details about
/// the query parameters and headers that you use to request suggestions and
/// the JSON response objects that contain them.
/// </summary>
/// <param name='query'>
/// The user's search term.
/// </param>
/// <param name='acceptLanguage'>
/// A comma-delimited list of one or more languages to use for user interface
/// strings. The list is in decreasing order of preference. For additional
/// information, including expected format, see
/// [RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). This
/// header and the setLang query parameter are mutually exclusive; do not
/// specify both. If you set this header, you must also specify the
/// [cc](https://docs.microsoft.com/en-us/bing/bing-autosuggest/overview) query
/// parameter. To determine the market to return results for, Bing uses the
/// first supported language it finds from the list and combines it with the cc
/// parameter value. If the list does not include a supported language, Bing
/// finds the closest language and market that supports the request or it uses
/// an aggregated or default market for the results. To determine the market
/// that Bing used, see the BingAPIs-Market header. Use this header and the cc
/// query parameter only if you specify multiple languages. Otherwise, use the
/// [mkt](https://docs.microsoft.com/en-us/bing/bing-autosuggest/overview) and
/// [setLang](https://docs.microsoft.com/en-us/bing/bing-autosuggest/overview)
/// query parameters. A user interface string is a string that's used as a
/// label in a user interface. There are few user interface strings in the JSON
/// response objects. Any links to Bing.com properties in the response objects
/// apply the specified language.
/// </param>
/// <param name='pragma'>
/// By default, Bing returns cached content, if available. To prevent Bing from
/// returning cached content, set the Pragma header to no-cache (for example,
/// Pragma: no-cache).
/// </param>
/// <param name='userAgent'>
/// The user agent originating the request. Bing uses the user agent to provide
/// mobile users with an optimized experience. Although optional, you are
/// encouraged to always specify this header. The user-agent should be the same
/// string that any commonly used browser sends. For information about user
/// agents, see [RFC
/// 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). The
/// following are examples of user-agent strings. Windows Phone: Mozilla/5.0
/// (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM;
/// Touch; NOKIA; Lumia 822). Android: Mozilla / 5.0 (Linux; U; Android 2.3.5;
/// en - us; SCH - I500 Build / GINGERBREAD) AppleWebKit / 533.1 (KHTML; like
/// Gecko) Version / 4.0 Mobile Safari / 533.1. iPhone: Mozilla / 5.0 (iPhone;
/// CPU iPhone OS 6_1 like Mac OS X) AppleWebKit / 536.26 (KHTML; like Gecko)
/// Mobile / 10B142 iPhone4; 1 BingWeb / 3.03.1428.20120423. PC: Mozilla / 5.0
/// (Windows NT 6.3; WOW64; Trident / 7.0; Touch; rv:11.0) like Gecko. iPad:
/// Mozilla / 5.0 (iPad; CPU OS 7_0 like Mac OS X) AppleWebKit / 537.51.1
/// (KHTML, like Gecko) Version / 7.0 Mobile / 11A465 Safari / 9537.53
/// </param>
/// <param name='clientId'>
/// Bing uses this header to provide users with consistent behavior across Bing
/// API calls. Bing often flights new features and improvements, and it uses
/// the client ID as a key for assigning traffic on different flights. If you
/// do not use the same client ID for a user across multiple requests, then
/// Bing may assign the user to multiple conflicting flights. Being assigned to
/// multiple conflicting flights can lead to an inconsistent user experience.
/// For example, if the second request has a different flight assignment than
/// the first, the experience may be unexpected. Also, Bing can use the client
/// ID to tailor web results to that client IDs search history, providing a
/// richer experience for the user. Bing also uses this header to help improve
/// result rankings by analyzing the activity generated by a client ID. The
/// relevance improvements help with better quality of results delivered by
/// Bing APIs and in turn enables higher click-through rates for the API
/// consumer. IMPORTANT: Although optional, you should consider this header
/// required. Persisting the client ID across multiple requests for the same
/// end user and device combination enables 1) the API consumer to receive a
/// consistent user experience, and 2) higher click-through rates via better
/// quality of results from the Bing APIs. Each user that uses your application
/// on the device must have a unique, Bing generated client ID. If you do not
/// include this header in the request, Bing generates an ID and returns it in
/// the X-MSEdge-ClientID response header. The only time that you should NOT
/// include this header in a request is the first time the user uses your app
/// on that device. Use the client ID for each Bing API request that your app
/// makes for this user on the device. Persist the client ID. To persist the ID
/// in a browser app, use a persistent HTTP cookie to ensure the ID is used
/// across all sessions. Do not use a session cookie. For other apps such as
/// mobile apps, use the device's persistent storage to persist the ID. The
/// next time the user uses your app on that device, get the client ID that you
/// persisted. Bing responses may or may not include this header. If the
/// response includes this header, capture the client ID and use it for all
/// subsequent Bing requests for the user on that device. If you include the
/// X-MSEdge-ClientID, you must not include cookies in the request.
/// </param>
/// <param name='clientIp'>
/// The IPv4 or IPv6 address of the client device. The IP address is used to
/// discover the user's location. Bing uses the location information to
/// determine safe search behavior. Although optional, you are encouraged to
/// always specify this header and the X-Search-Location header. Do not
/// obfuscate the address (for example, by changing the last octet to 0).
/// Obfuscating the address results in the location not being anywhere near the
/// device's actual location, which may result in Bing serving erroneous
/// results.
/// </param>
/// <param name='location'>
/// A semicolon-delimited list of key/value pairs that describe the client's
/// geographical location. Bing uses the location information to determine safe
/// search behavior and to return relevant local content. Specify the key/value
/// pair as &lt;key&gt;:&lt;value&gt;. The following are the keys that you use
/// to specify the user's location. lat (required): The latitude of the
/// client's location, in degrees. The latitude must be greater than or equal
/// to -90.0 and less than or equal to +90.0. Negative values indicate southern
/// latitudes and positive values indicate northern latitudes. long (required):
/// The longitude of the client's location, in degrees. The longitude must be
/// greater than or equal to -180.0 and less than or equal to +180.0. Negative
/// values indicate western longitudes and positive values indicate eastern
/// longitudes. re (required): The radius, in meters, which specifies the
/// horizontal accuracy of the coordinates. Pass the value returned by the
/// device's location service. Typical values might be 22m for GPS/Wi-Fi, 380m
/// for cell tower triangulation, and 18,000m for reverse IP lookup. ts
/// (optional): The UTC UNIX timestamp of when the client was at the location.
/// (The UNIX timestamp is the number of seconds since January 1, 1970.) head
/// (optional): The client's relative heading or direction of travel. Specify
/// the direction of travel as degrees from 0 through 360, counting clockwise
/// relative to true north. Specify this key only if the sp key is nonzero. sp
/// (optional): The horizontal velocity (speed), in meters per second, that the
/// client device is traveling. alt (optional): The altitude of the client
/// device, in meters. are (optional): The radius, in meters, that specifies
/// the vertical accuracy of the coordinates. Specify this key only if you
/// specify the alt key. Although many of the keys are optional, the more
/// information that you provide, the more accurate the location results are.
/// Although optional, you are encouraged to always specify the user's
/// geographical location. Providing the location is especially important if
/// the client's IP address does not accurately reflect the user's physical
/// location (for example, if the client uses VPN). For optimal results, you
/// should include this header and the X-MSEdge-ClientIP header, but at a
/// minimum, you should include this header.
/// </param>
/// <param name='countryCode'>
/// A 2-character country code of the country where the results come from. This
/// API supports only the United States market. If you specify this query
/// parameter, it must be set to us. If you set this parameter, you must also
/// specify the Accept-Language header. Bing uses the first supported language
/// it finds from the languages list, and combine that language with the
/// country code that you specify to determine the market to return results
/// for. If the languages list does not include a supported language, Bing
/// finds the closest language and market that supports the request, or it may
/// use an aggregated or default market for the results instead of a specified
/// one. You should use this query parameter and the Accept-Language query
/// parameter only if you specify multiple languages; otherwise, you should use
/// the mkt and setLang query parameters. This parameter and the mkt query
/// parameter are mutually exclusive—do not specify both.
/// </param>
/// <param name='market'>
/// The market where the results come from. You are strongly encouraged to
/// always specify the market, if known. Specifying the market helps Bing route
/// the request and return an appropriate and optimal response. This parameter
/// and the cc query parameter are mutually exclusive—do not specify both.
/// </param>
/// <param name='safeSearch'>
/// Filter suggestions for adult content. The following are the possible filter
/// values. Off: Return suggestions with adult text, images, or videos.
/// Moderate: Return suggestion with adult text but not adult images or videos.
/// Strict: Do not return news articles with adult text, images, or videos. If
/// the request comes from a market that Bing's adult policy requires that
/// safeSearch is set to Strict, Bing ignores the safeSearch value and uses
/// Strict. If you use the site: query operator, there is the chance that the
/// response may contain adult content regardless of what the safeSearch query
/// parameter is set to. Use site: only if you are aware of the content on the
/// site and your scenario supports the possibility of adult content. Possible
/// values include: 'Off', 'Moderate', 'Strict'
/// </param>
/// <param name='setLang'>
/// The language to use for user interface strings. Specify the language using
/// the ISO 639-1 2-letter language code. For example, the language code for
/// English is EN. The default is EN (English). Although optional, you should
/// always specify the language. Typically, you set setLang to the same
/// language specified by mkt unless the user wants the user interface strings
/// displayed in a different language. This parameter and the Accept-Language
/// header are mutually exclusive; do not specify both. A user interface string
/// is a string that's used as a label in a user interface. There are few user
/// interface strings in the JSON response objects. Also, any links to Bing.com
/// properties in the response objects apply the specified language.
/// </param>
/// <param name='responseFormat'>
/// The media type to use for the response. The following are the possible
/// case-insensitive values: JSON, JSONLD. The default is JSON. If you specify
/// JSONLD, the response body includes JSON-LD objects that contain the search
/// results.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<Suggestions>> AutoSuggestMethodWithHttpMessagesAsync(string query, string acceptLanguage = default(string), string pragma = default(string), string userAgent = default(string), string clientId = default(string), string clientIp = default(string), string location = default(string), string countryCode = default(string), string market = "en-us", string safeSearch = default(string), string setLang = default(string), IList<string> responseFormat = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (query == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "query");
}
string xBingApisSDK = "true";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("xBingApisSDK", xBingApisSDK);
tracingParameters.Add("acceptLanguage", acceptLanguage);
tracingParameters.Add("pragma", pragma);
tracingParameters.Add("userAgent", userAgent);
tracingParameters.Add("clientId", clientId);
tracingParameters.Add("clientIp", clientIp);
tracingParameters.Add("location", location);
tracingParameters.Add("countryCode", countryCode);
tracingParameters.Add("market", market);
tracingParameters.Add("query", query);
tracingParameters.Add("safeSearch", safeSearch);
tracingParameters.Add("setLang", setLang);
tracingParameters.Add("responseFormat", responseFormat);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "AutoSuggestMethod", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Suggestions").ToString();
List<string> _queryParameters = new List<string>();
if (countryCode != null)
{
_queryParameters.Add(string.Format("cc={0}", System.Uri.EscapeDataString(countryCode)));
}
if (market != null)
{
_queryParameters.Add(string.Format("mkt={0}", System.Uri.EscapeDataString(market)));
}
if (query != null)
{
_queryParameters.Add(string.Format("q={0}", System.Uri.EscapeDataString(query)));
}
if (safeSearch != null)
{
_queryParameters.Add(string.Format("safeSearch={0}", System.Uri.EscapeDataString(safeSearch)));
}
if (setLang != null)
{
_queryParameters.Add(string.Format("setLang={0}", System.Uri.EscapeDataString(setLang)));
}
if (responseFormat != null)
{
_queryParameters.Add(string.Format("ResponseFormat={0}", System.Uri.EscapeDataString(string.Join(",", responseFormat))));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (xBingApisSDK != null)
{
if (_httpRequest.Headers.Contains("X-BingApis-SDK"))
{
_httpRequest.Headers.Remove("X-BingApis-SDK");
}
_httpRequest.Headers.TryAddWithoutValidation("X-BingApis-SDK", xBingApisSDK);
}
if (acceptLanguage != null)
{
if (_httpRequest.Headers.Contains("Accept-Language"))
{
_httpRequest.Headers.Remove("Accept-Language");
}
_httpRequest.Headers.TryAddWithoutValidation("Accept-Language", acceptLanguage);
}
if (pragma != null)
{
if (_httpRequest.Headers.Contains("Pragma"))
{
_httpRequest.Headers.Remove("Pragma");
}
_httpRequest.Headers.TryAddWithoutValidation("Pragma", pragma);
}
if (userAgent != null)
{
if (_httpRequest.Headers.Contains("User-Agent"))
{
_httpRequest.Headers.Remove("User-Agent");
}
_httpRequest.Headers.TryAddWithoutValidation("User-Agent", userAgent);
}
if (clientId != null)
{
if (_httpRequest.Headers.Contains("X-MSEdge-ClientID"))
{
_httpRequest.Headers.Remove("X-MSEdge-ClientID");
}
_httpRequest.Headers.TryAddWithoutValidation("X-MSEdge-ClientID", clientId);
}
if (clientIp != null)
{
if (_httpRequest.Headers.Contains("X-MSEdge-ClientIP"))
{
_httpRequest.Headers.Remove("X-MSEdge-ClientIP");
}
_httpRequest.Headers.TryAddWithoutValidation("X-MSEdge-ClientIP", clientIp);
}
if (location != null)
{
if (_httpRequest.Headers.Contains("X-Search-Location"))
{
_httpRequest.Headers.Remove("X-Search-Location");
}
_httpRequest.Headers.TryAddWithoutValidation("X-Search-Location", location);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Suggestions>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Suggestions>(_responseContent, DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}

Просмотреть файл

@ -0,0 +1,411 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.AutoSuggest
{
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for AutoSuggestClient.
/// </summary>
public static partial class AutoSuggestClientExtensions
{
/// <summary>
/// The AutoSuggest API lets you send a search query to Bing and get back a
/// list of query suggestions. This section provides technical details about
/// the query parameters and headers that you use to request suggestions and
/// the JSON response objects that contain them.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='query'>
/// The user's search term.
/// </param>
/// <param name='acceptLanguage'>
/// A comma-delimited list of one or more languages to use for user interface
/// strings. The list is in decreasing order of preference. For additional
/// information, including expected format, see
/// [RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). This
/// header and the setLang query parameter are mutually exclusive; do not
/// specify both. If you set this header, you must also specify the
/// [cc](https://docs.microsoft.com/en-us/bing/bing-autosuggest/overview) query
/// parameter. To determine the market to return results for, Bing uses the
/// first supported language it finds from the list and combines it with the cc
/// parameter value. If the list does not include a supported language, Bing
/// finds the closest language and market that supports the request or it uses
/// an aggregated or default market for the results. To determine the market
/// that Bing used, see the BingAPIs-Market header. Use this header and the cc
/// query parameter only if you specify multiple languages. Otherwise, use the
/// [mkt](https://docs.microsoft.com/en-us/bing/bing-autosuggest/overview) and
/// [setLang](https://docs.microsoft.com/en-us/bing/bing-autosuggest/overview)
/// query parameters. A user interface string is a string that's used as a
/// label in a user interface. There are few user interface strings in the JSON
/// response objects. Any links to Bing.com properties in the response objects
/// apply the specified language.
/// </param>
/// <param name='pragma'>
/// By default, Bing returns cached content, if available. To prevent Bing from
/// returning cached content, set the Pragma header to no-cache (for example,
/// Pragma: no-cache).
/// </param>
/// <param name='userAgent'>
/// The user agent originating the request. Bing uses the user agent to provide
/// mobile users with an optimized experience. Although optional, you are
/// encouraged to always specify this header. The user-agent should be the same
/// string that any commonly used browser sends. For information about user
/// agents, see [RFC
/// 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). The
/// following are examples of user-agent strings. Windows Phone: Mozilla/5.0
/// (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM;
/// Touch; NOKIA; Lumia 822). Android: Mozilla / 5.0 (Linux; U; Android 2.3.5;
/// en - us; SCH - I500 Build / GINGERBREAD) AppleWebKit / 533.1 (KHTML; like
/// Gecko) Version / 4.0 Mobile Safari / 533.1. iPhone: Mozilla / 5.0 (iPhone;
/// CPU iPhone OS 6_1 like Mac OS X) AppleWebKit / 536.26 (KHTML; like Gecko)
/// Mobile / 10B142 iPhone4; 1 BingWeb / 3.03.1428.20120423. PC: Mozilla / 5.0
/// (Windows NT 6.3; WOW64; Trident / 7.0; Touch; rv:11.0) like Gecko. iPad:
/// Mozilla / 5.0 (iPad; CPU OS 7_0 like Mac OS X) AppleWebKit / 537.51.1
/// (KHTML, like Gecko) Version / 7.0 Mobile / 11A465 Safari / 9537.53
/// </param>
/// <param name='clientId'>
/// Bing uses this header to provide users with consistent behavior across Bing
/// API calls. Bing often flights new features and improvements, and it uses
/// the client ID as a key for assigning traffic on different flights. If you
/// do not use the same client ID for a user across multiple requests, then
/// Bing may assign the user to multiple conflicting flights. Being assigned to
/// multiple conflicting flights can lead to an inconsistent user experience.
/// For example, if the second request has a different flight assignment than
/// the first, the experience may be unexpected. Also, Bing can use the client
/// ID to tailor web results to that client IDs search history, providing a
/// richer experience for the user. Bing also uses this header to help improve
/// result rankings by analyzing the activity generated by a client ID. The
/// relevance improvements help with better quality of results delivered by
/// Bing APIs and in turn enables higher click-through rates for the API
/// consumer. IMPORTANT: Although optional, you should consider this header
/// required. Persisting the client ID across multiple requests for the same
/// end user and device combination enables 1) the API consumer to receive a
/// consistent user experience, and 2) higher click-through rates via better
/// quality of results from the Bing APIs. Each user that uses your application
/// on the device must have a unique, Bing generated client ID. If you do not
/// include this header in the request, Bing generates an ID and returns it in
/// the X-MSEdge-ClientID response header. The only time that you should NOT
/// include this header in a request is the first time the user uses your app
/// on that device. Use the client ID for each Bing API request that your app
/// makes for this user on the device. Persist the client ID. To persist the ID
/// in a browser app, use a persistent HTTP cookie to ensure the ID is used
/// across all sessions. Do not use a session cookie. For other apps such as
/// mobile apps, use the device's persistent storage to persist the ID. The
/// next time the user uses your app on that device, get the client ID that you
/// persisted. Bing responses may or may not include this header. If the
/// response includes this header, capture the client ID and use it for all
/// subsequent Bing requests for the user on that device. If you include the
/// X-MSEdge-ClientID, you must not include cookies in the request.
/// </param>
/// <param name='clientIp'>
/// The IPv4 or IPv6 address of the client device. The IP address is used to
/// discover the user's location. Bing uses the location information to
/// determine safe search behavior. Although optional, you are encouraged to
/// always specify this header and the X-Search-Location header. Do not
/// obfuscate the address (for example, by changing the last octet to 0).
/// Obfuscating the address results in the location not being anywhere near the
/// device's actual location, which may result in Bing serving erroneous
/// results.
/// </param>
/// <param name='location'>
/// A semicolon-delimited list of key/value pairs that describe the client's
/// geographical location. Bing uses the location information to determine safe
/// search behavior and to return relevant local content. Specify the key/value
/// pair as &lt;key&gt;:&lt;value&gt;. The following are the keys that you use
/// to specify the user's location. lat (required): The latitude of the
/// client's location, in degrees. The latitude must be greater than or equal
/// to -90.0 and less than or equal to +90.0. Negative values indicate southern
/// latitudes and positive values indicate northern latitudes. long (required):
/// The longitude of the client's location, in degrees. The longitude must be
/// greater than or equal to -180.0 and less than or equal to +180.0. Negative
/// values indicate western longitudes and positive values indicate eastern
/// longitudes. re (required): The radius, in meters, which specifies the
/// horizontal accuracy of the coordinates. Pass the value returned by the
/// device's location service. Typical values might be 22m for GPS/Wi-Fi, 380m
/// for cell tower triangulation, and 18,000m for reverse IP lookup. ts
/// (optional): The UTC UNIX timestamp of when the client was at the location.
/// (The UNIX timestamp is the number of seconds since January 1, 1970.) head
/// (optional): The client's relative heading or direction of travel. Specify
/// the direction of travel as degrees from 0 through 360, counting clockwise
/// relative to true north. Specify this key only if the sp key is nonzero. sp
/// (optional): The horizontal velocity (speed), in meters per second, that the
/// client device is traveling. alt (optional): The altitude of the client
/// device, in meters. are (optional): The radius, in meters, that specifies
/// the vertical accuracy of the coordinates. Specify this key only if you
/// specify the alt key. Although many of the keys are optional, the more
/// information that you provide, the more accurate the location results are.
/// Although optional, you are encouraged to always specify the user's
/// geographical location. Providing the location is especially important if
/// the client's IP address does not accurately reflect the user's physical
/// location (for example, if the client uses VPN). For optimal results, you
/// should include this header and the X-MSEdge-ClientIP header, but at a
/// minimum, you should include this header.
/// </param>
/// <param name='countryCode'>
/// A 2-character country code of the country where the results come from. This
/// API supports only the United States market. If you specify this query
/// parameter, it must be set to us. If you set this parameter, you must also
/// specify the Accept-Language header. Bing uses the first supported language
/// it finds from the languages list, and combine that language with the
/// country code that you specify to determine the market to return results
/// for. If the languages list does not include a supported language, Bing
/// finds the closest language and market that supports the request, or it may
/// use an aggregated or default market for the results instead of a specified
/// one. You should use this query parameter and the Accept-Language query
/// parameter only if you specify multiple languages; otherwise, you should use
/// the mkt and setLang query parameters. This parameter and the mkt query
/// parameter are mutually exclusive—do not specify both.
/// </param>
/// <param name='market'>
/// The market where the results come from. You are strongly encouraged to
/// always specify the market, if known. Specifying the market helps Bing route
/// the request and return an appropriate and optimal response. This parameter
/// and the cc query parameter are mutually exclusive—do not specify both.
/// </param>
/// <param name='safeSearch'>
/// Filter suggestions for adult content. The following are the possible filter
/// values. Off: Return suggestions with adult text, images, or videos.
/// Moderate: Return suggestion with adult text but not adult images or videos.
/// Strict: Do not return news articles with adult text, images, or videos. If
/// the request comes from a market that Bing's adult policy requires that
/// safeSearch is set to Strict, Bing ignores the safeSearch value and uses
/// Strict. If you use the site: query operator, there is the chance that the
/// response may contain adult content regardless of what the safeSearch query
/// parameter is set to. Use site: only if you are aware of the content on the
/// site and your scenario supports the possibility of adult content. Possible
/// values include: 'Off', 'Moderate', 'Strict'
/// </param>
/// <param name='setLang'>
/// The language to use for user interface strings. Specify the language using
/// the ISO 639-1 2-letter language code. For example, the language code for
/// English is EN. The default is EN (English). Although optional, you should
/// always specify the language. Typically, you set setLang to the same
/// language specified by mkt unless the user wants the user interface strings
/// displayed in a different language. This parameter and the Accept-Language
/// header are mutually exclusive; do not specify both. A user interface string
/// is a string that's used as a label in a user interface. There are few user
/// interface strings in the JSON response objects. Also, any links to Bing.com
/// properties in the response objects apply the specified language.
/// </param>
/// <param name='responseFormat'>
/// The media type to use for the response. The following are the possible
/// case-insensitive values: JSON, JSONLD. The default is JSON. If you specify
/// JSONLD, the response body includes JSON-LD objects that contain the search
/// results.
/// </param>
public static Suggestions AutoSuggestMethod(this IAutoSuggestClient operations, string query, string acceptLanguage = default(string), string pragma = default(string), string userAgent = default(string), string clientId = default(string), string clientIp = default(string), string location = default(string), string countryCode = default(string), string market = "en-us", string safeSearch = default(string), string setLang = default(string), IList<string> responseFormat = default(IList<string>))
{
return operations.AutoSuggestMethodAsync(query, acceptLanguage, pragma, userAgent, clientId, clientIp, location, countryCode, market, safeSearch, setLang, responseFormat).GetAwaiter().GetResult();
}
/// <summary>
/// The AutoSuggest API lets you send a search query to Bing and get back a
/// list of query suggestions. This section provides technical details about
/// the query parameters and headers that you use to request suggestions and
/// the JSON response objects that contain them.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='query'>
/// The user's search term.
/// </param>
/// <param name='acceptLanguage'>
/// A comma-delimited list of one or more languages to use for user interface
/// strings. The list is in decreasing order of preference. For additional
/// information, including expected format, see
/// [RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). This
/// header and the setLang query parameter are mutually exclusive; do not
/// specify both. If you set this header, you must also specify the
/// [cc](https://docs.microsoft.com/en-us/bing/bing-autosuggest/overview) query
/// parameter. To determine the market to return results for, Bing uses the
/// first supported language it finds from the list and combines it with the cc
/// parameter value. If the list does not include a supported language, Bing
/// finds the closest language and market that supports the request or it uses
/// an aggregated or default market for the results. To determine the market
/// that Bing used, see the BingAPIs-Market header. Use this header and the cc
/// query parameter only if you specify multiple languages. Otherwise, use the
/// [mkt](https://docs.microsoft.com/en-us/bing/bing-autosuggest/overview) and
/// [setLang](https://docs.microsoft.com/en-us/bing/bing-autosuggest/overview)
/// query parameters. A user interface string is a string that's used as a
/// label in a user interface. There are few user interface strings in the JSON
/// response objects. Any links to Bing.com properties in the response objects
/// apply the specified language.
/// </param>
/// <param name='pragma'>
/// By default, Bing returns cached content, if available. To prevent Bing from
/// returning cached content, set the Pragma header to no-cache (for example,
/// Pragma: no-cache).
/// </param>
/// <param name='userAgent'>
/// The user agent originating the request. Bing uses the user agent to provide
/// mobile users with an optimized experience. Although optional, you are
/// encouraged to always specify this header. The user-agent should be the same
/// string that any commonly used browser sends. For information about user
/// agents, see [RFC
/// 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). The
/// following are examples of user-agent strings. Windows Phone: Mozilla/5.0
/// (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM;
/// Touch; NOKIA; Lumia 822). Android: Mozilla / 5.0 (Linux; U; Android 2.3.5;
/// en - us; SCH - I500 Build / GINGERBREAD) AppleWebKit / 533.1 (KHTML; like
/// Gecko) Version / 4.0 Mobile Safari / 533.1. iPhone: Mozilla / 5.0 (iPhone;
/// CPU iPhone OS 6_1 like Mac OS X) AppleWebKit / 536.26 (KHTML; like Gecko)
/// Mobile / 10B142 iPhone4; 1 BingWeb / 3.03.1428.20120423. PC: Mozilla / 5.0
/// (Windows NT 6.3; WOW64; Trident / 7.0; Touch; rv:11.0) like Gecko. iPad:
/// Mozilla / 5.0 (iPad; CPU OS 7_0 like Mac OS X) AppleWebKit / 537.51.1
/// (KHTML, like Gecko) Version / 7.0 Mobile / 11A465 Safari / 9537.53
/// </param>
/// <param name='clientId'>
/// Bing uses this header to provide users with consistent behavior across Bing
/// API calls. Bing often flights new features and improvements, and it uses
/// the client ID as a key for assigning traffic on different flights. If you
/// do not use the same client ID for a user across multiple requests, then
/// Bing may assign the user to multiple conflicting flights. Being assigned to
/// multiple conflicting flights can lead to an inconsistent user experience.
/// For example, if the second request has a different flight assignment than
/// the first, the experience may be unexpected. Also, Bing can use the client
/// ID to tailor web results to that client IDs search history, providing a
/// richer experience for the user. Bing also uses this header to help improve
/// result rankings by analyzing the activity generated by a client ID. The
/// relevance improvements help with better quality of results delivered by
/// Bing APIs and in turn enables higher click-through rates for the API
/// consumer. IMPORTANT: Although optional, you should consider this header
/// required. Persisting the client ID across multiple requests for the same
/// end user and device combination enables 1) the API consumer to receive a
/// consistent user experience, and 2) higher click-through rates via better
/// quality of results from the Bing APIs. Each user that uses your application
/// on the device must have a unique, Bing generated client ID. If you do not
/// include this header in the request, Bing generates an ID and returns it in
/// the X-MSEdge-ClientID response header. The only time that you should NOT
/// include this header in a request is the first time the user uses your app
/// on that device. Use the client ID for each Bing API request that your app
/// makes for this user on the device. Persist the client ID. To persist the ID
/// in a browser app, use a persistent HTTP cookie to ensure the ID is used
/// across all sessions. Do not use a session cookie. For other apps such as
/// mobile apps, use the device's persistent storage to persist the ID. The
/// next time the user uses your app on that device, get the client ID that you
/// persisted. Bing responses may or may not include this header. If the
/// response includes this header, capture the client ID and use it for all
/// subsequent Bing requests for the user on that device. If you include the
/// X-MSEdge-ClientID, you must not include cookies in the request.
/// </param>
/// <param name='clientIp'>
/// The IPv4 or IPv6 address of the client device. The IP address is used to
/// discover the user's location. Bing uses the location information to
/// determine safe search behavior. Although optional, you are encouraged to
/// always specify this header and the X-Search-Location header. Do not
/// obfuscate the address (for example, by changing the last octet to 0).
/// Obfuscating the address results in the location not being anywhere near the
/// device's actual location, which may result in Bing serving erroneous
/// results.
/// </param>
/// <param name='location'>
/// A semicolon-delimited list of key/value pairs that describe the client's
/// geographical location. Bing uses the location information to determine safe
/// search behavior and to return relevant local content. Specify the key/value
/// pair as &lt;key&gt;:&lt;value&gt;. The following are the keys that you use
/// to specify the user's location. lat (required): The latitude of the
/// client's location, in degrees. The latitude must be greater than or equal
/// to -90.0 and less than or equal to +90.0. Negative values indicate southern
/// latitudes and positive values indicate northern latitudes. long (required):
/// The longitude of the client's location, in degrees. The longitude must be
/// greater than or equal to -180.0 and less than or equal to +180.0. Negative
/// values indicate western longitudes and positive values indicate eastern
/// longitudes. re (required): The radius, in meters, which specifies the
/// horizontal accuracy of the coordinates. Pass the value returned by the
/// device's location service. Typical values might be 22m for GPS/Wi-Fi, 380m
/// for cell tower triangulation, and 18,000m for reverse IP lookup. ts
/// (optional): The UTC UNIX timestamp of when the client was at the location.
/// (The UNIX timestamp is the number of seconds since January 1, 1970.) head
/// (optional): The client's relative heading or direction of travel. Specify
/// the direction of travel as degrees from 0 through 360, counting clockwise
/// relative to true north. Specify this key only if the sp key is nonzero. sp
/// (optional): The horizontal velocity (speed), in meters per second, that the
/// client device is traveling. alt (optional): The altitude of the client
/// device, in meters. are (optional): The radius, in meters, that specifies
/// the vertical accuracy of the coordinates. Specify this key only if you
/// specify the alt key. Although many of the keys are optional, the more
/// information that you provide, the more accurate the location results are.
/// Although optional, you are encouraged to always specify the user's
/// geographical location. Providing the location is especially important if
/// the client's IP address does not accurately reflect the user's physical
/// location (for example, if the client uses VPN). For optimal results, you
/// should include this header and the X-MSEdge-ClientIP header, but at a
/// minimum, you should include this header.
/// </param>
/// <param name='countryCode'>
/// A 2-character country code of the country where the results come from. This
/// API supports only the United States market. If you specify this query
/// parameter, it must be set to us. If you set this parameter, you must also
/// specify the Accept-Language header. Bing uses the first supported language
/// it finds from the languages list, and combine that language with the
/// country code that you specify to determine the market to return results
/// for. If the languages list does not include a supported language, Bing
/// finds the closest language and market that supports the request, or it may
/// use an aggregated or default market for the results instead of a specified
/// one. You should use this query parameter and the Accept-Language query
/// parameter only if you specify multiple languages; otherwise, you should use
/// the mkt and setLang query parameters. This parameter and the mkt query
/// parameter are mutually exclusive—do not specify both.
/// </param>
/// <param name='market'>
/// The market where the results come from. You are strongly encouraged to
/// always specify the market, if known. Specifying the market helps Bing route
/// the request and return an appropriate and optimal response. This parameter
/// and the cc query parameter are mutually exclusive—do not specify both.
/// </param>
/// <param name='safeSearch'>
/// Filter suggestions for adult content. The following are the possible filter
/// values. Off: Return suggestions with adult text, images, or videos.
/// Moderate: Return suggestion with adult text but not adult images or videos.
/// Strict: Do not return news articles with adult text, images, or videos. If
/// the request comes from a market that Bing's adult policy requires that
/// safeSearch is set to Strict, Bing ignores the safeSearch value and uses
/// Strict. If you use the site: query operator, there is the chance that the
/// response may contain adult content regardless of what the safeSearch query
/// parameter is set to. Use site: only if you are aware of the content on the
/// site and your scenario supports the possibility of adult content. Possible
/// values include: 'Off', 'Moderate', 'Strict'
/// </param>
/// <param name='setLang'>
/// The language to use for user interface strings. Specify the language using
/// the ISO 639-1 2-letter language code. For example, the language code for
/// English is EN. The default is EN (English). Although optional, you should
/// always specify the language. Typically, you set setLang to the same
/// language specified by mkt unless the user wants the user interface strings
/// displayed in a different language. This parameter and the Accept-Language
/// header are mutually exclusive; do not specify both. A user interface string
/// is a string that's used as a label in a user interface. There are few user
/// interface strings in the JSON response objects. Also, any links to Bing.com
/// properties in the response objects apply the specified language.
/// </param>
/// <param name='responseFormat'>
/// The media type to use for the response. The following are the possible
/// case-insensitive values: JSON, JSONLD. The default is JSON. If you specify
/// JSONLD, the response body includes JSON-LD objects that contain the search
/// results.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Suggestions> AutoSuggestMethodAsync(this IAutoSuggestClient operations, string query, string acceptLanguage = default(string), string pragma = default(string), string userAgent = default(string), string clientId = default(string), string clientIp = default(string), string location = default(string), string countryCode = default(string), string market = "en-us", string safeSearch = default(string), string setLang = default(string), IList<string> responseFormat = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.AutoSuggestMethodWithHttpMessagesAsync(query, acceptLanguage, pragma, userAgent, clientId, clientIp, location, countryCode, market, safeSearch, setLang, responseFormat, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}

Просмотреть файл

@ -0,0 +1,264 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.AutoSuggest
{
using Microsoft.Rest;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Autosuggest supplies search terms derived from a root text sent to the
/// service. The terms Autosuggest supplies are related to the root text
/// based on similarity and their frequency or ratings of usefulness in
/// other searches. For examples that show how to use Autosuggest, see
/// [Search using
/// AutoSuggest](https://docs.microsoft.com/en-us/bing/bing-autosuggest/overview).
/// </summary>
public partial interface IAutoSuggestClient : System.IDisposable
{
/// <summary>
/// The base URI of the service.
/// </summary>
System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
JsonSerializerSettings SerializationSettings { get; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
JsonSerializerSettings DeserializationSettings { get; }
/// <summary>
/// Subscription credentials which uniquely identify client
/// subscription.
/// </summary>
ServiceClientCredentials Credentials { get; }
/// <summary>
/// The AutoSuggest API lets you send a search query to Bing and get
/// back a list of query suggestions. This section provides technical
/// details about the query parameters and headers that you use to
/// request suggestions and the JSON response objects that contain
/// them.
/// </summary>
/// <param name='query'>
/// The user's search term.
/// </param>
/// <param name='acceptLanguage'>
/// A comma-delimited list of one or more languages to use for user
/// interface strings. The list is in decreasing order of preference.
/// For additional information, including expected format, see
/// [RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html).
/// This header and the setLang query parameter are mutually exclusive;
/// do not specify both. If you set this header, you must also specify
/// the
/// [cc](https://docs.microsoft.com/en-us/bing/bing-autosuggest/overview)
/// query parameter. To determine the market to return results for,
/// Bing uses the first supported language it finds from the list and
/// combines it with the cc parameter value. If the list does not
/// include a supported language, Bing finds the closest language and
/// market that supports the request or it uses an aggregated or
/// default market for the results. To determine the market that Bing
/// used, see the BingAPIs-Market header. Use this header and the cc
/// query parameter only if you specify multiple languages. Otherwise,
/// use the
/// [mkt](https://docs.microsoft.com/en-us/bing/bing-autosuggest/overview)
/// and
/// [setLang](https://docs.microsoft.com/en-us/bing/bing-autosuggest/overview)
/// query parameters. A user interface string is a string that's used
/// as a label in a user interface. There are few user interface
/// strings in the JSON response objects. Any links to Bing.com
/// properties in the response objects apply the specified language.
/// </param>
/// <param name='pragma'>
/// By default, Bing returns cached content, if available. To prevent
/// Bing from returning cached content, set the Pragma header to
/// no-cache (for example, Pragma: no-cache).
/// </param>
/// <param name='userAgent'>
/// The user agent originating the request. Bing uses the user agent to
/// provide mobile users with an optimized experience. Although
/// optional, you are encouraged to always specify this header. The
/// user-agent should be the same string that any commonly used browser
/// sends. For information about user agents, see [RFC
/// 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). The
/// following are examples of user-agent strings. Windows Phone:
/// Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0;
/// IEMobile/10.0; ARM; Touch; NOKIA; Lumia 822). Android: Mozilla /
/// 5.0 (Linux; U; Android 2.3.5; en - us; SCH - I500 Build /
/// GINGERBREAD) AppleWebKit / 533.1 (KHTML; like Gecko) Version / 4.0
/// Mobile Safari / 533.1. iPhone: Mozilla / 5.0 (iPhone; CPU iPhone OS
/// 6_1 like Mac OS X) AppleWebKit / 536.26 (KHTML; like Gecko) Mobile
/// / 10B142 iPhone4; 1 BingWeb / 3.03.1428.20120423. PC: Mozilla / 5.0
/// (Windows NT 6.3; WOW64; Trident / 7.0; Touch; rv:11.0) like Gecko.
/// iPad: Mozilla / 5.0 (iPad; CPU OS 7_0 like Mac OS X) AppleWebKit /
/// 537.51.1 (KHTML, like Gecko) Version / 7.0 Mobile / 11A465 Safari /
/// 9537.53
/// </param>
/// <param name='clientId'>
/// Bing uses this header to provide users with consistent behavior
/// across Bing API calls. Bing often flights new features and
/// improvements, and it uses the client ID as a key for assigning
/// traffic on different flights. If you do not use the same client ID
/// for a user across multiple requests, then Bing may assign the user
/// to multiple conflicting flights. Being assigned to multiple
/// conflicting flights can lead to an inconsistent user experience.
/// For example, if the second request has a different flight
/// assignment than the first, the experience may be unexpected. Also,
/// Bing can use the client ID to tailor web results to that client
/// IDs search history, providing a richer experience for the user.
/// Bing also uses this header to help improve result rankings by
/// analyzing the activity generated by a client ID. The relevance
/// improvements help with better quality of results delivered by Bing
/// APIs and in turn enables higher click-through rates for the API
/// consumer. IMPORTANT: Although optional, you should consider this
/// header required. Persisting the client ID across multiple requests
/// for the same end user and device combination enables 1) the API
/// consumer to receive a consistent user experience, and 2) higher
/// click-through rates via better quality of results from the Bing
/// APIs. Each user that uses your application on the device must have
/// a unique, Bing generated client ID. If you do not include this
/// header in the request, Bing generates an ID and returns it in the
/// X-MSEdge-ClientID response header. The only time that you should
/// NOT include this header in a request is the first time the user
/// uses your app on that device. Use the client ID for each Bing API
/// request that your app makes for this user on the device. Persist
/// the client ID. To persist the ID in a browser app, use a persistent
/// HTTP cookie to ensure the ID is used across all sessions. Do not
/// use a session cookie. For other apps such as mobile apps, use the
/// device's persistent storage to persist the ID. The next time the
/// user uses your app on that device, get the client ID that you
/// persisted. Bing responses may or may not include this header. If
/// the response includes this header, capture the client ID and use it
/// for all subsequent Bing requests for the user on that device. If
/// you include the X-MSEdge-ClientID, you must not include cookies in
/// the request.
/// </param>
/// <param name='clientIp'>
/// The IPv4 or IPv6 address of the client device. The IP address is
/// used to discover the user's location. Bing uses the location
/// information to determine safe search behavior. Although optional,
/// you are encouraged to always specify this header and the
/// X-Search-Location header. Do not obfuscate the address (for
/// example, by changing the last octet to 0). Obfuscating the address
/// results in the location not being anywhere near the device's actual
/// location, which may result in Bing serving erroneous results.
/// </param>
/// <param name='location'>
/// A semicolon-delimited list of key/value pairs that describe the
/// client's geographical location. Bing uses the location information
/// to determine safe search behavior and to return relevant local
/// content. Specify the key/value pair as &lt;key&gt;:&lt;value&gt;.
/// The following are the keys that you use to specify the user's
/// location. lat (required): The latitude of the client's location, in
/// degrees. The latitude must be greater than or equal to -90.0 and
/// less than or equal to +90.0. Negative values indicate southern
/// latitudes and positive values indicate northern latitudes. long
/// (required): The longitude of the client's location, in degrees. The
/// longitude must be greater than or equal to -180.0 and less than or
/// equal to +180.0. Negative values indicate western longitudes and
/// positive values indicate eastern longitudes. re (required): The
/// radius, in meters, which specifies the horizontal accuracy of the
/// coordinates. Pass the value returned by the device's location
/// service. Typical values might be 22m for GPS/Wi-Fi, 380m for cell
/// tower triangulation, and 18,000m for reverse IP lookup. ts
/// (optional): The UTC UNIX timestamp of when the client was at the
/// location. (The UNIX timestamp is the number of seconds since
/// January 1, 1970.) head (optional): The client's relative heading or
/// direction of travel. Specify the direction of travel as degrees
/// from 0 through 360, counting clockwise relative to true north.
/// Specify this key only if the sp key is nonzero. sp (optional): The
/// horizontal velocity (speed), in meters per second, that the client
/// device is traveling. alt (optional): The altitude of the client
/// device, in meters. are (optional): The radius, in meters, that
/// specifies the vertical accuracy of the coordinates. Specify this
/// key only if you specify the alt key. Although many of the keys are
/// optional, the more information that you provide, the more accurate
/// the location results are. Although optional, you are encouraged to
/// always specify the user's geographical location. Providing the
/// location is especially important if the client's IP address does
/// not accurately reflect the user's physical location (for example,
/// if the client uses VPN). For optimal results, you should include
/// this header and the X-MSEdge-ClientIP header, but at a minimum, you
/// should include this header.
/// </param>
/// <param name='countryCode'>
/// A 2-character country code of the country where the results come
/// from. This API supports only the United States market. If you
/// specify this query parameter, it must be set to us. If you set this
/// parameter, you must also specify the Accept-Language header. Bing
/// uses the first supported language it finds from the languages list,
/// and combine that language with the country code that you specify to
/// determine the market to return results for. If the languages list
/// does not include a supported language, Bing finds the closest
/// language and market that supports the request, or it may use an
/// aggregated or default market for the results instead of a specified
/// one. You should use this query parameter and the Accept-Language
/// query parameter only if you specify multiple languages; otherwise,
/// you should use the mkt and setLang query parameters. This parameter
/// and the mkt query parameter are mutually exclusive—do not specify
/// both.
/// </param>
/// <param name='market'>
/// The market where the results come from. You are strongly encouraged
/// to always specify the market, if known. Specifying the market helps
/// Bing route the request and return an appropriate and optimal
/// response. This parameter and the cc query parameter are mutually
/// exclusive—do not specify both.
/// </param>
/// <param name='safeSearch'>
/// Filter suggestions for adult content. The following are the
/// possible filter values. Off: Return suggestions with adult text,
/// images, or videos. Moderate: Return suggestion with adult text but
/// not adult images or videos. Strict: Do not return news articles
/// with adult text, images, or videos. If the request comes from a
/// market that Bing's adult policy requires that safeSearch is set to
/// Strict, Bing ignores the safeSearch value and uses Strict. If you
/// use the site: query operator, there is the chance that the response
/// may contain adult content regardless of what the safeSearch query
/// parameter is set to. Use site: only if you are aware of the content
/// on the site and your scenario supports the possibility of adult
/// content. Possible values include: 'Off', 'Moderate', 'Strict'
/// </param>
/// <param name='setLang'>
/// The language to use for user interface strings. Specify the
/// language using the ISO 639-1 2-letter language code. For example,
/// the language code for English is EN. The default is EN (English).
/// Although optional, you should always specify the language.
/// Typically, you set setLang to the same language specified by mkt
/// unless the user wants the user interface strings displayed in a
/// different language. This parameter and the Accept-Language header
/// are mutually exclusive; do not specify both. A user interface
/// string is a string that's used as a label in a user interface.
/// There are few user interface strings in the JSON response objects.
/// Also, any links to Bing.com properties in the response objects
/// apply the specified language.
/// </param>
/// <param name='responseFormat'>
/// The media type to use for the response. The following are the
/// possible case-insensitive values: JSON, JSONLD. The default is
/// JSON. If you specify JSONLD, the response body includes JSON-LD
/// objects that contain the search results.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Suggestions>> AutoSuggestMethodWithHttpMessagesAsync(string query, string acceptLanguage = default(string), string pragma = default(string), string userAgent = default(string), string clientId = default(string), string clientIp = default(string), string location = default(string), string countryCode = default(string), string market = "en-us", string safeSearch = default(string), string setLang = default(string), IList<string> responseFormat = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}

Просмотреть файл

@ -0,0 +1,75 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.AutoSuggest.Models
{
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public partial class Action : CreativeWork
{
/// <summary>
/// Initializes a new instance of the Action class.
/// </summary>
public Action()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the Action class.
/// </summary>
/// <param name="id">A String identifier.</param>
/// <param name="readLink">The URL that returns this resource.</param>
/// <param name="webSearchUrl">The URL To Bing's search result for this
/// item.</param>
/// <param name="url">The URL to get more information about the thing
/// represented by this object.</param>
/// <param name="thumbnailUrl">The URL to a thumbnail of the
/// item.</param>
/// <param name="about">For internal use only.</param>
/// <param name="mentions">For internal use only.</param>
/// <param name="provider">The source of the creative work.</param>
/// <param name="text">Text content of this creative work</param>
public Action(string _type = default(string), string id = default(string), string readLink = default(string), string webSearchUrl = default(string), IList<Action> potentialAction = default(IList<Action>), IList<Action> immediateAction = default(IList<Action>), string preferredClickthroughUrl = default(string), string adaptiveCard = default(string), string url = default(string), string thumbnailUrl = default(string), IList<Thing> about = default(IList<Thing>), IList<Thing> mentions = default(IList<Thing>), IList<Thing> provider = default(IList<Thing>), Thing creator = default(Thing), string text = default(string), string discussionUrl = default(string), int? commentCount = default(int?), Thing mainEntity = default(Thing), string headLine = default(string), Thing copyrightHolder = default(Thing), int? copyrightYear = default(int?), string disclaimer = default(string), bool? isAccessibleForFree = default(bool?), IList<string> genre = default(IList<string>), bool? isFamilyFriendly = default(bool?), IList<Thing> result = default(IList<Thing>), string displayName = default(string), bool? isTopAction = default(bool?), string serviceUrl = default(string))
: base(_type, id, readLink, webSearchUrl, potentialAction, immediateAction, preferredClickthroughUrl, adaptiveCard, url, thumbnailUrl, about, mentions, provider, creator, text, discussionUrl, commentCount, mainEntity, headLine, copyrightHolder, copyrightYear, disclaimer, isAccessibleForFree, genre, isFamilyFriendly)
{
Result = result;
DisplayName = displayName;
IsTopAction = isTopAction;
ServiceUrl = serviceUrl;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "result")]
public IList<Thing> Result { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "displayName")]
public string DisplayName { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "isTopAction")]
public bool? IsTopAction { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "serviceUrl")]
public string ServiceUrl { get; private set; }
}
}

Просмотреть файл

@ -0,0 +1,45 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.AutoSuggest.Models
{
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Defines an answer.
/// </summary>
public partial class Answer : Response
{
/// <summary>
/// Initializes a new instance of the Answer class.
/// </summary>
public Answer()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the Answer class.
/// </summary>
/// <param name="id">A String identifier.</param>
/// <param name="readLink">The URL that returns this resource.</param>
/// <param name="webSearchUrl">The URL To Bing's search result for this
/// item.</param>
public Answer(string _type = default(string), string id = default(string), string readLink = default(string), string webSearchUrl = default(string), IList<Action> potentialAction = default(IList<Action>), IList<Action> immediateAction = default(IList<Action>), string preferredClickthroughUrl = default(string), string adaptiveCard = default(string))
: base(_type, id, readLink, webSearchUrl, potentialAction, immediateAction, preferredClickthroughUrl, adaptiveCard)
{
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
}
}

Просмотреть файл

@ -0,0 +1,156 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.AutoSuggest.Models
{
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// The most generic kind of creative work, including books, movies,
/// photographs, software programs, etc.
/// </summary>
public partial class CreativeWork : Thing
{
/// <summary>
/// Initializes a new instance of the CreativeWork class.
/// </summary>
public CreativeWork()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the CreativeWork class.
/// </summary>
/// <param name="id">A String identifier.</param>
/// <param name="readLink">The URL that returns this resource.</param>
/// <param name="webSearchUrl">The URL To Bing's search result for this
/// item.</param>
/// <param name="url">The URL to get more information about the thing
/// represented by this object.</param>
/// <param name="thumbnailUrl">The URL to a thumbnail of the
/// item.</param>
/// <param name="about">For internal use only.</param>
/// <param name="mentions">For internal use only.</param>
/// <param name="provider">The source of the creative work.</param>
/// <param name="text">Text content of this creative work</param>
public CreativeWork(string _type = default(string), string id = default(string), string readLink = default(string), string webSearchUrl = default(string), IList<Action> potentialAction = default(IList<Action>), IList<Action> immediateAction = default(IList<Action>), string preferredClickthroughUrl = default(string), string adaptiveCard = default(string), string url = default(string), string thumbnailUrl = default(string), IList<Thing> about = default(IList<Thing>), IList<Thing> mentions = default(IList<Thing>), IList<Thing> provider = default(IList<Thing>), Thing creator = default(Thing), string text = default(string), string discussionUrl = default(string), int? commentCount = default(int?), Thing mainEntity = default(Thing), string headLine = default(string), Thing copyrightHolder = default(Thing), int? copyrightYear = default(int?), string disclaimer = default(string), bool? isAccessibleForFree = default(bool?), IList<string> genre = default(IList<string>), bool? isFamilyFriendly = default(bool?))
: base(_type, id, readLink, webSearchUrl, potentialAction, immediateAction, preferredClickthroughUrl, adaptiveCard, url)
{
ThumbnailUrl = thumbnailUrl;
About = about;
Mentions = mentions;
Provider = provider;
Creator = creator;
Text = text;
DiscussionUrl = discussionUrl;
CommentCount = commentCount;
MainEntity = mainEntity;
HeadLine = headLine;
CopyrightHolder = copyrightHolder;
CopyrightYear = copyrightYear;
Disclaimer = disclaimer;
IsAccessibleForFree = isAccessibleForFree;
Genre = genre;
IsFamilyFriendly = isFamilyFriendly;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets the URL to a thumbnail of the item.
/// </summary>
[JsonProperty(PropertyName = "thumbnailUrl")]
public string ThumbnailUrl { get; private set; }
/// <summary>
/// Gets for internal use only.
/// </summary>
[JsonProperty(PropertyName = "about")]
public IList<Thing> About { get; private set; }
/// <summary>
/// Gets for internal use only.
/// </summary>
[JsonProperty(PropertyName = "mentions")]
public IList<Thing> Mentions { get; private set; }
/// <summary>
/// Gets the source of the creative work.
/// </summary>
[JsonProperty(PropertyName = "provider")]
public IList<Thing> Provider { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "creator")]
public Thing Creator { get; private set; }
/// <summary>
/// Gets text content of this creative work
/// </summary>
[JsonProperty(PropertyName = "text")]
public string Text { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "discussionUrl")]
public string DiscussionUrl { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "commentCount")]
public int? CommentCount { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "mainEntity")]
public Thing MainEntity { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "headLine")]
public string HeadLine { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "copyrightHolder")]
public Thing CopyrightHolder { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "copyrightYear")]
public int? CopyrightYear { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "disclaimer")]
public string Disclaimer { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "isAccessibleForFree")]
public bool? IsAccessibleForFree { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "genre")]
public IList<string> Genre { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "isFamilyFriendly")]
public bool? IsFamilyFriendly { get; private set; }
}
}

Просмотреть файл

@ -0,0 +1,113 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.AutoSuggest.Models
{
using Microsoft.Rest;
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Defines the error that occurred.
/// </summary>
public partial class Error
{
/// <summary>
/// Initializes a new instance of the Error class.
/// </summary>
public Error()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the Error class.
/// </summary>
/// <param name="code">The error code that identifies the category of
/// error. Possible values include: 'None', 'ServerError',
/// 'InvalidRequest', 'RateLimitExceeded', 'InvalidAuthorization',
/// 'InsufficientAuthorization'</param>
/// <param name="message">A description of the error.</param>
/// <param name="moreDetails">A description that provides additional
/// information about the error.</param>
/// <param name="parameter">The parameter in the request that caused
/// the error.</param>
/// <param name="value">The parameter's value in the request that was
/// not valid.</param>
public Error(string code, string message, string moreDetails = default(string), string parameter = default(string), string value = default(string), string _type = default(string))
{
Code = code;
Message = message;
MoreDetails = moreDetails;
Parameter = parameter;
Value = value;
this._type = _type;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets the error code that identifies the category of error.
/// Possible values include: 'None', 'ServerError', 'InvalidRequest',
/// 'RateLimitExceeded', 'InvalidAuthorization',
/// 'InsufficientAuthorization'
/// </summary>
[JsonProperty(PropertyName = "code")]
public string Code { get; set; }
/// <summary>
/// Gets or sets a description of the error.
/// </summary>
[JsonProperty(PropertyName = "message")]
public string Message { get; set; }
/// <summary>
/// Gets a description that provides additional information about the
/// error.
/// </summary>
[JsonProperty(PropertyName = "moreDetails")]
public string MoreDetails { get; private set; }
/// <summary>
/// Gets the parameter in the request that caused the error.
/// </summary>
[JsonProperty(PropertyName = "parameter")]
public string Parameter { get; private set; }
/// <summary>
/// Gets the parameter's value in the request that was not valid.
/// </summary>
[JsonProperty(PropertyName = "value")]
public string Value { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "_type")]
public string _type { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (Code == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Code");
}
if (Message == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Message");
}
}
}
}

Просмотреть файл

@ -0,0 +1,22 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.AutoSuggest.Models
{
/// <summary>
/// Defines values for ErrorCode.
/// </summary>
public static class ErrorCode
{
public const string None = "None";
public const string ServerError = "ServerError";
public const string InvalidRequest = "InvalidRequest";
public const string RateLimitExceeded = "RateLimitExceeded";
public const string InvalidAuthorization = "InvalidAuthorization";
public const string InsufficientAuthorization = "InsufficientAuthorization";
}
}

Просмотреть файл

@ -0,0 +1,80 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.AutoSuggest.Models
{
using Microsoft.Rest;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// The top-level response that represents a failed request.
/// </summary>
public partial class ErrorResponse : Response
{
/// <summary>
/// Initializes a new instance of the ErrorResponse class.
/// </summary>
public ErrorResponse()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the ErrorResponse class.
/// </summary>
/// <param name="errors">A list of errors that describe the reasons why
/// the request failed.</param>
/// <param name="id">A String identifier.</param>
/// <param name="readLink">The URL that returns this resource.</param>
/// <param name="webSearchUrl">The URL To Bing's search result for this
/// item.</param>
public ErrorResponse(IList<Error> errors, string _type = default(string), string id = default(string), string readLink = default(string), string webSearchUrl = default(string), IList<Action> potentialAction = default(IList<Action>), IList<Action> immediateAction = default(IList<Action>), string preferredClickthroughUrl = default(string), string adaptiveCard = default(string))
: base(_type, id, readLink, webSearchUrl, potentialAction, immediateAction, preferredClickthroughUrl, adaptiveCard)
{
Errors = errors;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets a list of errors that describe the reasons why the
/// request failed.
/// </summary>
[JsonProperty(PropertyName = "errors")]
public IList<Error> Errors { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (Errors == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Errors");
}
if (Errors != null)
{
foreach (var element in Errors)
{
if (element != null)
{
element.Validate();
}
}
}
}
}
}

Просмотреть файл

@ -0,0 +1,58 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.AutoSuggest.Models
{
using Microsoft.Rest;
/// <summary>
/// Exception thrown for an invalid response with ErrorResponse
/// information.
/// </summary>
public partial class ErrorResponseException : RestException
{
/// <summary>
/// Gets information about the associated HTTP request.
/// </summary>
public HttpRequestMessageWrapper Request { get; set; }
/// <summary>
/// Gets information about the associated HTTP response.
/// </summary>
public HttpResponseMessageWrapper Response { get; set; }
/// <summary>
/// Gets or sets the body object.
/// </summary>
public ErrorResponse Body { get; set; }
/// <summary>
/// Initializes a new instance of the ErrorResponseException class.
/// </summary>
public ErrorResponseException()
{
}
/// <summary>
/// Initializes a new instance of the ErrorResponseException class.
/// </summary>
/// <param name="message">The exception message.</param>
public ErrorResponseException(string message)
: this(message, null)
{
}
/// <summary>
/// Initializes a new instance of the ErrorResponseException class.
/// </summary>
/// <param name="message">The exception message.</param>
/// <param name="innerException">Inner exception.</param>
public ErrorResponseException(string message, System.Exception innerException)
: base(message, innerException)
{
}
}
}

Просмотреть файл

@ -0,0 +1,48 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.AutoSuggest.Models
{
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Defines the identity of a resource.
/// </summary>
public partial class Identifiable : ResponseBase
{
/// <summary>
/// Initializes a new instance of the Identifiable class.
/// </summary>
public Identifiable()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the Identifiable class.
/// </summary>
/// <param name="id">A String identifier.</param>
public Identifiable(string _type = default(string), string id = default(string))
: base(_type)
{
Id = id;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets a String identifier.
/// </summary>
[JsonProperty(PropertyName = "id")]
public string Id { get; private set; }
}
}

Просмотреть файл

@ -0,0 +1,149 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.AutoSuggest.Models
{
using Microsoft.Rest;
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Defines the query context that Bing used for the request.
/// </summary>
public partial class QueryContext
{
/// <summary>
/// Initializes a new instance of the QueryContext class.
/// </summary>
public QueryContext()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the QueryContext class.
/// </summary>
/// <param name="originalQuery">The query string as specified in the
/// request.</param>
/// <param name="alteredQuery">The query string used by Bing to perform
/// the query. Bing uses the altered query string if the original query
/// string contained spelling mistakes. For example, if the query
/// string is "saling downwind", the altered query string will be
/// "sailing downwind". This field is included only if the original
/// query string contains a spelling mistake.</param>
/// <param name="alterationOverrideQuery">The query string to use to
/// force Bing to use the original string. For example, if the query
/// string is "saling downwind", the override query string will be
/// "+saling downwind". Remember to encode the query string which
/// results in "%2Bsaling+downwind". This field is included only if the
/// original query string contains a spelling mistake.</param>
/// <param name="adultIntent">A Boolean value that indicates whether
/// the specified query has adult intent. The value is true if the
/// query has adult intent; otherwise, false.</param>
/// <param name="askUserForLocation">A Boolean value that indicates
/// whether Bing requires the user's location to provide accurate
/// results. If you specified the user's location by using the
/// X-MSEdge-ClientIP and X-Search-Location headers, you can ignore
/// this field. For location aware queries, such as "today's weather"
/// or "restaurants near me" that need the user's location to provide
/// accurate results, this field is set to true. For location aware
/// queries that include the location (for example, "Seattle weather"),
/// this field is set to false. This field is also set to false for
/// queries that are not location aware, such as "best
/// sellers".</param>
public QueryContext(string originalQuery, string alteredQuery = default(string), string alterationOverrideQuery = default(string), bool? adultIntent = default(bool?), bool? askUserForLocation = default(bool?), bool? isTransactional = default(bool?), string _type = default(string))
{
OriginalQuery = originalQuery;
AlteredQuery = alteredQuery;
AlterationOverrideQuery = alterationOverrideQuery;
AdultIntent = adultIntent;
AskUserForLocation = askUserForLocation;
IsTransactional = isTransactional;
this._type = _type;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets the query string as specified in the request.
/// </summary>
[JsonProperty(PropertyName = "originalQuery")]
public string OriginalQuery { get; set; }
/// <summary>
/// Gets the query string used by Bing to perform the query. Bing uses
/// the altered query string if the original query string contained
/// spelling mistakes. For example, if the query string is "saling
/// downwind", the altered query string will be "sailing downwind".
/// This field is included only if the original query string contains a
/// spelling mistake.
/// </summary>
[JsonProperty(PropertyName = "alteredQuery")]
public string AlteredQuery { get; private set; }
/// <summary>
/// Gets the query string to use to force Bing to use the original
/// string. For example, if the query string is "saling downwind", the
/// override query string will be "+saling downwind". Remember to
/// encode the query string which results in "%2Bsaling+downwind". This
/// field is included only if the original query string contains a
/// spelling mistake.
/// </summary>
[JsonProperty(PropertyName = "alterationOverrideQuery")]
public string AlterationOverrideQuery { get; private set; }
/// <summary>
/// Gets a Boolean value that indicates whether the specified query has
/// adult intent. The value is true if the query has adult intent;
/// otherwise, false.
/// </summary>
[JsonProperty(PropertyName = "adultIntent")]
public bool? AdultIntent { get; private set; }
/// <summary>
/// Gets a Boolean value that indicates whether Bing requires the
/// user's location to provide accurate results. If you specified the
/// user's location by using the X-MSEdge-ClientIP and
/// X-Search-Location headers, you can ignore this field. For location
/// aware queries, such as "today's weather" or "restaurants near me"
/// that need the user's location to provide accurate results, this
/// field is set to true. For location aware queries that include the
/// location (for example, "Seattle weather"), this field is set to
/// false. This field is also set to false for queries that are not
/// location aware, such as "best sellers".
/// </summary>
[JsonProperty(PropertyName = "askUserForLocation")]
public bool? AskUserForLocation { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "isTransactional")]
public bool? IsTransactional { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "_type")]
public string _type { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (OriginalQuery == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "OriginalQuery");
}
}
}
}

Просмотреть файл

@ -0,0 +1,85 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.AutoSuggest.Models
{
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Defines a response. All schemas that could be returned at the root of a
/// response should inherit from this
/// </summary>
public partial class Response : Identifiable
{
/// <summary>
/// Initializes a new instance of the Response class.
/// </summary>
public Response()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the Response class.
/// </summary>
/// <param name="id">A String identifier.</param>
/// <param name="readLink">The URL that returns this resource.</param>
/// <param name="webSearchUrl">The URL To Bing's search result for this
/// item.</param>
public Response(string _type = default(string), string id = default(string), string readLink = default(string), string webSearchUrl = default(string), IList<Action> potentialAction = default(IList<Action>), IList<Action> immediateAction = default(IList<Action>), string preferredClickthroughUrl = default(string), string adaptiveCard = default(string))
: base(_type, id)
{
ReadLink = readLink;
WebSearchUrl = webSearchUrl;
PotentialAction = potentialAction;
ImmediateAction = immediateAction;
PreferredClickthroughUrl = preferredClickthroughUrl;
AdaptiveCard = adaptiveCard;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets the URL that returns this resource.
/// </summary>
[JsonProperty(PropertyName = "readLink")]
public string ReadLink { get; private set; }
/// <summary>
/// Gets the URL To Bing's search result for this item.
/// </summary>
[JsonProperty(PropertyName = "webSearchUrl")]
public string WebSearchUrl { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "potentialAction")]
public IList<Action> PotentialAction { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "immediateAction")]
public IList<Action> ImmediateAction { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "preferredClickthroughUrl")]
public string PreferredClickthroughUrl { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "adaptiveCard")]
public string AdaptiveCard { get; private set; }
}
}

Просмотреть файл

@ -0,0 +1,45 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.AutoSuggest.Models
{
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Response base
/// </summary>
public partial class ResponseBase
{
/// <summary>
/// Initializes a new instance of the ResponseBase class.
/// </summary>
public ResponseBase()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the ResponseBase class.
/// </summary>
public ResponseBase(string _type = default(string))
{
this._type = _type;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "_type")]
public string _type { get; set; }
}
}

Просмотреть файл

@ -0,0 +1,18 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.AutoSuggest.Models
{
/// <summary>
/// Defines values for ResponseFormat.
/// </summary>
public static class ResponseFormat
{
public const string Json = "Json";
public const string JsonLd = "JsonLd";
}
}

Просмотреть файл

@ -0,0 +1,19 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.AutoSuggest.Models
{
/// <summary>
/// Defines values for SafeSearch.
/// </summary>
public static class SafeSearch
{
public const string Off = "Off";
public const string Moderate = "Moderate";
public const string Strict = "Strict";
}
}

Просмотреть файл

@ -0,0 +1,23 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.AutoSuggest.Models
{
/// <summary>
/// Defines values for ScenarioType.
/// </summary>
public static class ScenarioType
{
public const string Unknown = "Unknown";
public const string Web = "Web";
public const string StoreApps = "StoreApps";
public const string SearchHistory = "SearchHistory";
public const string PersonalSearchDocuments = "PersonalSearchDocuments";
public const string PersonalSearchTags = "PersonalSearchTags";
public const string Custom = "Custom";
}
}

Просмотреть файл

@ -0,0 +1,74 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.AutoSuggest.Models
{
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public partial class SearchAction : Action
{
/// <summary>
/// Initializes a new instance of the SearchAction class.
/// </summary>
public SearchAction()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the SearchAction class.
/// </summary>
/// <param name="id">A String identifier.</param>
/// <param name="readLink">The URL that returns this resource.</param>
/// <param name="webSearchUrl">The URL To Bing's search result for this
/// item.</param>
/// <param name="url">The URL to get more information about the thing
/// represented by this object.</param>
/// <param name="thumbnailUrl">The URL to a thumbnail of the
/// item.</param>
/// <param name="about">For internal use only.</param>
/// <param name="mentions">For internal use only.</param>
/// <param name="provider">The source of the creative work.</param>
/// <param name="text">Text content of this creative work</param>
/// <param name="searchKind">Possible values include: 'WebSearch',
/// 'HistorySearch', 'DocumentSearch', 'TagSearch', 'LocationSearch',
/// 'CustomSearch'</param>
public SearchAction(string _type = default(string), string id = default(string), string readLink = default(string), string webSearchUrl = default(string), IList<Action> potentialAction = default(IList<Action>), IList<Action> immediateAction = default(IList<Action>), string preferredClickthroughUrl = default(string), string adaptiveCard = default(string), string url = default(string), string thumbnailUrl = default(string), IList<Thing> about = default(IList<Thing>), IList<Thing> mentions = default(IList<Thing>), IList<Thing> provider = default(IList<Thing>), Thing creator = default(Thing), string text = default(string), string discussionUrl = default(string), int? commentCount = default(int?), Thing mainEntity = default(Thing), string headLine = default(string), Thing copyrightHolder = default(Thing), int? copyrightYear = default(int?), string disclaimer = default(string), bool? isAccessibleForFree = default(bool?), IList<string> genre = default(IList<string>), bool? isFamilyFriendly = default(bool?), IList<Thing> result = default(IList<Thing>), string displayName = default(string), bool? isTopAction = default(bool?), string serviceUrl = default(string), string displayText = default(string), string query = default(string), string searchKind = default(string))
: base(_type, id, readLink, webSearchUrl, potentialAction, immediateAction, preferredClickthroughUrl, adaptiveCard, url, thumbnailUrl, about, mentions, provider, creator, text, discussionUrl, commentCount, mainEntity, headLine, copyrightHolder, copyrightYear, disclaimer, isAccessibleForFree, genre, isFamilyFriendly, result, displayName, isTopAction, serviceUrl)
{
DisplayText = displayText;
Query = query;
SearchKind = searchKind;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "displayText")]
public string DisplayText { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "query")]
public string Query { get; private set; }
/// <summary>
/// Gets possible values include: 'WebSearch', 'HistorySearch',
/// 'DocumentSearch', 'TagSearch', 'LocationSearch', 'CustomSearch'
/// </summary>
[JsonProperty(PropertyName = "searchKind")]
public string SearchKind { get; private set; }
}
}

Просмотреть файл

@ -0,0 +1,22 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.AutoSuggest.Models
{
/// <summary>
/// Defines values for SearchKind.
/// </summary>
public static class SearchKind
{
public const string WebSearch = "WebSearch";
public const string HistorySearch = "HistorySearch";
public const string DocumentSearch = "DocumentSearch";
public const string TagSearch = "TagSearch";
public const string LocationSearch = "LocationSearch";
public const string CustomSearch = "CustomSearch";
}
}

Просмотреть файл

@ -0,0 +1,65 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.AutoSuggest.Models
{
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Defines a search result answer.
/// </summary>
public partial class SearchResultsAnswer : Answer
{
/// <summary>
/// Initializes a new instance of the SearchResultsAnswer class.
/// </summary>
public SearchResultsAnswer()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the SearchResultsAnswer class.
/// </summary>
/// <param name="id">A String identifier.</param>
/// <param name="readLink">The URL that returns this resource.</param>
/// <param name="webSearchUrl">The URL To Bing's search result for this
/// item.</param>
public SearchResultsAnswer(string _type = default(string), string id = default(string), string readLink = default(string), string webSearchUrl = default(string), IList<Action> potentialAction = default(IList<Action>), IList<Action> immediateAction = default(IList<Action>), string preferredClickthroughUrl = default(string), string adaptiveCard = default(string), QueryContext queryContext = default(QueryContext))
: base(_type, id, readLink, webSearchUrl, potentialAction, immediateAction, preferredClickthroughUrl, adaptiveCard)
{
QueryContext = queryContext;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "queryContext")]
public QueryContext QueryContext { get; private set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="Rest.ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (QueryContext != null)
{
QueryContext.Validate();
}
}
}
}

Просмотреть файл

@ -0,0 +1,74 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.AutoSuggest.Models
{
using Microsoft.Rest;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public partial class Suggestions : SearchResultsAnswer
{
/// <summary>
/// Initializes a new instance of the Suggestions class.
/// </summary>
public Suggestions()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the Suggestions class.
/// </summary>
/// <param name="id">A String identifier.</param>
/// <param name="readLink">The URL that returns this resource.</param>
/// <param name="webSearchUrl">The URL To Bing's search result for this
/// item.</param>
public Suggestions(IList<SuggestionsSuggestionGroup> suggestionGroups, string _type = default(string), string id = default(string), string readLink = default(string), string webSearchUrl = default(string), IList<Action> potentialAction = default(IList<Action>), IList<Action> immediateAction = default(IList<Action>), string preferredClickthroughUrl = default(string), string adaptiveCard = default(string), QueryContext queryContext = default(QueryContext))
: base(_type, id, readLink, webSearchUrl, potentialAction, immediateAction, preferredClickthroughUrl, adaptiveCard, queryContext)
{
SuggestionGroups = suggestionGroups;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "suggestionGroups")]
public IList<SuggestionsSuggestionGroup> SuggestionGroups { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public override void Validate()
{
base.Validate();
if (SuggestionGroups == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "SuggestionGroups");
}
if (SuggestionGroups != null)
{
foreach (var element in SuggestionGroups)
{
if (element != null)
{
element.Validate();
}
}
}
}
}
}

Просмотреть файл

@ -0,0 +1,80 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.AutoSuggest.Models
{
using Microsoft.Rest;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public partial class SuggestionsSuggestionGroup
{
/// <summary>
/// Initializes a new instance of the SuggestionsSuggestionGroup class.
/// </summary>
public SuggestionsSuggestionGroup()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the SuggestionsSuggestionGroup class.
/// </summary>
/// <param name="name">Possible values include: 'Unknown', 'Web',
/// 'StoreApps', 'SearchHistory', 'PersonalSearchDocuments',
/// 'PersonalSearchTags', 'Custom'</param>
public SuggestionsSuggestionGroup(string name, IList<SearchAction> searchSuggestions, string _type = default(string))
{
Name = name;
SearchSuggestions = searchSuggestions;
this._type = _type;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets possible values include: 'Unknown', 'Web',
/// 'StoreApps', 'SearchHistory', 'PersonalSearchDocuments',
/// 'PersonalSearchTags', 'Custom'
/// </summary>
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "searchSuggestions")]
public IList<SearchAction> SearchSuggestions { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "_type")]
public string _type { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (Name == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Name");
}
if (SearchSuggestions == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "SearchSuggestions");
}
}
}
}

Просмотреть файл

@ -0,0 +1,56 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.AutoSuggest.Models
{
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Defines a thing.
/// </summary>
public partial class Thing : Response
{
/// <summary>
/// Initializes a new instance of the Thing class.
/// </summary>
public Thing()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the Thing class.
/// </summary>
/// <param name="id">A String identifier.</param>
/// <param name="readLink">The URL that returns this resource.</param>
/// <param name="webSearchUrl">The URL To Bing's search result for this
/// item.</param>
/// <param name="url">The URL to get more information about the thing
/// represented by this object.</param>
public Thing(string _type = default(string), string id = default(string), string readLink = default(string), string webSearchUrl = default(string), IList<Action> potentialAction = default(IList<Action>), IList<Action> immediateAction = default(IList<Action>), string preferredClickthroughUrl = default(string), string adaptiveCard = default(string), string url = default(string))
: base(_type, id, readLink, webSearchUrl, potentialAction, immediateAction, preferredClickthroughUrl, adaptiveCard)
{
Url = url;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets the URL to get more information about the thing represented by
/// this object.
/// </summary>
[JsonProperty(PropertyName = "url")]
public string Url { get; private set; }
}
}

Просмотреть файл

@ -0,0 +1,321 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomImageSearch
{
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
/// <summary>
/// The Bing Custom Image Search API lets you send an image search query to
/// Bing and get back image search results customized to meet your custom
/// search definition.
/// </summary>
public partial class CustomImageSearchClient : ServiceClient<CustomImageSearchClient>, ICustomImageSearchClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Subscription credentials which uniquely identify client subscription.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Gets the ICustomInstance.
/// </summary>
public virtual ICustomInstance CustomInstance { get; private set; }
/// <summary>
/// Initializes a new instance of the CustomImageSearchClient class.
/// </summary>
/// <param name='httpClient'>
/// HttpClient to be used
/// </param>
/// <param name='disposeHttpClient'>
/// True: will dispose the provided httpClient on calling CustomImageSearchClient.Dispose(). False: will not dispose provided httpClient</param>
protected CustomImageSearchClient(HttpClient httpClient, bool disposeHttpClient) : base(httpClient, disposeHttpClient)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the CustomImageSearchClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected CustomImageSearchClient(params DelegatingHandler[] handlers) : base(handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the CustomImageSearchClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected CustomImageSearchClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the CustomImageSearchClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected CustomImageSearchClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the CustomImageSearchClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected CustomImageSearchClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the CustomImageSearchClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Subscription credentials which uniquely identify client subscription.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public CustomImageSearchClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the CustomImageSearchClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Subscription credentials which uniquely identify client subscription.
/// </param>
/// <param name='httpClient'>
/// HttpClient to be used
/// </param>
/// <param name='disposeHttpClient'>
/// True: will dispose the provided httpClient on calling CustomImageSearchClient.Dispose(). False: will not dispose provided httpClient</param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public CustomImageSearchClient(ServiceClientCredentials credentials, HttpClient httpClient, bool disposeHttpClient) : this(httpClient, disposeHttpClient)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the CustomImageSearchClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Subscription credentials which uniquely identify client subscription.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public CustomImageSearchClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the CustomImageSearchClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Subscription credentials which uniquely identify client subscription.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public CustomImageSearchClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the CustomImageSearchClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Subscription credentials which uniquely identify client subscription.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public CustomImageSearchClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
///</summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
CustomInstance = new CustomInstance(this);
BaseUri = new System.Uri("https://api.bing.microsoft.com/v7.0/custom");
SerializationSettings = new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
CustomInitialize();
}
}
}

Просмотреть файл

@ -0,0 +1,732 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomImageSearch
{
using Microsoft.Rest;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// CustomInstance operations.
/// </summary>
public partial class CustomInstance : IServiceOperations<CustomImageSearchClient>, ICustomInstance
{
/// <summary>
/// Initializes a new instance of the CustomInstance class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public CustomInstance(CustomImageSearchClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the CustomImageSearchClient
/// </summary>
public CustomImageSearchClient Client { get; private set; }
/// <summary>
/// The Custom Image Search API lets you send an image search query to Bing and
/// get image results found in your custom view of the web.
/// </summary>
/// <param name='customConfig'>
/// The identifier for the custom search configuration
/// </param>
/// <param name='query'>
/// The user's search query term. The term cannot be empty. The term may
/// contain [Bing Advanced
/// Operators](http://msdn.microsoft.com/library/ff795620.aspx). For example,
/// to limit images to a specific domain, use the
/// [site:](http://msdn.microsoft.com/library/ff795613.aspx) operator. To help
/// improve relevance of an insights query (see
/// [insightsToken](https://docs.microsoft.com/en-us/bing/bing-custom-search/overview)),
/// you should always include the user's query term. Use this parameter only
/// with the Image Search API.Do not specify this parameter when calling the
/// Trending Images API.
/// </param>
/// <param name='acceptLanguage'>
/// A comma-delimited list of one or more languages to use for user interface
/// strings. The list is in decreasing order of preference. For additional
/// information, including expected format, see
/// [RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). This
/// header and the
/// [setLang](https://docs.microsoft.com/en-us/bing/bing-custom-search/overview)
/// query parameter are mutually exclusive; do not specify both. If you set
/// this header, you must also specify the
/// [cc](https://docs.microsoft.com/en-us/bing/bing-custom-search/overview)
/// query parameter. To determine the market to return results for, Bing uses
/// the first supported language it finds from the list and combines it with
/// the cc parameter value. If the list does not include a supported language,
/// Bing finds the closest language and market that supports the request or it
/// uses an aggregated or default market for the results. To determine the
/// market that Bing used, see the BingAPIs-Market header. Use this header and
/// the cc query parameter only if you specify multiple languages. Otherwise,
/// use the
/// [mkt](https://docs.microsoft.com/en-us/bing/bing-custom-search/overview)
/// and
/// [setLang](https://docs.microsoft.com/en-us/bing/bing-custom-search/overview)
/// query parameters. A user interface string is a string that's used as a
/// label in a user interface. There are few user interface strings in the JSON
/// response objects. Any links to Bing.com properties in the response objects
/// apply the specified language.
/// </param>
/// <param name='userAgent'>
/// The user agent originating the request. Bing uses the user agent to provide
/// mobile users with an optimized experience. Although optional, you are
/// encouraged to always specify this header. The user-agent should be the same
/// string that any commonly used browser sends. For information about user
/// agents, see [RFC
/// 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). The
/// following are examples of user-agent strings. Windows Phone: Mozilla/5.0
/// (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM;
/// Touch; NOKIA; Lumia 822). Android: Mozilla / 5.0 (Linux; U; Android 2.3.5;
/// en - us; SCH - I500 Build / GINGERBREAD) AppleWebKit / 533.1 (KHTML; like
/// Gecko) Version / 4.0 Mobile Safari / 533.1. iPhone: Mozilla / 5.0 (iPhone;
/// CPU iPhone OS 6_1 like Mac OS X) AppleWebKit / 536.26 (KHTML; like Gecko)
/// Mobile / 10B142 iPhone4; 1 BingWeb / 3.03.1428.20120423. PC: Mozilla / 5.0
/// (Windows NT 6.3; WOW64; Trident / 7.0; Touch; rv:11.0) like Gecko. iPad:
/// Mozilla / 5.0 (iPad; CPU OS 7_0 like Mac OS X) AppleWebKit / 537.51.1
/// (KHTML, like Gecko) Version / 7.0 Mobile / 11A465 Safari / 9537.53
/// </param>
/// <param name='clientId'>
/// Bing uses this header to provide users with consistent behavior across Bing
/// API calls. Bing often flights new features and improvements, and it uses
/// the client ID as a key for assigning traffic on different flights. If you
/// do not use the same client ID for a user across multiple requests, then
/// Bing may assign the user to multiple conflicting flights. Being assigned to
/// multiple conflicting flights can lead to an inconsistent user experience.
/// For example, if the second request has a different flight assignment than
/// the first, the experience may be unexpected. Also, Bing can use the client
/// ID to tailor web results to that client IDs search history, providing a
/// richer experience for the user. Bing also uses this header to help improve
/// result rankings by analyzing the activity generated by a client ID. The
/// relevance improvements help with better quality of results delivered by
/// Bing APIs and in turn enables higher click-through rates for the API
/// consumer. IMPORTANT: Although optional, you should consider this header
/// required. Persisting the client ID across multiple requests for the same
/// end user and device combination enables 1) the API consumer to receive a
/// consistent user experience, and 2) higher click-through rates via better
/// quality of results from the Bing APIs. Each user that uses your application
/// on the device must have a unique, Bing generated client ID. If you do not
/// include this header in the request, Bing generates an ID and returns it in
/// the X-MSEdge-ClientID response header. The only time that you should NOT
/// include this header in a request is the first time the user uses your app
/// on that device. Use the client ID for each Bing API request that your app
/// makes for this user on the device. Persist the client ID. To persist the ID
/// in a browser app, use a persistent HTTP cookie to ensure the ID is used
/// across all sessions. Do not use a session cookie. For other apps such as
/// mobile apps, use the device's persistent storage to persist the ID. The
/// next time the user uses your app on that device, get the client ID that you
/// persisted. Bing responses may or may not include this header. If the
/// response includes this header, capture the client ID and use it for all
/// subsequent Bing requests for the user on that device. If you include the
/// X-MSEdge-ClientID, you must not include cookies in the request.
/// </param>
/// <param name='clientIp'>
/// The IPv4 or IPv6 address of the client device. The IP address is used to
/// discover the user's location. Bing uses the location information to
/// determine safe search behavior. Although optional, you are encouraged to
/// always specify this header and the X-Search-Location header. Do not
/// obfuscate the address (for example, by changing the last octet to 0).
/// Obfuscating the address results in the location not being anywhere near the
/// device's actual location, which may result in Bing serving erroneous
/// results.
/// </param>
/// <param name='location'>
/// A semicolon-delimited list of key/value pairs that describe the client's
/// geographical location. Bing uses the location information to determine safe
/// search behavior and to return relevant local content. Specify the key/value
/// pair as &lt;key&gt;:&lt;value&gt;. The following are the keys that you use
/// to specify the user's location. lat (required): The latitude of the
/// client's location, in degrees. The latitude must be greater than or equal
/// to -90.0 and less than or equal to +90.0. Negative values indicate southern
/// latitudes and positive values indicate northern latitudes. long (required):
/// The longitude of the client's location, in degrees. The longitude must be
/// greater than or equal to -180.0 and less than or equal to +180.0. Negative
/// values indicate western longitudes and positive values indicate eastern
/// longitudes. re (required): The radius, in meters, which specifies the
/// horizontal accuracy of the coordinates. Pass the value returned by the
/// device's location service. Typical values might be 22m for GPS/Wi-Fi, 380m
/// for cell tower triangulation, and 18,000m for reverse IP lookup. ts
/// (optional): The UTC UNIX timestamp of when the client was at the location.
/// (The UNIX timestamp is the number of seconds since January 1, 1970.) head
/// (optional): The client's relative heading or direction of travel. Specify
/// the direction of travel as degrees from 0 through 360, counting clockwise
/// relative to true north. Specify this key only if the sp key is nonzero. sp
/// (optional): The horizontal velocity (speed), in meters per second, that the
/// client device is traveling. alt (optional): The altitude of the client
/// device, in meters. are (optional): The radius, in meters, that specifies
/// the vertical accuracy of the coordinates. Specify this key only if you
/// specify the alt key. Although many of the keys are optional, the more
/// information that you provide, the more accurate the location results are.
/// Although optional, you are encouraged to always specify the user's
/// geographical location. Providing the location is especially important if
/// the client's IP address does not accurately reflect the user's physical
/// location (for example, if the client uses VPN). For optimal results, you
/// should include this header and the X-MSEdge-ClientIP header, but at a
/// minimum, you should include this header.
/// </param>
/// <param name='aspect'>
/// Filter images by the following aspect ratios. All: Do not filter by
/// aspect.Specifying this value is the same as not specifying the aspect
/// parameter. Square: Return images with standard aspect ratio. Wide: Return
/// images with wide screen aspect ratio. Tall: Return images with tall aspect
/// ratio. Possible values include: 'All', 'Square', 'Wide', 'Tall'
/// </param>
/// <param name='color'>
/// Filter images by the following color options. ColorOnly: Return color
/// images. Monochrome: Return black and white images. Return images with one
/// of the following dominant colors: Black, Blue, Brown, Gray, Green, Orange,
/// Pink, Purple, Red, Teal, White, Yellow. Possible values include:
/// 'ColorOnly', 'Monochrome', 'Black', 'Blue', 'Brown', 'Gray', 'Green',
/// 'Orange', 'Pink', 'Purple', 'Red', 'Teal', 'White', 'Yellow'
/// </param>
/// <param name='countryCode'>
/// A 2-character country code of the country where the results come from. For
/// a list of possible values, see [Market
/// Codes](https://docs.microsoft.com/en-us/bing/bing-custom-search/overview).
/// If you set this parameter, you must also specify the
/// [Accept-Language](https://docs.microsoft.com/en-us/bing/bing-custom-search/overview)
/// header. Bing uses the first supported language it finds from the languages
/// list, and combine that language with the country code that you specify to
/// determine the market to return results for. If the languages list does not
/// include a supported language, Bing finds the closest language and market
/// that supports the request, or it may use an aggregated or default market
/// for the results instead of a specified one. You should use this query
/// parameter and the Accept-Language query parameter only if you specify
/// multiple languages; otherwise, you should use the mkt and setLang query
/// parameters. This parameter and the
/// [mkt](https://docs.microsoft.com/en-us/bing/bing-custom-search/overview)
/// query parameter are mutually exclusive—do not specify both.
/// </param>
/// <param name='count'>
/// The number of images to return in the response. The actual number delivered
/// may be less than requested. The default is 35. The maximum value is 150.
/// You use this parameter along with the offset parameter to page results.For
/// example, if your user interface displays 20 images per page, set count to
/// 20 and offset to 0 to get the first page of results.For each subsequent
/// page, increment offset by 20 (for example, 0, 20, 40). Use this parameter
/// only with the Image Search API.Do not specify this parameter when calling
/// the Insights, Trending Images, or Web Search APIs.
/// </param>
/// <param name='freshness'>
/// Filter images by the following discovery options. Day: Return images
/// discovered by Bing within the last 24 hours. Week: Return images discovered
/// by Bing within the last 7 days. Month: Return images discovered by Bing
/// within the last 30 days. Possible values include: 'Day', 'Week', 'Month'
/// </param>
/// <param name='height'>
/// Filter images that have the specified height, in pixels. You may use this
/// filter with the size filter to return small images that have a height of
/// 150 pixels.
/// </param>
/// <param name='id'>
/// An ID that uniquely identifies an image. Use this parameter to ensure that
/// the specified image is the first image in the list of images that Bing
/// returns. The
/// [Image](https://docs.microsoft.com/en-us/bing/bing-custom-search/overview)
/// object's imageId field contains the ID that you set this parameter to.
/// </param>
/// <param name='imageContent'>
/// Filter images by the following content types. Face: Return images that show
/// only a person's face. Portrait: Return images that show only a person's
/// head and shoulders. Possible values include: 'Face', 'Portrait'
/// </param>
/// <param name='imageType'>
/// Filter images by the following image types. AnimatedGif: Return only
/// animated GIFs. Clipart: Return only clip art images. Line: Return only line
/// drawings. Photo: Return only photographs(excluding line drawings, animated
/// Gifs, and clip art). Shopping: Return only images that contain items where
/// Bing knows of a merchant that is selling the items. This option is valid in
/// the en - US market only.Transparent: Return only images with a transparent
/// background. Possible values include: 'AnimatedGif', 'Clipart', 'Line',
/// 'Photo', 'Shopping', 'Transparent'
/// </param>
/// <param name='license'>
/// Filter images by the following license types. All: Do not filter by license
/// type.Specifying this value is the same as not specifying the license
/// parameter. Any: Return images that are under any license type. The response
/// doesn't include images that do not specify a license or the license is
/// unknown. Public: Return images where the creator has waived their exclusive
/// rights, to the fullest extent allowed by law. Share: Return images that may
/// be shared with others. Changing or editing the image might not be allowed.
/// Also, modifying, sharing, and using the image for commercial purposes might
/// not be allowed. Typically, this option returns the most images.
/// ShareCommercially: Return images that may be shared with others for
/// personal or commercial purposes. Changing or editing the image might not be
/// allowed. Modify: Return images that may be modified, shared, and used.
/// Changing or editing the image might not be allowed. Modifying, sharing, and
/// using the image for commercial purposes might not be allowed.
/// ModifyCommercially: Return images that may be modified, shared, and used
/// for personal or commercial purposes. Typically, this option returns the
/// fewest images. For more information about these license types, see [Filter
/// Images By License Type](http://go.microsoft.com/fwlink/?LinkId=309768).
/// Possible values include: 'All', 'Any', 'Public', 'Share',
/// 'ShareCommercially', 'Modify', 'ModifyCommercially'
/// </param>
/// <param name='market'>
/// The market where the results come from. Typically, mkt is the country where
/// the user is making the request from. However, it could be a different
/// country if the user is not located in a country where Bing delivers
/// results. The market must be in the form &lt;language code&gt;-&lt;country
/// code&gt;. For example, en-US. The string is case insensitive. For a list of
/// possible market values, see [Market
/// Codes](https://docs.microsoft.com/en-us/bing/bing-custom-search/overview).
/// NOTE: If known, you are encouraged to always specify the market. Specifying
/// the market helps Bing route the request and return an appropriate and
/// optimal response. If you specify a market that is not listed in [Market
/// Codes](https://docs.microsoft.com/en-us/bing/bing-custom-search/overview),
/// Bing uses a best fit market code based on an internal mapping that is
/// subject to change. This parameter and the
/// [cc](https://docs.microsoft.com/en-us/bing/bing-custom-search/overview)
/// query parameter are mutually exclusive—do not specify both.
/// </param>
/// <param name='maxFileSize'>
/// Filter images that are less than or equal to the specified file size. The
/// maximum file size that you may specify is 520,192 bytes. If you specify a
/// larger value, the API uses 520,192. It is possible that the response may
/// include images that are slightly larger than the specified maximum. You may
/// specify this filter and minFileSize to filter images within a range of file
/// sizes.
/// </param>
/// <param name='maxHeight'>
/// Filter images that have a height that is less than or equal to the
/// specified height. Specify the height in pixels. You may specify this filter
/// and minHeight to filter images within a range of heights. This filter and
/// the height filter are mutually exclusive.
/// </param>
/// <param name='maxWidth'>
/// Filter images that have a width that is less than or equal to the specified
/// width. Specify the width in pixels. You may specify this filter and
/// maxWidth to filter images within a range of widths. This filter and the
/// width filter are mutually exclusive.
/// </param>
/// <param name='minFileSize'>
/// Filter images that are greater than or equal to the specified file size.
/// The maximum file size that you may specify is 520,192 bytes. If you specify
/// a larger value, the API uses 520,192. It is possible that the response may
/// include images that are slightly smaller than the specified minimum. You
/// may specify this filter and maxFileSize to filter images within a range of
/// file sizes.
/// </param>
/// <param name='minHeight'>
/// Filter images that have a height that is greater than or equal to the
/// specified height. Specify the height in pixels. You may specify this filter
/// and maxHeight to filter images within a range of heights. This filter and
/// the height filter are mutually exclusive.
/// </param>
/// <param name='minWidth'>
/// Filter images that have a width that is greater than or equal to the
/// specified width. Specify the width in pixels. You may specify this filter
/// and maxWidth to filter images within a range of widths. This filter and the
/// width filter are mutually exclusive.
/// </param>
/// <param name='offset'>
/// The zero-based offset that indicates the number of images to skip before
/// returning images. The default is 0. The offset should be less than
/// ([totalEstimatedMatches](https://docs.microsoft.com/en-us/bing/bing-custom-search/overview)
/// - count). Use this parameter along with the count parameter to page
/// results. For example, if your user interface displays 20 images per page,
/// set count to 20 and offset to 0 to get the first page of results. For each
/// subsequent page, increment offset by 20 (for example, 0, 20, 40). It is
/// possible for multiple pages to include some overlap in results. To prevent
/// duplicates, see
/// [nextOffset](https://docs.microsoft.com/en-us/bing/bing-custom-search/overview).
/// Use this parameter only with the Image API. Do not specify this parameter
/// when calling the Trending Images API or the Web Search API.
/// </param>
/// <param name='safeSearch'>
/// Filter images for adult content. The following are the possible filter
/// values. Off: May return images with adult content. If the request is
/// through the Image Search API, the response includes thumbnail images that
/// are clear (non-fuzzy). However, if the request is through the Web Search
/// API, the response includes thumbnail images that are pixelated (fuzzy).
/// Moderate: If the request is through the Image Search API, the response
/// doesn't include images with adult content. If the request is through the
/// Web Search API, the response may include images with adult content (the
/// thumbnail images are pixelated (fuzzy)). Strict: Do not return images with
/// adult content. The default is Moderate. If the request comes from a market
/// that Bing's adult policy requires that safeSearch is set to Strict, Bing
/// ignores the safeSearch value and uses Strict. If you use the site: query
/// operator, there is the chance that the response may contain adult content
/// regardless of what the safeSearch query parameter is set to. Use site: only
/// if you are aware of the content on the site and your scenario supports the
/// possibility of adult content. Possible values include: 'Off', 'Moderate',
/// 'Strict'
/// </param>
/// <param name='size'>
/// Filter images by the following sizes. All: Do not filter by size.
/// Specifying this value is the same as not specifying the size parameter.
/// Small: Return images that are less than 200x200 pixels. Medium: Return
/// images that are greater than or equal to 200x200 pixels but less than
/// 500x500 pixels. Large: Return images that are 500x500 pixels or larger.
/// Wallpaper: Return wallpaper images. You may use this parameter along with
/// the height or width parameters. For example, you may use height and size to
/// request small images that are 150 pixels tall. Possible values include:
/// 'All', 'Small', 'Medium', 'Large', 'Wallpaper'
/// </param>
/// <param name='setLang'>
/// The language to use for user interface strings. Specify the language using
/// the ISO 639-1 2-letter language code. For example, the language code for
/// English is EN. The default is EN (English). Although optional, you should
/// always specify the language. Typically, you set setLang to the same
/// language specified by mkt unless the user wants the user interface strings
/// displayed in a different language. This parameter and the
/// [Accept-Language](https://docs.microsoft.com/en-us/bing/bing-custom-search/overview)
/// header are mutually exclusive; do not specify both. A user interface string
/// is a string that's used as a label in a user interface. There are few user
/// interface strings in the JSON response objects. Also, any links to Bing.com
/// properties in the response objects apply the specified language.
/// </param>
/// <param name='width'>
/// Filter images that have the specified width, in pixels. You may use this
/// filter with the size filter to return small images that have a width of 150
/// pixels.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<Images>> ImageSearchWithHttpMessagesAsync(string customConfig, string query, string acceptLanguage = default(string), string userAgent = default(string), string clientId = default(string), string clientIp = default(string), string location = default(string), string aspect = default(string), string color = default(string), string countryCode = default(string), int? count = default(int?), string freshness = default(string), int? height = default(int?), string id = default(string), string imageContent = default(string), string imageType = default(string), string license = default(string), string market = default(string), long? maxFileSize = default(long?), long? maxHeight = default(long?), long? maxWidth = default(long?), long? minFileSize = default(long?), long? minHeight = default(long?), long? minWidth = default(long?), long? offset = default(long?), string safeSearch = default(string), string size = default(string), string setLang = default(string), int? width = default(int?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (customConfig == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "customConfig");
}
if (query == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "query");
}
string xBingApisSDK = "true";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("xBingApisSDK", xBingApisSDK);
tracingParameters.Add("acceptLanguage", acceptLanguage);
tracingParameters.Add("userAgent", userAgent);
tracingParameters.Add("clientId", clientId);
tracingParameters.Add("clientIp", clientIp);
tracingParameters.Add("location", location);
tracingParameters.Add("customConfig", customConfig);
tracingParameters.Add("aspect", aspect);
tracingParameters.Add("color", color);
tracingParameters.Add("countryCode", countryCode);
tracingParameters.Add("count", count);
tracingParameters.Add("freshness", freshness);
tracingParameters.Add("height", height);
tracingParameters.Add("id", id);
tracingParameters.Add("imageContent", imageContent);
tracingParameters.Add("imageType", imageType);
tracingParameters.Add("license", license);
tracingParameters.Add("market", market);
tracingParameters.Add("maxFileSize", maxFileSize);
tracingParameters.Add("maxHeight", maxHeight);
tracingParameters.Add("maxWidth", maxWidth);
tracingParameters.Add("minFileSize", minFileSize);
tracingParameters.Add("minHeight", minHeight);
tracingParameters.Add("minWidth", minWidth);
tracingParameters.Add("offset", offset);
tracingParameters.Add("query", query);
tracingParameters.Add("safeSearch", safeSearch);
tracingParameters.Add("size", size);
tracingParameters.Add("setLang", setLang);
tracingParameters.Add("width", width);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ImageSearch", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "images/search").ToString();
List<string> _queryParameters = new List<string>();
if (customConfig != null)
{
_queryParameters.Add(string.Format("customConfig={0}", System.Uri.EscapeDataString(customConfig)));
}
if (aspect != null)
{
_queryParameters.Add(string.Format("aspect={0}", System.Uri.EscapeDataString(aspect)));
}
if (color != null)
{
_queryParameters.Add(string.Format("color={0}", System.Uri.EscapeDataString(color)));
}
if (countryCode != null)
{
_queryParameters.Add(string.Format("cc={0}", System.Uri.EscapeDataString(countryCode)));
}
if (count != null)
{
_queryParameters.Add(string.Format("count={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(count, Client.SerializationSettings).Trim('"'))));
}
if (freshness != null)
{
_queryParameters.Add(string.Format("freshness={0}", System.Uri.EscapeDataString(freshness)));
}
if (height != null)
{
_queryParameters.Add(string.Format("height={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(height, Client.SerializationSettings).Trim('"'))));
}
if (id != null)
{
_queryParameters.Add(string.Format("id={0}", System.Uri.EscapeDataString(id)));
}
if (imageContent != null)
{
_queryParameters.Add(string.Format("imageContent={0}", System.Uri.EscapeDataString(imageContent)));
}
if (imageType != null)
{
_queryParameters.Add(string.Format("imageType={0}", System.Uri.EscapeDataString(imageType)));
}
if (license != null)
{
_queryParameters.Add(string.Format("license={0}", System.Uri.EscapeDataString(license)));
}
if (market != null)
{
_queryParameters.Add(string.Format("mkt={0}", System.Uri.EscapeDataString(market)));
}
if (maxFileSize != null)
{
_queryParameters.Add(string.Format("maxFileSize={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(maxFileSize, Client.SerializationSettings).Trim('"'))));
}
if (maxHeight != null)
{
_queryParameters.Add(string.Format("maxHeight={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(maxHeight, Client.SerializationSettings).Trim('"'))));
}
if (maxWidth != null)
{
_queryParameters.Add(string.Format("maxWidth={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(maxWidth, Client.SerializationSettings).Trim('"'))));
}
if (minFileSize != null)
{
_queryParameters.Add(string.Format("minFileSize={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(minFileSize, Client.SerializationSettings).Trim('"'))));
}
if (minHeight != null)
{
_queryParameters.Add(string.Format("minHeight={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(minHeight, Client.SerializationSettings).Trim('"'))));
}
if (minWidth != null)
{
_queryParameters.Add(string.Format("minWidth={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(minWidth, Client.SerializationSettings).Trim('"'))));
}
if (offset != null)
{
_queryParameters.Add(string.Format("offset={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(offset, Client.SerializationSettings).Trim('"'))));
}
if (query != null)
{
_queryParameters.Add(string.Format("q={0}", System.Uri.EscapeDataString(query)));
}
if (safeSearch != null)
{
_queryParameters.Add(string.Format("safeSearch={0}", System.Uri.EscapeDataString(safeSearch)));
}
if (size != null)
{
_queryParameters.Add(string.Format("size={0}", System.Uri.EscapeDataString(size)));
}
if (setLang != null)
{
_queryParameters.Add(string.Format("setLang={0}", System.Uri.EscapeDataString(setLang)));
}
if (width != null)
{
_queryParameters.Add(string.Format("width={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(width, Client.SerializationSettings).Trim('"'))));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (xBingApisSDK != null)
{
if (_httpRequest.Headers.Contains("X-BingApis-SDK"))
{
_httpRequest.Headers.Remove("X-BingApis-SDK");
}
_httpRequest.Headers.TryAddWithoutValidation("X-BingApis-SDK", xBingApisSDK);
}
if (acceptLanguage != null)
{
if (_httpRequest.Headers.Contains("Accept-Language"))
{
_httpRequest.Headers.Remove("Accept-Language");
}
_httpRequest.Headers.TryAddWithoutValidation("Accept-Language", acceptLanguage);
}
if (userAgent != null)
{
if (_httpRequest.Headers.Contains("User-Agent"))
{
_httpRequest.Headers.Remove("User-Agent");
}
_httpRequest.Headers.TryAddWithoutValidation("User-Agent", userAgent);
}
if (clientId != null)
{
if (_httpRequest.Headers.Contains("X-MSEdge-ClientID"))
{
_httpRequest.Headers.Remove("X-MSEdge-ClientID");
}
_httpRequest.Headers.TryAddWithoutValidation("X-MSEdge-ClientID", clientId);
}
if (clientIp != null)
{
if (_httpRequest.Headers.Contains("X-MSEdge-ClientIP"))
{
_httpRequest.Headers.Remove("X-MSEdge-ClientIP");
}
_httpRequest.Headers.TryAddWithoutValidation("X-MSEdge-ClientIP", clientIp);
}
if (location != null)
{
if (_httpRequest.Headers.Contains("X-Search-Location"))
{
_httpRequest.Headers.Remove("X-Search-Location");
}
_httpRequest.Headers.TryAddWithoutValidation("X-Search-Location", location);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Images>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Images>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}

Просмотреть файл

@ -0,0 +1,391 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomImageSearch
{
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for CustomInstance.
/// </summary>
public static partial class CustomInstanceExtensions
{
/// <summary>
/// The Custom Image Search API lets you send an image search query to Bing and
/// get image results found in your custom view of the web.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='customConfig'>
/// The identifier for the custom search configuration
/// </param>
/// <param name='query'>
/// The user's search query term. The term cannot be empty. The term may
/// contain [Bing Advanced
/// Operators](http://msdn.microsoft.com/library/ff795620.aspx). For example,
/// to limit images to a specific domain, use the
/// [site:](http://msdn.microsoft.com/library/ff795613.aspx) operator. To help
/// improve relevance of an insights query (see
/// [insightsToken](https://docs.microsoft.com/en-us/bing/bing-custom-search/overview)),
/// you should always include the user's query term. Use this parameter only
/// with the Image Search API.Do not specify this parameter when calling the
/// Trending Images API.
/// </param>
/// <param name='acceptLanguage'>
/// A comma-delimited list of one or more languages to use for user interface
/// strings. The list is in decreasing order of preference. For additional
/// information, including expected format, see
/// [RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). This
/// header and the
/// [setLang](https://docs.microsoft.com/en-us/bing/bing-custom-search/overview)
/// query parameter are mutually exclusive; do not specify both. If you set
/// this header, you must also specify the
/// [cc](https://docs.microsoft.com/en-us/bing/bing-custom-search/overview)
/// query parameter. To determine the market to return results for, Bing uses
/// the first supported language it finds from the list and combines it with
/// the cc parameter value. If the list does not include a supported language,
/// Bing finds the closest language and market that supports the request or it
/// uses an aggregated or default market for the results. To determine the
/// market that Bing used, see the BingAPIs-Market header. Use this header and
/// the cc query parameter only if you specify multiple languages. Otherwise,
/// use the
/// [mkt](https://docs.microsoft.com/en-us/bing/bing-custom-search/overview)
/// and
/// [setLang](https://docs.microsoft.com/en-us/bing/bing-custom-search/overview)
/// query parameters. A user interface string is a string that's used as a
/// label in a user interface. There are few user interface strings in the JSON
/// response objects. Any links to Bing.com properties in the response objects
/// apply the specified language.
/// </param>
/// <param name='userAgent'>
/// The user agent originating the request. Bing uses the user agent to provide
/// mobile users with an optimized experience. Although optional, you are
/// encouraged to always specify this header. The user-agent should be the same
/// string that any commonly used browser sends. For information about user
/// agents, see [RFC
/// 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). The
/// following are examples of user-agent strings. Windows Phone: Mozilla/5.0
/// (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM;
/// Touch; NOKIA; Lumia 822). Android: Mozilla / 5.0 (Linux; U; Android 2.3.5;
/// en - us; SCH - I500 Build / GINGERBREAD) AppleWebKit / 533.1 (KHTML; like
/// Gecko) Version / 4.0 Mobile Safari / 533.1. iPhone: Mozilla / 5.0 (iPhone;
/// CPU iPhone OS 6_1 like Mac OS X) AppleWebKit / 536.26 (KHTML; like Gecko)
/// Mobile / 10B142 iPhone4; 1 BingWeb / 3.03.1428.20120423. PC: Mozilla / 5.0
/// (Windows NT 6.3; WOW64; Trident / 7.0; Touch; rv:11.0) like Gecko. iPad:
/// Mozilla / 5.0 (iPad; CPU OS 7_0 like Mac OS X) AppleWebKit / 537.51.1
/// (KHTML, like Gecko) Version / 7.0 Mobile / 11A465 Safari / 9537.53
/// </param>
/// <param name='clientId'>
/// Bing uses this header to provide users with consistent behavior across Bing
/// API calls. Bing often flights new features and improvements, and it uses
/// the client ID as a key for assigning traffic on different flights. If you
/// do not use the same client ID for a user across multiple requests, then
/// Bing may assign the user to multiple conflicting flights. Being assigned to
/// multiple conflicting flights can lead to an inconsistent user experience.
/// For example, if the second request has a different flight assignment than
/// the first, the experience may be unexpected. Also, Bing can use the client
/// ID to tailor web results to that client IDs search history, providing a
/// richer experience for the user. Bing also uses this header to help improve
/// result rankings by analyzing the activity generated by a client ID. The
/// relevance improvements help with better quality of results delivered by
/// Bing APIs and in turn enables higher click-through rates for the API
/// consumer. IMPORTANT: Although optional, you should consider this header
/// required. Persisting the client ID across multiple requests for the same
/// end user and device combination enables 1) the API consumer to receive a
/// consistent user experience, and 2) higher click-through rates via better
/// quality of results from the Bing APIs. Each user that uses your application
/// on the device must have a unique, Bing generated client ID. If you do not
/// include this header in the request, Bing generates an ID and returns it in
/// the X-MSEdge-ClientID response header. The only time that you should NOT
/// include this header in a request is the first time the user uses your app
/// on that device. Use the client ID for each Bing API request that your app
/// makes for this user on the device. Persist the client ID. To persist the ID
/// in a browser app, use a persistent HTTP cookie to ensure the ID is used
/// across all sessions. Do not use a session cookie. For other apps such as
/// mobile apps, use the device's persistent storage to persist the ID. The
/// next time the user uses your app on that device, get the client ID that you
/// persisted. Bing responses may or may not include this header. If the
/// response includes this header, capture the client ID and use it for all
/// subsequent Bing requests for the user on that device. If you include the
/// X-MSEdge-ClientID, you must not include cookies in the request.
/// </param>
/// <param name='clientIp'>
/// The IPv4 or IPv6 address of the client device. The IP address is used to
/// discover the user's location. Bing uses the location information to
/// determine safe search behavior. Although optional, you are encouraged to
/// always specify this header and the X-Search-Location header. Do not
/// obfuscate the address (for example, by changing the last octet to 0).
/// Obfuscating the address results in the location not being anywhere near the
/// device's actual location, which may result in Bing serving erroneous
/// results.
/// </param>
/// <param name='location'>
/// A semicolon-delimited list of key/value pairs that describe the client's
/// geographical location. Bing uses the location information to determine safe
/// search behavior and to return relevant local content. Specify the key/value
/// pair as &lt;key&gt;:&lt;value&gt;. The following are the keys that you use
/// to specify the user's location. lat (required): The latitude of the
/// client's location, in degrees. The latitude must be greater than or equal
/// to -90.0 and less than or equal to +90.0. Negative values indicate southern
/// latitudes and positive values indicate northern latitudes. long (required):
/// The longitude of the client's location, in degrees. The longitude must be
/// greater than or equal to -180.0 and less than or equal to +180.0. Negative
/// values indicate western longitudes and positive values indicate eastern
/// longitudes. re (required): The radius, in meters, which specifies the
/// horizontal accuracy of the coordinates. Pass the value returned by the
/// device's location service. Typical values might be 22m for GPS/Wi-Fi, 380m
/// for cell tower triangulation, and 18,000m for reverse IP lookup. ts
/// (optional): The UTC UNIX timestamp of when the client was at the location.
/// (The UNIX timestamp is the number of seconds since January 1, 1970.) head
/// (optional): The client's relative heading or direction of travel. Specify
/// the direction of travel as degrees from 0 through 360, counting clockwise
/// relative to true north. Specify this key only if the sp key is nonzero. sp
/// (optional): The horizontal velocity (speed), in meters per second, that the
/// client device is traveling. alt (optional): The altitude of the client
/// device, in meters. are (optional): The radius, in meters, that specifies
/// the vertical accuracy of the coordinates. Specify this key only if you
/// specify the alt key. Although many of the keys are optional, the more
/// information that you provide, the more accurate the location results are.
/// Although optional, you are encouraged to always specify the user's
/// geographical location. Providing the location is especially important if
/// the client's IP address does not accurately reflect the user's physical
/// location (for example, if the client uses VPN). For optimal results, you
/// should include this header and the X-MSEdge-ClientIP header, but at a
/// minimum, you should include this header.
/// </param>
/// <param name='aspect'>
/// Filter images by the following aspect ratios. All: Do not filter by
/// aspect.Specifying this value is the same as not specifying the aspect
/// parameter. Square: Return images with standard aspect ratio. Wide: Return
/// images with wide screen aspect ratio. Tall: Return images with tall aspect
/// ratio. Possible values include: 'All', 'Square', 'Wide', 'Tall'
/// </param>
/// <param name='color'>
/// Filter images by the following color options. ColorOnly: Return color
/// images. Monochrome: Return black and white images. Return images with one
/// of the following dominant colors: Black, Blue, Brown, Gray, Green, Orange,
/// Pink, Purple, Red, Teal, White, Yellow. Possible values include:
/// 'ColorOnly', 'Monochrome', 'Black', 'Blue', 'Brown', 'Gray', 'Green',
/// 'Orange', 'Pink', 'Purple', 'Red', 'Teal', 'White', 'Yellow'
/// </param>
/// <param name='countryCode'>
/// A 2-character country code of the country where the results come from. For
/// a list of possible values, see [Market
/// Codes](https://docs.microsoft.com/en-us/bing/bing-custom-search/overview).
/// If you set this parameter, you must also specify the
/// [Accept-Language](https://docs.microsoft.com/en-us/bing/bing-custom-search/overview)
/// header. Bing uses the first supported language it finds from the languages
/// list, and combine that language with the country code that you specify to
/// determine the market to return results for. If the languages list does not
/// include a supported language, Bing finds the closest language and market
/// that supports the request, or it may use an aggregated or default market
/// for the results instead of a specified one. You should use this query
/// parameter and the Accept-Language query parameter only if you specify
/// multiple languages; otherwise, you should use the mkt and setLang query
/// parameters. This parameter and the
/// [mkt](https://docs.microsoft.com/en-us/bing/bing-custom-search/overview)
/// query parameter are mutually exclusive—do not specify both.
/// </param>
/// <param name='count'>
/// The number of images to return in the response. The actual number delivered
/// may be less than requested. The default is 35. The maximum value is 150.
/// You use this parameter along with the offset parameter to page results.For
/// example, if your user interface displays 20 images per page, set count to
/// 20 and offset to 0 to get the first page of results.For each subsequent
/// page, increment offset by 20 (for example, 0, 20, 40). Use this parameter
/// only with the Image Search API.Do not specify this parameter when calling
/// the Insights, Trending Images, or Web Search APIs.
/// </param>
/// <param name='freshness'>
/// Filter images by the following discovery options. Day: Return images
/// discovered by Bing within the last 24 hours. Week: Return images discovered
/// by Bing within the last 7 days. Month: Return images discovered by Bing
/// within the last 30 days. Possible values include: 'Day', 'Week', 'Month'
/// </param>
/// <param name='height'>
/// Filter images that have the specified height, in pixels. You may use this
/// filter with the size filter to return small images that have a height of
/// 150 pixels.
/// </param>
/// <param name='id'>
/// An ID that uniquely identifies an image. Use this parameter to ensure that
/// the specified image is the first image in the list of images that Bing
/// returns. The
/// [Image](https://docs.microsoft.com/en-us/bing/bing-custom-search/overview)
/// object's imageId field contains the ID that you set this parameter to.
/// </param>
/// <param name='imageContent'>
/// Filter images by the following content types. Face: Return images that show
/// only a person's face. Portrait: Return images that show only a person's
/// head and shoulders. Possible values include: 'Face', 'Portrait'
/// </param>
/// <param name='imageType'>
/// Filter images by the following image types. AnimatedGif: Return only
/// animated GIFs. Clipart: Return only clip art images. Line: Return only line
/// drawings. Photo: Return only photographs(excluding line drawings, animated
/// Gifs, and clip art). Shopping: Return only images that contain items where
/// Bing knows of a merchant that is selling the items. This option is valid in
/// the en - US market only.Transparent: Return only images with a transparent
/// background. Possible values include: 'AnimatedGif', 'Clipart', 'Line',
/// 'Photo', 'Shopping', 'Transparent'
/// </param>
/// <param name='license'>
/// Filter images by the following license types. All: Do not filter by license
/// type.Specifying this value is the same as not specifying the license
/// parameter. Any: Return images that are under any license type. The response
/// doesn't include images that do not specify a license or the license is
/// unknown. Public: Return images where the creator has waived their exclusive
/// rights, to the fullest extent allowed by law. Share: Return images that may
/// be shared with others. Changing or editing the image might not be allowed.
/// Also, modifying, sharing, and using the image for commercial purposes might
/// not be allowed. Typically, this option returns the most images.
/// ShareCommercially: Return images that may be shared with others for
/// personal or commercial purposes. Changing or editing the image might not be
/// allowed. Modify: Return images that may be modified, shared, and used.
/// Changing or editing the image might not be allowed. Modifying, sharing, and
/// using the image for commercial purposes might not be allowed.
/// ModifyCommercially: Return images that may be modified, shared, and used
/// for personal or commercial purposes. Typically, this option returns the
/// fewest images. For more information about these license types, see [Filter
/// Images By License Type](http://go.microsoft.com/fwlink/?LinkId=309768).
/// Possible values include: 'All', 'Any', 'Public', 'Share',
/// 'ShareCommercially', 'Modify', 'ModifyCommercially'
/// </param>
/// <param name='market'>
/// The market where the results come from. Typically, mkt is the country where
/// the user is making the request from. However, it could be a different
/// country if the user is not located in a country where Bing delivers
/// results. The market must be in the form &lt;language code&gt;-&lt;country
/// code&gt;. For example, en-US. The string is case insensitive. For a list of
/// possible market values, see [Market
/// Codes](https://docs.microsoft.com/en-us/bing/bing-custom-search/overview).
/// NOTE: If known, you are encouraged to always specify the market. Specifying
/// the market helps Bing route the request and return an appropriate and
/// optimal response. If you specify a market that is not listed in [Market
/// Codes](https://docs.microsoft.com/en-us/bing/bing-custom-search/overview),
/// Bing uses a best fit market code based on an internal mapping that is
/// subject to change. This parameter and the
/// [cc](https://docs.microsoft.com/en-us/bing/bing-custom-search/overview)
/// query parameter are mutually exclusive—do not specify both.
/// </param>
/// <param name='maxFileSize'>
/// Filter images that are less than or equal to the specified file size. The
/// maximum file size that you may specify is 520,192 bytes. If you specify a
/// larger value, the API uses 520,192. It is possible that the response may
/// include images that are slightly larger than the specified maximum. You may
/// specify this filter and minFileSize to filter images within a range of file
/// sizes.
/// </param>
/// <param name='maxHeight'>
/// Filter images that have a height that is less than or equal to the
/// specified height. Specify the height in pixels. You may specify this filter
/// and minHeight to filter images within a range of heights. This filter and
/// the height filter are mutually exclusive.
/// </param>
/// <param name='maxWidth'>
/// Filter images that have a width that is less than or equal to the specified
/// width. Specify the width in pixels. You may specify this filter and
/// maxWidth to filter images within a range of widths. This filter and the
/// width filter are mutually exclusive.
/// </param>
/// <param name='minFileSize'>
/// Filter images that are greater than or equal to the specified file size.
/// The maximum file size that you may specify is 520,192 bytes. If you specify
/// a larger value, the API uses 520,192. It is possible that the response may
/// include images that are slightly smaller than the specified minimum. You
/// may specify this filter and maxFileSize to filter images within a range of
/// file sizes.
/// </param>
/// <param name='minHeight'>
/// Filter images that have a height that is greater than or equal to the
/// specified height. Specify the height in pixels. You may specify this filter
/// and maxHeight to filter images within a range of heights. This filter and
/// the height filter are mutually exclusive.
/// </param>
/// <param name='minWidth'>
/// Filter images that have a width that is greater than or equal to the
/// specified width. Specify the width in pixels. You may specify this filter
/// and maxWidth to filter images within a range of widths. This filter and the
/// width filter are mutually exclusive.
/// </param>
/// <param name='offset'>
/// The zero-based offset that indicates the number of images to skip before
/// returning images. The default is 0. The offset should be less than
/// ([totalEstimatedMatches](https://docs.microsoft.com/en-us/bing/bing-custom-search/overview)
/// - count). Use this parameter along with the count parameter to page
/// results. For example, if your user interface displays 20 images per page,
/// set count to 20 and offset to 0 to get the first page of results. For each
/// subsequent page, increment offset by 20 (for example, 0, 20, 40). It is
/// possible for multiple pages to include some overlap in results. To prevent
/// duplicates, see
/// [nextOffset](https://docs.microsoft.com/en-us/bing/bing-custom-search/overview).
/// Use this parameter only with the Image API. Do not specify this parameter
/// when calling the Trending Images API or the Web Search API.
/// </param>
/// <param name='safeSearch'>
/// Filter images for adult content. The following are the possible filter
/// values. Off: May return images with adult content. If the request is
/// through the Image Search API, the response includes thumbnail images that
/// are clear (non-fuzzy). However, if the request is through the Web Search
/// API, the response includes thumbnail images that are pixelated (fuzzy).
/// Moderate: If the request is through the Image Search API, the response
/// doesn't include images with adult content. If the request is through the
/// Web Search API, the response may include images with adult content (the
/// thumbnail images are pixelated (fuzzy)). Strict: Do not return images with
/// adult content. The default is Moderate. If the request comes from a market
/// that Bing's adult policy requires that safeSearch is set to Strict, Bing
/// ignores the safeSearch value and uses Strict. If you use the site: query
/// operator, there is the chance that the response may contain adult content
/// regardless of what the safeSearch query parameter is set to. Use site: only
/// if you are aware of the content on the site and your scenario supports the
/// possibility of adult content. Possible values include: 'Off', 'Moderate',
/// 'Strict'
/// </param>
/// <param name='size'>
/// Filter images by the following sizes. All: Do not filter by size.
/// Specifying this value is the same as not specifying the size parameter.
/// Small: Return images that are less than 200x200 pixels. Medium: Return
/// images that are greater than or equal to 200x200 pixels but less than
/// 500x500 pixels. Large: Return images that are 500x500 pixels or larger.
/// Wallpaper: Return wallpaper images. You may use this parameter along with
/// the height or width parameters. For example, you may use height and size to
/// request small images that are 150 pixels tall. Possible values include:
/// 'All', 'Small', 'Medium', 'Large', 'Wallpaper'
/// </param>
/// <param name='setLang'>
/// The language to use for user interface strings. Specify the language using
/// the ISO 639-1 2-letter language code. For example, the language code for
/// English is EN. The default is EN (English). Although optional, you should
/// always specify the language. Typically, you set setLang to the same
/// language specified by mkt unless the user wants the user interface strings
/// displayed in a different language. This parameter and the
/// [Accept-Language](https://docs.microsoft.com/en-us/bing/bing-custom-search/overview)
/// header are mutually exclusive; do not specify both. A user interface string
/// is a string that's used as a label in a user interface. There are few user
/// interface strings in the JSON response objects. Also, any links to Bing.com
/// properties in the response objects apply the specified language.
/// </param>
/// <param name='width'>
/// Filter images that have the specified width, in pixels. You may use this
/// filter with the size filter to return small images that have a width of 150
/// pixels.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Images> ImageSearchAsync(this ICustomInstance operations, string customConfig, string query, string acceptLanguage = default(string), string userAgent = default(string), string clientId = default(string), string clientIp = default(string), string location = default(string), string aspect = default(string), string color = default(string), string countryCode = default(string), int? count = default(int?), string freshness = default(string), int? height = default(int?), string id = default(string), string imageContent = default(string), string imageType = default(string), string license = default(string), string market = default(string), long? maxFileSize = default(long?), long? maxHeight = default(long?), long? maxWidth = default(long?), long? minFileSize = default(long?), long? minHeight = default(long?), long? minWidth = default(long?), long? offset = default(long?), string safeSearch = default(string), string size = default(string), string setLang = default(string), int? width = default(int?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ImageSearchWithHttpMessagesAsync(customConfig, query, acceptLanguage, userAgent, clientId, clientIp, location, aspect, color, countryCode, count, freshness, height, id, imageContent, imageType, license, market, maxFileSize, maxHeight, maxWidth, minFileSize, minHeight, minWidth, offset, safeSearch, size, setLang, width, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}

Просмотреть файл

@ -0,0 +1,48 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomImageSearch
{
using Microsoft.Rest;
using Models;
using Newtonsoft.Json;
/// <summary>
/// The Bing Custom Image Search API lets you send an image search query to
/// Bing and get back image search results customized to meet your custom
/// search definition.
/// </summary>
public partial interface ICustomImageSearchClient : System.IDisposable
{
/// <summary>
/// The base URI of the service.
/// </summary>
System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
JsonSerializerSettings SerializationSettings { get; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
JsonSerializerSettings DeserializationSettings { get; }
/// <summary>
/// Subscription credentials which uniquely identify client
/// subscription.
/// </summary>
ServiceClientCredentials Credentials { get; }
/// <summary>
/// Gets the ICustomInstance.
/// </summary>
ICustomInstance CustomInstance { get; }
}
}

Просмотреть файл

@ -0,0 +1,427 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomImageSearch
{
using Microsoft.Rest;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// CustomInstance operations.
/// </summary>
public partial interface ICustomInstance
{
/// <summary>
/// The Custom Image Search API lets you send an image search query to
/// Bing and get image results found in your custom view of the web.
/// </summary>
/// <param name='customConfig'>
/// The identifier for the custom search configuration
/// </param>
/// <param name='query'>
/// The user's search query term. The term cannot be empty. The term
/// may contain [Bing Advanced
/// Operators](http://msdn.microsoft.com/library/ff795620.aspx). For
/// example, to limit images to a specific domain, use the
/// [site:](http://msdn.microsoft.com/library/ff795613.aspx) operator.
/// To help improve relevance of an insights query (see
/// [insightsToken](https://docs.microsoft.com/en-us/bing/bing-custom-search/overview)),
/// you should always include the user's query term. Use this parameter
/// only with the Image Search API.Do not specify this parameter when
/// calling the Trending Images API.
/// </param>
/// <param name='acceptLanguage'>
/// A comma-delimited list of one or more languages to use for user
/// interface strings. The list is in decreasing order of preference.
/// For additional information, including expected format, see
/// [RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html).
/// This header and the
/// [setLang](https://docs.microsoft.com/en-us/bing/bing-custom-search/overview)
/// query parameter are mutually exclusive; do not specify both. If you
/// set this header, you must also specify the
/// [cc](https://docs.microsoft.com/en-us/bing/bing-custom-search/overview)
/// query parameter. To determine the market to return results for,
/// Bing uses the first supported language it finds from the list and
/// combines it with the cc parameter value. If the list does not
/// include a supported language, Bing finds the closest language and
/// market that supports the request or it uses an aggregated or
/// default market for the results. To determine the market that Bing
/// used, see the BingAPIs-Market header. Use this header and the cc
/// query parameter only if you specify multiple languages. Otherwise,
/// use the
/// [mkt](https://docs.microsoft.com/en-us/bing/bing-custom-search/overview)
/// and
/// [setLang](https://docs.microsoft.com/en-us/bing/bing-custom-search/overview)
/// query parameters. A user interface string is a string that's used
/// as a label in a user interface. There are few user interface
/// strings in the JSON response objects. Any links to Bing.com
/// properties in the response objects apply the specified language.
/// </param>
/// <param name='userAgent'>
/// The user agent originating the request. Bing uses the user agent to
/// provide mobile users with an optimized experience. Although
/// optional, you are encouraged to always specify this header. The
/// user-agent should be the same string that any commonly used browser
/// sends. For information about user agents, see [RFC
/// 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). The
/// following are examples of user-agent strings. Windows Phone:
/// Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0;
/// IEMobile/10.0; ARM; Touch; NOKIA; Lumia 822). Android: Mozilla /
/// 5.0 (Linux; U; Android 2.3.5; en - us; SCH - I500 Build /
/// GINGERBREAD) AppleWebKit / 533.1 (KHTML; like Gecko) Version / 4.0
/// Mobile Safari / 533.1. iPhone: Mozilla / 5.0 (iPhone; CPU iPhone OS
/// 6_1 like Mac OS X) AppleWebKit / 536.26 (KHTML; like Gecko) Mobile
/// / 10B142 iPhone4; 1 BingWeb / 3.03.1428.20120423. PC: Mozilla / 5.0
/// (Windows NT 6.3; WOW64; Trident / 7.0; Touch; rv:11.0) like Gecko.
/// iPad: Mozilla / 5.0 (iPad; CPU OS 7_0 like Mac OS X) AppleWebKit /
/// 537.51.1 (KHTML, like Gecko) Version / 7.0 Mobile / 11A465 Safari /
/// 9537.53
/// </param>
/// <param name='clientId'>
/// Bing uses this header to provide users with consistent behavior
/// across Bing API calls. Bing often flights new features and
/// improvements, and it uses the client ID as a key for assigning
/// traffic on different flights. If you do not use the same client ID
/// for a user across multiple requests, then Bing may assign the user
/// to multiple conflicting flights. Being assigned to multiple
/// conflicting flights can lead to an inconsistent user experience.
/// For example, if the second request has a different flight
/// assignment than the first, the experience may be unexpected. Also,
/// Bing can use the client ID to tailor web results to that client
/// IDs search history, providing a richer experience for the user.
/// Bing also uses this header to help improve result rankings by
/// analyzing the activity generated by a client ID. The relevance
/// improvements help with better quality of results delivered by Bing
/// APIs and in turn enables higher click-through rates for the API
/// consumer. IMPORTANT: Although optional, you should consider this
/// header required. Persisting the client ID across multiple requests
/// for the same end user and device combination enables 1) the API
/// consumer to receive a consistent user experience, and 2) higher
/// click-through rates via better quality of results from the Bing
/// APIs. Each user that uses your application on the device must have
/// a unique, Bing generated client ID. If you do not include this
/// header in the request, Bing generates an ID and returns it in the
/// X-MSEdge-ClientID response header. The only time that you should
/// NOT include this header in a request is the first time the user
/// uses your app on that device. Use the client ID for each Bing API
/// request that your app makes for this user on the device. Persist
/// the client ID. To persist the ID in a browser app, use a persistent
/// HTTP cookie to ensure the ID is used across all sessions. Do not
/// use a session cookie. For other apps such as mobile apps, use the
/// device's persistent storage to persist the ID. The next time the
/// user uses your app on that device, get the client ID that you
/// persisted. Bing responses may or may not include this header. If
/// the response includes this header, capture the client ID and use it
/// for all subsequent Bing requests for the user on that device. If
/// you include the X-MSEdge-ClientID, you must not include cookies in
/// the request.
/// </param>
/// <param name='clientIp'>
/// The IPv4 or IPv6 address of the client device. The IP address is
/// used to discover the user's location. Bing uses the location
/// information to determine safe search behavior. Although optional,
/// you are encouraged to always specify this header and the
/// X-Search-Location header. Do not obfuscate the address (for
/// example, by changing the last octet to 0). Obfuscating the address
/// results in the location not being anywhere near the device's actual
/// location, which may result in Bing serving erroneous results.
/// </param>
/// <param name='location'>
/// A semicolon-delimited list of key/value pairs that describe the
/// client's geographical location. Bing uses the location information
/// to determine safe search behavior and to return relevant local
/// content. Specify the key/value pair as &lt;key&gt;:&lt;value&gt;.
/// The following are the keys that you use to specify the user's
/// location. lat (required): The latitude of the client's location, in
/// degrees. The latitude must be greater than or equal to -90.0 and
/// less than or equal to +90.0. Negative values indicate southern
/// latitudes and positive values indicate northern latitudes. long
/// (required): The longitude of the client's location, in degrees. The
/// longitude must be greater than or equal to -180.0 and less than or
/// equal to +180.0. Negative values indicate western longitudes and
/// positive values indicate eastern longitudes. re (required): The
/// radius, in meters, which specifies the horizontal accuracy of the
/// coordinates. Pass the value returned by the device's location
/// service. Typical values might be 22m for GPS/Wi-Fi, 380m for cell
/// tower triangulation, and 18,000m for reverse IP lookup. ts
/// (optional): The UTC UNIX timestamp of when the client was at the
/// location. (The UNIX timestamp is the number of seconds since
/// January 1, 1970.) head (optional): The client's relative heading or
/// direction of travel. Specify the direction of travel as degrees
/// from 0 through 360, counting clockwise relative to true north.
/// Specify this key only if the sp key is nonzero. sp (optional): The
/// horizontal velocity (speed), in meters per second, that the client
/// device is traveling. alt (optional): The altitude of the client
/// device, in meters. are (optional): The radius, in meters, that
/// specifies the vertical accuracy of the coordinates. Specify this
/// key only if you specify the alt key. Although many of the keys are
/// optional, the more information that you provide, the more accurate
/// the location results are. Although optional, you are encouraged to
/// always specify the user's geographical location. Providing the
/// location is especially important if the client's IP address does
/// not accurately reflect the user's physical location (for example,
/// if the client uses VPN). For optimal results, you should include
/// this header and the X-MSEdge-ClientIP header, but at a minimum, you
/// should include this header.
/// </param>
/// <param name='aspect'>
/// Filter images by the following aspect ratios. All: Do not filter by
/// aspect.Specifying this value is the same as not specifying the
/// aspect parameter. Square: Return images with standard aspect ratio.
/// Wide: Return images with wide screen aspect ratio. Tall: Return
/// images with tall aspect ratio. Possible values include: 'All',
/// 'Square', 'Wide', 'Tall'
/// </param>
/// <param name='color'>
/// Filter images by the following color options. ColorOnly: Return
/// color images. Monochrome: Return black and white images. Return
/// images with one of the following dominant colors: Black, Blue,
/// Brown, Gray, Green, Orange, Pink, Purple, Red, Teal, White, Yellow.
/// Possible values include: 'ColorOnly', 'Monochrome', 'Black',
/// 'Blue', 'Brown', 'Gray', 'Green', 'Orange', 'Pink', 'Purple',
/// 'Red', 'Teal', 'White', 'Yellow'
/// </param>
/// <param name='countryCode'>
/// A 2-character country code of the country where the results come
/// from. For a list of possible values, see [Market
/// Codes](https://docs.microsoft.com/en-us/bing/bing-custom-search/overview).
/// If you set this parameter, you must also specify the
/// [Accept-Language](https://docs.microsoft.com/en-us/bing/bing-custom-search/overview)
/// header. Bing uses the first supported language it finds from the
/// languages list, and combine that language with the country code
/// that you specify to determine the market to return results for. If
/// the languages list does not include a supported language, Bing
/// finds the closest language and market that supports the request, or
/// it may use an aggregated or default market for the results instead
/// of a specified one. You should use this query parameter and the
/// Accept-Language query parameter only if you specify multiple
/// languages; otherwise, you should use the mkt and setLang query
/// parameters. This parameter and the
/// [mkt](https://docs.microsoft.com/en-us/bing/bing-custom-search/overview)
/// query parameter are mutually exclusive—do not specify both.
/// </param>
/// <param name='count'>
/// The number of images to return in the response. The actual number
/// delivered may be less than requested. The default is 35. The
/// maximum value is 150. You use this parameter along with the offset
/// parameter to page results.For example, if your user interface
/// displays 20 images per page, set count to 20 and offset to 0 to get
/// the first page of results.For each subsequent page, increment
/// offset by 20 (for example, 0, 20, 40). Use this parameter only with
/// the Image Search API.Do not specify this parameter when calling the
/// Insights, Trending Images, or Web Search APIs.
/// </param>
/// <param name='freshness'>
/// Filter images by the following discovery options. Day: Return
/// images discovered by Bing within the last 24 hours. Week: Return
/// images discovered by Bing within the last 7 days. Month: Return
/// images discovered by Bing within the last 30 days. Possible values
/// include: 'Day', 'Week', 'Month'
/// </param>
/// <param name='height'>
/// Filter images that have the specified height, in pixels. You may
/// use this filter with the size filter to return small images that
/// have a height of 150 pixels.
/// </param>
/// <param name='id'>
/// An ID that uniquely identifies an image. Use this parameter to
/// ensure that the specified image is the first image in the list of
/// images that Bing returns. The
/// [Image](https://docs.microsoft.com/en-us/bing/bing-custom-search/overview)
/// object's imageId field contains the ID that you set this parameter
/// to.
/// </param>
/// <param name='imageContent'>
/// Filter images by the following content types. Face: Return images
/// that show only a person's face. Portrait: Return images that show
/// only a person's head and shoulders. Possible values include:
/// 'Face', 'Portrait'
/// </param>
/// <param name='imageType'>
/// Filter images by the following image types. AnimatedGif: Return
/// only animated GIFs. Clipart: Return only clip art images. Line:
/// Return only line drawings. Photo: Return only photographs(excluding
/// line drawings, animated Gifs, and clip art). Shopping: Return only
/// images that contain items where Bing knows of a merchant that is
/// selling the items. This option is valid in the en - US market
/// only.Transparent: Return only images with a transparent background.
/// Possible values include: 'AnimatedGif', 'Clipart', 'Line', 'Photo',
/// 'Shopping', 'Transparent'
/// </param>
/// <param name='license'>
/// Filter images by the following license types. All: Do not filter by
/// license type.Specifying this value is the same as not specifying
/// the license parameter. Any: Return images that are under any
/// license type. The response doesn't include images that do not
/// specify a license or the license is unknown. Public: Return images
/// where the creator has waived their exclusive rights, to the fullest
/// extent allowed by law. Share: Return images that may be shared with
/// others. Changing or editing the image might not be allowed. Also,
/// modifying, sharing, and using the image for commercial purposes
/// might not be allowed. Typically, this option returns the most
/// images. ShareCommercially: Return images that may be shared with
/// others for personal or commercial purposes. Changing or editing the
/// image might not be allowed. Modify: Return images that may be
/// modified, shared, and used. Changing or editing the image might not
/// be allowed. Modifying, sharing, and using the image for commercial
/// purposes might not be allowed. ModifyCommercially: Return images
/// that may be modified, shared, and used for personal or commercial
/// purposes. Typically, this option returns the fewest images. For
/// more information about these license types, see [Filter Images By
/// License Type](http://go.microsoft.com/fwlink/?LinkId=309768).
/// Possible values include: 'All', 'Any', 'Public', 'Share',
/// 'ShareCommercially', 'Modify', 'ModifyCommercially'
/// </param>
/// <param name='market'>
/// The market where the results come from. Typically, mkt is the
/// country where the user is making the request from. However, it
/// could be a different country if the user is not located in a
/// country where Bing delivers results. The market must be in the form
/// &lt;language code&gt;-&lt;country code&gt;. For example, en-US. The
/// string is case insensitive. For a list of possible market values,
/// see [Market
/// Codes](https://docs.microsoft.com/en-us/bing/bing-custom-search/overview).
/// NOTE: If known, you are encouraged to always specify the market.
/// Specifying the market helps Bing route the request and return an
/// appropriate and optimal response. If you specify a market that is
/// not listed in [Market
/// Codes](https://docs.microsoft.com/en-us/bing/bing-custom-search/overview),
/// Bing uses a best fit market code based on an internal mapping that
/// is subject to change. This parameter and the
/// [cc](https://docs.microsoft.com/en-us/bing/bing-custom-search/overview)
/// query parameter are mutually exclusive—do not specify both.
/// </param>
/// <param name='maxFileSize'>
/// Filter images that are less than or equal to the specified file
/// size. The maximum file size that you may specify is 520,192 bytes.
/// If you specify a larger value, the API uses 520,192. It is possible
/// that the response may include images that are slightly larger than
/// the specified maximum. You may specify this filter and minFileSize
/// to filter images within a range of file sizes.
/// </param>
/// <param name='maxHeight'>
/// Filter images that have a height that is less than or equal to the
/// specified height. Specify the height in pixels. You may specify
/// this filter and minHeight to filter images within a range of
/// heights. This filter and the height filter are mutually exclusive.
/// </param>
/// <param name='maxWidth'>
/// Filter images that have a width that is less than or equal to the
/// specified width. Specify the width in pixels. You may specify this
/// filter and maxWidth to filter images within a range of widths. This
/// filter and the width filter are mutually exclusive.
/// </param>
/// <param name='minFileSize'>
/// Filter images that are greater than or equal to the specified file
/// size. The maximum file size that you may specify is 520,192 bytes.
/// If you specify a larger value, the API uses 520,192. It is possible
/// that the response may include images that are slightly smaller than
/// the specified minimum. You may specify this filter and maxFileSize
/// to filter images within a range of file sizes.
/// </param>
/// <param name='minHeight'>
/// Filter images that have a height that is greater than or equal to
/// the specified height. Specify the height in pixels. You may specify
/// this filter and maxHeight to filter images within a range of
/// heights. This filter and the height filter are mutually exclusive.
/// </param>
/// <param name='minWidth'>
/// Filter images that have a width that is greater than or equal to
/// the specified width. Specify the width in pixels. You may specify
/// this filter and maxWidth to filter images within a range of widths.
/// This filter and the width filter are mutually exclusive.
/// </param>
/// <param name='offset'>
/// The zero-based offset that indicates the number of images to skip
/// before returning images. The default is 0. The offset should be
/// less than
/// ([totalEstimatedMatches](https://docs.microsoft.com/en-us/bing/bing-custom-search/overview)
/// - count). Use this parameter along with the count parameter to page
/// results. For example, if your user interface displays 20 images per
/// page, set count to 20 and offset to 0 to get the first page of
/// results. For each subsequent page, increment offset by 20 (for
/// example, 0, 20, 40). It is possible for multiple pages to include
/// some overlap in results. To prevent duplicates, see
/// [nextOffset](https://docs.microsoft.com/en-us/bing/bing-custom-search/overview).
/// Use this parameter only with the Image API. Do not specify this
/// parameter when calling the Trending Images API or the Web Search
/// API.
/// </param>
/// <param name='safeSearch'>
/// Filter images for adult content. The following are the possible
/// filter values. Off: May return images with adult content. If the
/// request is through the Image Search API, the response includes
/// thumbnail images that are clear (non-fuzzy). However, if the
/// request is through the Web Search API, the response includes
/// thumbnail images that are pixelated (fuzzy). Moderate: If the
/// request is through the Image Search API, the response doesn't
/// include images with adult content. If the request is through the
/// Web Search API, the response may include images with adult content
/// (the thumbnail images are pixelated (fuzzy)). Strict: Do not return
/// images with adult content. The default is Moderate. If the request
/// comes from a market that Bing's adult policy requires that
/// safeSearch is set to Strict, Bing ignores the safeSearch value and
/// uses Strict. If you use the site: query operator, there is the
/// chance that the response may contain adult content regardless of
/// what the safeSearch query parameter is set to. Use site: only if
/// you are aware of the content on the site and your scenario supports
/// the possibility of adult content. Possible values include: 'Off',
/// 'Moderate', 'Strict'
/// </param>
/// <param name='size'>
/// Filter images by the following sizes. All: Do not filter by size.
/// Specifying this value is the same as not specifying the size
/// parameter. Small: Return images that are less than 200x200 pixels.
/// Medium: Return images that are greater than or equal to 200x200
/// pixels but less than 500x500 pixels. Large: Return images that are
/// 500x500 pixels or larger. Wallpaper: Return wallpaper images. You
/// may use this parameter along with the height or width parameters.
/// For example, you may use height and size to request small images
/// that are 150 pixels tall. Possible values include: 'All', 'Small',
/// 'Medium', 'Large', 'Wallpaper'
/// </param>
/// <param name='setLang'>
/// The language to use for user interface strings. Specify the
/// language using the ISO 639-1 2-letter language code. For example,
/// the language code for English is EN. The default is EN (English).
/// Although optional, you should always specify the language.
/// Typically, you set setLang to the same language specified by mkt
/// unless the user wants the user interface strings displayed in a
/// different language. This parameter and the
/// [Accept-Language](https://docs.microsoft.com/en-us/bing/bing-custom-search/overview)
/// header are mutually exclusive; do not specify both. A user
/// interface string is a string that's used as a label in a user
/// interface. There are few user interface strings in the JSON
/// response objects. Also, any links to Bing.com properties in the
/// response objects apply the specified language.
/// </param>
/// <param name='width'>
/// Filter images that have the specified width, in pixels. You may use
/// this filter with the size filter to return small images that have a
/// width of 150 pixels.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse<Images>> ImageSearchWithHttpMessagesAsync(string customConfig, string query, string acceptLanguage = default(string), string userAgent = default(string), string clientId = default(string), string clientIp = default(string), string location = default(string), string aspect = default(string), string color = default(string), string countryCode = default(string), int? count = default(int?), string freshness = default(string), int? height = default(int?), string id = default(string), string imageContent = default(string), string imageType = default(string), string license = default(string), string market = default(string), long? maxFileSize = default(long?), long? maxHeight = default(long?), long? maxWidth = default(long?), long? minFileSize = default(long?), long? minHeight = default(long?), long? minWidth = default(long?), long? offset = default(long?), string safeSearch = default(string), string size = default(string), string setLang = default(string), int? width = default(int?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}

Просмотреть файл

@ -0,0 +1,43 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomImageSearch.Models
{
using System.Linq;
/// <summary>
/// Defines an answer.
/// </summary>
public partial class Answer : Response
{
/// <summary>
/// Initializes a new instance of the Answer class.
/// </summary>
public Answer()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the Answer class.
/// </summary>
/// <param name="id">A String identifier.</param>
/// <param name="readLink">The URL that returns this resource.</param>
/// <param name="webSearchUrl">The URL To Bing's search result for this
/// item.</param>
public Answer(string _type = default(string), string id = default(string), string readLink = default(string), string webSearchUrl = default(string))
: base(_type, id, readLink, webSearchUrl)
{
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
}
}

Просмотреть файл

@ -0,0 +1,81 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomImageSearch.Models
{
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// The most generic kind of creative work, including books, movies,
/// photographs, software programs, etc.
/// </summary>
public partial class CreativeWork : Thing
{
/// <summary>
/// Initializes a new instance of the CreativeWork class.
/// </summary>
public CreativeWork()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the CreativeWork class.
/// </summary>
/// <param name="id">A String identifier.</param>
/// <param name="readLink">The URL that returns this resource.</param>
/// <param name="webSearchUrl">The URL To Bing's search result for this
/// item.</param>
/// <param name="name">The name of the thing represented by this
/// object.</param>
/// <param name="url">The URL to get more information about the thing
/// represented by this object.</param>
/// <param name="image">An image of the item.</param>
/// <param name="description">A short description of the item.</param>
/// <param name="alternateName">An alias for the item</param>
/// <param name="bingId">An ID that uniquely identifies this
/// item.</param>
/// <param name="thumbnailUrl">The URL to a thumbnail of the
/// item.</param>
/// <param name="provider">The source of the creative work.</param>
/// <param name="text">Text content of this creative work</param>
public CreativeWork(string _type = default(string), string id = default(string), string readLink = default(string), string webSearchUrl = default(string), string name = default(string), string url = default(string), ImageObject image = default(ImageObject), string description = default(string), string alternateName = default(string), string bingId = default(string), string thumbnailUrl = default(string), IList<Thing> provider = default(IList<Thing>), string text = default(string))
: base(_type, id, readLink, webSearchUrl, name, url, image, description, alternateName, bingId)
{
ThumbnailUrl = thumbnailUrl;
Provider = provider;
Text = text;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets the URL to a thumbnail of the item.
/// </summary>
[JsonProperty(PropertyName = "thumbnailUrl")]
public string ThumbnailUrl { get; private set; }
/// <summary>
/// Gets the source of the creative work.
/// </summary>
[JsonProperty(PropertyName = "provider")]
public IList<Thing> Provider { get; private set; }
/// <summary>
/// Gets text content of this creative work
/// </summary>
[JsonProperty(PropertyName = "text")]
public string Text { get; private set; }
}
}

Просмотреть файл

@ -0,0 +1,125 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomImageSearch.Models
{
using Microsoft.Rest;
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Defines the error that occurred.
/// </summary>
public partial class Error
{
/// <summary>
/// Initializes a new instance of the Error class.
/// </summary>
public Error()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the Error class.
/// </summary>
/// <param name="code">The error code that identifies the category of
/// error. Possible values include: 'None', 'ServerError',
/// 'InvalidRequest', 'RateLimitExceeded', 'InvalidAuthorization',
/// 'InsufficientAuthorization'</param>
/// <param name="message">A description of the error.</param>
/// <param name="subCode">The error code that further helps to identify
/// the error. Possible values include: 'UnexpectedError',
/// 'ResourceError', 'NotImplemented', 'ParameterMissing',
/// 'ParameterInvalidValue', 'HttpNotAllowed', 'Blocked',
/// 'AuthorizationMissing', 'AuthorizationRedundancy',
/// 'AuthorizationDisabled', 'AuthorizationExpired'</param>
/// <param name="moreDetails">A description that provides additional
/// information about the error.</param>
/// <param name="parameter">The parameter in the request that caused
/// the error.</param>
/// <param name="value">The parameter's value in the request that was
/// not valid.</param>
public Error(string code, string message, string subCode = default(string), string moreDetails = default(string), string parameter = default(string), string value = default(string))
{
Code = code;
SubCode = subCode;
Message = message;
MoreDetails = moreDetails;
Parameter = parameter;
Value = value;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets the error code that identifies the category of error.
/// Possible values include: 'None', 'ServerError', 'InvalidRequest',
/// 'RateLimitExceeded', 'InvalidAuthorization',
/// 'InsufficientAuthorization'
/// </summary>
[JsonProperty(PropertyName = "code")]
public string Code { get; set; }
/// <summary>
/// Gets the error code that further helps to identify the error.
/// Possible values include: 'UnexpectedError', 'ResourceError',
/// 'NotImplemented', 'ParameterMissing', 'ParameterInvalidValue',
/// 'HttpNotAllowed', 'Blocked', 'AuthorizationMissing',
/// 'AuthorizationRedundancy', 'AuthorizationDisabled',
/// 'AuthorizationExpired'
/// </summary>
[JsonProperty(PropertyName = "subCode")]
public string SubCode { get; private set; }
/// <summary>
/// Gets or sets a description of the error.
/// </summary>
[JsonProperty(PropertyName = "message")]
public string Message { get; set; }
/// <summary>
/// Gets a description that provides additional information about the
/// error.
/// </summary>
[JsonProperty(PropertyName = "moreDetails")]
public string MoreDetails { get; private set; }
/// <summary>
/// Gets the parameter in the request that caused the error.
/// </summary>
[JsonProperty(PropertyName = "parameter")]
public string Parameter { get; private set; }
/// <summary>
/// Gets the parameter's value in the request that was not valid.
/// </summary>
[JsonProperty(PropertyName = "value")]
public string Value { get; private set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (Code == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Code");
}
if (Message == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Message");
}
}
}
}

Просмотреть файл

@ -0,0 +1,22 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomImageSearch.Models
{
/// <summary>
/// Defines values for ErrorCode.
/// </summary>
public static class ErrorCode
{
public const string None = "None";
public const string ServerError = "ServerError";
public const string InvalidRequest = "InvalidRequest";
public const string RateLimitExceeded = "RateLimitExceeded";
public const string InvalidAuthorization = "InvalidAuthorization";
public const string InsufficientAuthorization = "InsufficientAuthorization";
}
}

Просмотреть файл

@ -0,0 +1,80 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomImageSearch.Models
{
using Microsoft.Rest;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// The top-level response that represents a failed request.
/// </summary>
public partial class ErrorResponse : Response
{
/// <summary>
/// Initializes a new instance of the ErrorResponse class.
/// </summary>
public ErrorResponse()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the ErrorResponse class.
/// </summary>
/// <param name="errors">A list of errors that describe the reasons why
/// the request failed.</param>
/// <param name="id">A String identifier.</param>
/// <param name="readLink">The URL that returns this resource.</param>
/// <param name="webSearchUrl">The URL To Bing's search result for this
/// item.</param>
public ErrorResponse(IList<Error> errors, string _type = default(string), string id = default(string), string readLink = default(string), string webSearchUrl = default(string))
: base(_type, id, readLink, webSearchUrl)
{
Errors = errors;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets a list of errors that describe the reasons why the
/// request failed.
/// </summary>
[JsonProperty(PropertyName = "errors")]
public IList<Error> Errors { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (Errors == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Errors");
}
if (Errors != null)
{
foreach (var element in Errors)
{
if (element != null)
{
element.Validate();
}
}
}
}
}
}

Просмотреть файл

@ -0,0 +1,58 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomImageSearch.Models
{
using Microsoft.Rest;
/// <summary>
/// Exception thrown for an invalid response with ErrorResponse
/// information.
/// </summary>
public partial class ErrorResponseException : RestException
{
/// <summary>
/// Gets information about the associated HTTP request.
/// </summary>
public HttpRequestMessageWrapper Request { get; set; }
/// <summary>
/// Gets information about the associated HTTP response.
/// </summary>
public HttpResponseMessageWrapper Response { get; set; }
/// <summary>
/// Gets or sets the body object.
/// </summary>
public ErrorResponse Body { get; set; }
/// <summary>
/// Initializes a new instance of the ErrorResponseException class.
/// </summary>
public ErrorResponseException()
{
}
/// <summary>
/// Initializes a new instance of the ErrorResponseException class.
/// </summary>
/// <param name="message">The exception message.</param>
public ErrorResponseException(string message)
: this(message, null)
{
}
/// <summary>
/// Initializes a new instance of the ErrorResponseException class.
/// </summary>
/// <param name="message">The exception message.</param>
/// <param name="innerException">Inner exception.</param>
public ErrorResponseException(string message, System.Exception innerException)
: base(message, innerException)
{
}
}
}

Просмотреть файл

@ -0,0 +1,27 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomImageSearch.Models
{
/// <summary>
/// Defines values for ErrorSubCode.
/// </summary>
public static class ErrorSubCode
{
public const string UnexpectedError = "UnexpectedError";
public const string ResourceError = "ResourceError";
public const string NotImplemented = "NotImplemented";
public const string ParameterMissing = "ParameterMissing";
public const string ParameterInvalidValue = "ParameterInvalidValue";
public const string HttpNotAllowed = "HttpNotAllowed";
public const string Blocked = "Blocked";
public const string AuthorizationMissing = "AuthorizationMissing";
public const string AuthorizationRedundancy = "AuthorizationRedundancy";
public const string AuthorizationDisabled = "AuthorizationDisabled";
public const string AuthorizationExpired = "AuthorizationExpired";
}
}

Просмотреть файл

@ -0,0 +1,19 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomImageSearch.Models
{
/// <summary>
/// Defines values for Freshness.
/// </summary>
public static class Freshness
{
public const string Day = "Day";
public const string Week = "Week";
public const string Month = "Month";
}
}

Просмотреть файл

@ -0,0 +1,48 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomImageSearch.Models
{
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Defines the identity of a resource.
/// </summary>
public partial class Identifiable : ResponseBase
{
/// <summary>
/// Initializes a new instance of the Identifiable class.
/// </summary>
public Identifiable()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the Identifiable class.
/// </summary>
/// <param name="id">A String identifier.</param>
public Identifiable(string _type = default(string), string id = default(string))
: base(_type)
{
Id = id;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets a String identifier.
/// </summary>
[JsonProperty(PropertyName = "id")]
public string Id { get; private set; }
}
}

Просмотреть файл

@ -0,0 +1,20 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomImageSearch.Models
{
/// <summary>
/// Defines values for ImageAspect.
/// </summary>
public static class ImageAspect
{
public const string All = "All";
public const string Square = "Square";
public const string Wide = "Wide";
public const string Tall = "Tall";
}
}

Просмотреть файл

@ -0,0 +1,30 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomImageSearch.Models
{
/// <summary>
/// Defines values for ImageColor.
/// </summary>
public static class ImageColor
{
public const string ColorOnly = "ColorOnly";
public const string Monochrome = "Monochrome";
public const string Black = "Black";
public const string Blue = "Blue";
public const string Brown = "Brown";
public const string Gray = "Gray";
public const string Green = "Green";
public const string Orange = "Orange";
public const string Pink = "Pink";
public const string Purple = "Purple";
public const string Red = "Red";
public const string Teal = "Teal";
public const string White = "White";
public const string Yellow = "Yellow";
}
}

Просмотреть файл

@ -0,0 +1,18 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomImageSearch.Models
{
/// <summary>
/// Defines values for ImageContent.
/// </summary>
public static class ImageContent
{
public const string Face = "Face";
public const string Portrait = "Portrait";
}
}

Просмотреть файл

@ -0,0 +1,23 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomImageSearch.Models
{
/// <summary>
/// Defines values for ImageLicense.
/// </summary>
public static class ImageLicense
{
public const string All = "All";
public const string Any = "Any";
public const string Public = "Public";
public const string Share = "Share";
public const string ShareCommercially = "ShareCommercially";
public const string Modify = "Modify";
public const string ModifyCommercially = "ModifyCommercially";
}
}

Просмотреть файл

@ -0,0 +1,126 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomImageSearch.Models
{
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Defines an image
/// </summary>
public partial class ImageObject : MediaObject
{
/// <summary>
/// Initializes a new instance of the ImageObject class.
/// </summary>
public ImageObject()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the ImageObject class.
/// </summary>
/// <param name="id">A String identifier.</param>
/// <param name="readLink">The URL that returns this resource.</param>
/// <param name="webSearchUrl">The URL To Bing's search result for this
/// item.</param>
/// <param name="name">The name of the thing represented by this
/// object.</param>
/// <param name="url">The URL to get more information about the thing
/// represented by this object.</param>
/// <param name="image">An image of the item.</param>
/// <param name="description">A short description of the item.</param>
/// <param name="alternateName">An alias for the item</param>
/// <param name="bingId">An ID that uniquely identifies this
/// item.</param>
/// <param name="thumbnailUrl">The URL to a thumbnail of the
/// item.</param>
/// <param name="provider">The source of the creative work.</param>
/// <param name="text">Text content of this creative work</param>
/// <param name="contentUrl">Original URL to retrieve the source (file)
/// for the media object (e.g the source URL for the image).</param>
/// <param name="hostPageUrl">URL of the page that hosts the media
/// object.</param>
/// <param name="contentSize">Size of the media object content (use
/// format "value unit" e.g "1024 B").</param>
/// <param name="encodingFormat">Encoding format (e.g mp3, mp4, jpeg,
/// etc).</param>
/// <param name="hostPageDisplayUrl">Display URL of the page that hosts
/// the media object.</param>
/// <param name="width">The width of the media object, in
/// pixels.</param>
/// <param name="height">The height of the media object, in
/// pixels.</param>
/// <param name="thumbnail">The URL to a thumbnail of the image</param>
/// <param name="imageInsightsToken">The token that you use in a
/// subsequent call to the Image Search API to get additional
/// information about the image. For information about using this
/// token, see the insightsToken query parameter.</param>
/// <param name="imageId">Unique Id for the image</param>
/// <param name="accentColor">A three-byte hexadecimal number that
/// represents the color that dominates the image. Use the color as the
/// temporary background in your client until the image is
/// loaded.</param>
/// <param name="visualWords">Visual representation of the image. Used
/// for getting more sizes</param>
public ImageObject(string _type = default(string), string id = default(string), string readLink = default(string), string webSearchUrl = default(string), string name = default(string), string url = default(string), ImageObject image = default(ImageObject), string description = default(string), string alternateName = default(string), string bingId = default(string), string thumbnailUrl = default(string), IList<Thing> provider = default(IList<Thing>), string text = default(string), string contentUrl = default(string), string hostPageUrl = default(string), string contentSize = default(string), string encodingFormat = default(string), string hostPageDisplayUrl = default(string), int? width = default(int?), int? height = default(int?), ImageObject thumbnail = default(ImageObject), string imageInsightsToken = default(string), string imageId = default(string), string accentColor = default(string), string visualWords = default(string))
: base(_type, id, readLink, webSearchUrl, name, url, image, description, alternateName, bingId, thumbnailUrl, provider, text, contentUrl, hostPageUrl, contentSize, encodingFormat, hostPageDisplayUrl, width, height)
{
Thumbnail = thumbnail;
ImageInsightsToken = imageInsightsToken;
ImageId = imageId;
AccentColor = accentColor;
VisualWords = visualWords;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets the URL to a thumbnail of the image
/// </summary>
[JsonProperty(PropertyName = "thumbnail")]
public ImageObject Thumbnail { get; private set; }
/// <summary>
/// Gets the token that you use in a subsequent call to the Image
/// Search API to get additional information about the image. For
/// information about using this token, see the insightsToken query
/// parameter.
/// </summary>
[JsonProperty(PropertyName = "imageInsightsToken")]
public string ImageInsightsToken { get; private set; }
/// <summary>
/// Gets unique Id for the image
/// </summary>
[JsonProperty(PropertyName = "imageId")]
public string ImageId { get; private set; }
/// <summary>
/// Gets a three-byte hexadecimal number that represents the color that
/// dominates the image. Use the color as the temporary background in
/// your client until the image is loaded.
/// </summary>
[JsonProperty(PropertyName = "accentColor")]
public string AccentColor { get; private set; }
/// <summary>
/// Gets visual representation of the image. Used for getting more
/// sizes
/// </summary>
[JsonProperty(PropertyName = "visualWords")]
public string VisualWords { get; private set; }
}
}

Просмотреть файл

@ -0,0 +1,21 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomImageSearch.Models
{
/// <summary>
/// Defines values for ImageSize.
/// </summary>
public static class ImageSize
{
public const string All = "All";
public const string Small = "Small";
public const string Medium = "Medium";
public const string Large = "Large";
public const string Wallpaper = "Wallpaper";
}
}

Просмотреть файл

@ -0,0 +1,22 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomImageSearch.Models
{
/// <summary>
/// Defines values for ImageType.
/// </summary>
public static class ImageType
{
public const string AnimatedGif = "AnimatedGif";
public const string Clipart = "Clipart";
public const string Line = "Line";
public const string Photo = "Photo";
public const string Shopping = "Shopping";
public const string Transparent = "Transparent";
}
}

Просмотреть файл

@ -0,0 +1,84 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomImageSearch.Models
{
using Microsoft.Rest;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Defines an image answer
/// </summary>
public partial class Images : SearchResultsAnswer
{
/// <summary>
/// Initializes a new instance of the Images class.
/// </summary>
public Images()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the Images class.
/// </summary>
/// <param name="value">A list of image objects that are relevant to
/// the query. If there are no results, the List is empty.</param>
/// <param name="id">A String identifier.</param>
/// <param name="readLink">The URL that returns this resource.</param>
/// <param name="webSearchUrl">The URL To Bing's search result for this
/// item.</param>
/// <param name="totalEstimatedMatches">The estimated number of
/// webpages that are relevant to the query. Use this number along with
/// the count and offset query parameters to page the results.</param>
/// <param name="nextOffset">Used as part of deduping. Tells client the
/// next offset that client should use in the next pagination
/// request</param>
public Images(IList<ImageObject> value, string _type = default(string), string id = default(string), string readLink = default(string), string webSearchUrl = default(string), long? totalEstimatedMatches = default(long?), int? nextOffset = default(int?))
: base(_type, id, readLink, webSearchUrl, totalEstimatedMatches)
{
NextOffset = nextOffset;
Value = value;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets used as part of deduping. Tells client the next offset that
/// client should use in the next pagination request
/// </summary>
[JsonProperty(PropertyName = "nextOffset")]
public int? NextOffset { get; private set; }
/// <summary>
/// Gets or sets a list of image objects that are relevant to the
/// query. If there are no results, the List is empty.
/// </summary>
[JsonProperty(PropertyName = "value")]
public IList<ImageObject> Value { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (Value == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Value");
}
}
}
}

Просмотреть файл

@ -0,0 +1,124 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomImageSearch.Models
{
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Defines a media object.
/// </summary>
public partial class MediaObject : CreativeWork
{
/// <summary>
/// Initializes a new instance of the MediaObject class.
/// </summary>
public MediaObject()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the MediaObject class.
/// </summary>
/// <param name="id">A String identifier.</param>
/// <param name="readLink">The URL that returns this resource.</param>
/// <param name="webSearchUrl">The URL To Bing's search result for this
/// item.</param>
/// <param name="name">The name of the thing represented by this
/// object.</param>
/// <param name="url">The URL to get more information about the thing
/// represented by this object.</param>
/// <param name="image">An image of the item.</param>
/// <param name="description">A short description of the item.</param>
/// <param name="alternateName">An alias for the item</param>
/// <param name="bingId">An ID that uniquely identifies this
/// item.</param>
/// <param name="thumbnailUrl">The URL to a thumbnail of the
/// item.</param>
/// <param name="provider">The source of the creative work.</param>
/// <param name="text">Text content of this creative work</param>
/// <param name="contentUrl">Original URL to retrieve the source (file)
/// for the media object (e.g the source URL for the image).</param>
/// <param name="hostPageUrl">URL of the page that hosts the media
/// object.</param>
/// <param name="contentSize">Size of the media object content (use
/// format "value unit" e.g "1024 B").</param>
/// <param name="encodingFormat">Encoding format (e.g mp3, mp4, jpeg,
/// etc).</param>
/// <param name="hostPageDisplayUrl">Display URL of the page that hosts
/// the media object.</param>
/// <param name="width">The width of the media object, in
/// pixels.</param>
/// <param name="height">The height of the media object, in
/// pixels.</param>
public MediaObject(string _type = default(string), string id = default(string), string readLink = default(string), string webSearchUrl = default(string), string name = default(string), string url = default(string), ImageObject image = default(ImageObject), string description = default(string), string alternateName = default(string), string bingId = default(string), string thumbnailUrl = default(string), IList<Thing> provider = default(IList<Thing>), string text = default(string), string contentUrl = default(string), string hostPageUrl = default(string), string contentSize = default(string), string encodingFormat = default(string), string hostPageDisplayUrl = default(string), int? width = default(int?), int? height = default(int?))
: base(_type, id, readLink, webSearchUrl, name, url, image, description, alternateName, bingId, thumbnailUrl, provider, text)
{
ContentUrl = contentUrl;
HostPageUrl = hostPageUrl;
ContentSize = contentSize;
EncodingFormat = encodingFormat;
HostPageDisplayUrl = hostPageDisplayUrl;
Width = width;
Height = height;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets original URL to retrieve the source (file) for the media
/// object (e.g the source URL for the image).
/// </summary>
[JsonProperty(PropertyName = "contentUrl")]
public string ContentUrl { get; private set; }
/// <summary>
/// Gets URL of the page that hosts the media object.
/// </summary>
[JsonProperty(PropertyName = "hostPageUrl")]
public string HostPageUrl { get; private set; }
/// <summary>
/// Gets size of the media object content (use format "value unit" e.g
/// "1024 B").
/// </summary>
[JsonProperty(PropertyName = "contentSize")]
public string ContentSize { get; private set; }
/// <summary>
/// Gets encoding format (e.g mp3, mp4, jpeg, etc).
/// </summary>
[JsonProperty(PropertyName = "encodingFormat")]
public string EncodingFormat { get; private set; }
/// <summary>
/// Gets display URL of the page that hosts the media object.
/// </summary>
[JsonProperty(PropertyName = "hostPageDisplayUrl")]
public string HostPageDisplayUrl { get; private set; }
/// <summary>
/// Gets the width of the media object, in pixels.
/// </summary>
[JsonProperty(PropertyName = "width")]
public int? Width { get; private set; }
/// <summary>
/// Gets the height of the media object, in pixels.
/// </summary>
[JsonProperty(PropertyName = "height")]
public int? Height { get; private set; }
}
}

Просмотреть файл

@ -0,0 +1,114 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomImageSearch.Models
{
using Microsoft.Rest;
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Defines a search query.
/// </summary>
public partial class Query
{
/// <summary>
/// Initializes a new instance of the Query class.
/// </summary>
public Query()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the Query class.
/// </summary>
/// <param name="text">The query string. Use this string as the query
/// term in a new search request.</param>
/// <param name="displayText">The display version of the query term.
/// This version of the query term may contain special characters that
/// highlight the search term found in the query string. The string
/// contains the highlighting characters only if the query enabled hit
/// highlighting</param>
/// <param name="webSearchUrl">The URL that takes the user to the Bing
/// search results page for the query.Only related search results
/// include this field.</param>
/// <param name="searchLink">The URL that you use to get the results of
/// the related search. Before using the URL, you must append query
/// parameters as appropriate and include the Ocp-Apim-Subscription-Key
/// header. Use this URL if you're displaying the results in your own
/// user interface. Otherwise, use the webSearchUrl URL.</param>
/// <param name="thumbnail">The URL to a thumbnail of a related
/// image.</param>
public Query(string text, string displayText = default(string), string webSearchUrl = default(string), string searchLink = default(string), ImageObject thumbnail = default(ImageObject))
{
Text = text;
DisplayText = displayText;
WebSearchUrl = webSearchUrl;
SearchLink = searchLink;
Thumbnail = thumbnail;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets the query string. Use this string as the query term in
/// a new search request.
/// </summary>
[JsonProperty(PropertyName = "text")]
public string Text { get; set; }
/// <summary>
/// Gets the display version of the query term. This version of the
/// query term may contain special characters that highlight the search
/// term found in the query string. The string contains the
/// highlighting characters only if the query enabled hit highlighting
/// </summary>
[JsonProperty(PropertyName = "displayText")]
public string DisplayText { get; private set; }
/// <summary>
/// Gets the URL that takes the user to the Bing search results page
/// for the query.Only related search results include this field.
/// </summary>
[JsonProperty(PropertyName = "webSearchUrl")]
public string WebSearchUrl { get; private set; }
/// <summary>
/// Gets the URL that you use to get the results of the related search.
/// Before using the URL, you must append query parameters as
/// appropriate and include the Ocp-Apim-Subscription-Key header. Use
/// this URL if you're displaying the results in your own user
/// interface. Otherwise, use the webSearchUrl URL.
/// </summary>
[JsonProperty(PropertyName = "searchLink")]
public string SearchLink { get; private set; }
/// <summary>
/// Gets the URL to a thumbnail of a related image.
/// </summary>
[JsonProperty(PropertyName = "thumbnail")]
public ImageObject Thumbnail { get; private set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (Text == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Text");
}
}
}
}

Просмотреть файл

@ -0,0 +1,59 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomImageSearch.Models
{
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Defines a response. All schemas that could be returned at the root of a
/// response should inherit from this
/// </summary>
public partial class Response : Identifiable
{
/// <summary>
/// Initializes a new instance of the Response class.
/// </summary>
public Response()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the Response class.
/// </summary>
/// <param name="id">A String identifier.</param>
/// <param name="readLink">The URL that returns this resource.</param>
/// <param name="webSearchUrl">The URL To Bing's search result for this
/// item.</param>
public Response(string _type = default(string), string id = default(string), string readLink = default(string), string webSearchUrl = default(string))
: base(_type, id)
{
ReadLink = readLink;
WebSearchUrl = webSearchUrl;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets the URL that returns this resource.
/// </summary>
[JsonProperty(PropertyName = "readLink")]
public string ReadLink { get; private set; }
/// <summary>
/// Gets the URL To Bing's search result for this item.
/// </summary>
[JsonProperty(PropertyName = "webSearchUrl")]
public string WebSearchUrl { get; private set; }
}
}

Просмотреть файл

@ -0,0 +1,45 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomImageSearch.Models
{
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Response base
/// </summary>
public partial class ResponseBase
{
/// <summary>
/// Initializes a new instance of the ResponseBase class.
/// </summary>
public ResponseBase()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the ResponseBase class.
/// </summary>
public ResponseBase(string _type = default(string))
{
this._type = _type;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "_type")]
public string _type { get; set; }
}
}

Просмотреть файл

@ -0,0 +1,19 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomImageSearch.Models
{
/// <summary>
/// Defines values for SafeSearch.
/// </summary>
public static class SafeSearch
{
public const string Off = "Off";
public const string Moderate = "Moderate";
public const string Strict = "Strict";
}
}

Просмотреть файл

@ -0,0 +1,56 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomImageSearch.Models
{
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Defines a search result answer.
/// </summary>
public partial class SearchResultsAnswer : Answer
{
/// <summary>
/// Initializes a new instance of the SearchResultsAnswer class.
/// </summary>
public SearchResultsAnswer()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the SearchResultsAnswer class.
/// </summary>
/// <param name="id">A String identifier.</param>
/// <param name="readLink">The URL that returns this resource.</param>
/// <param name="webSearchUrl">The URL To Bing's search result for this
/// item.</param>
/// <param name="totalEstimatedMatches">The estimated number of
/// webpages that are relevant to the query. Use this number along with
/// the count and offset query parameters to page the results.</param>
public SearchResultsAnswer(string _type = default(string), string id = default(string), string readLink = default(string), string webSearchUrl = default(string), long? totalEstimatedMatches = default(long?))
: base(_type, id, readLink, webSearchUrl)
{
TotalEstimatedMatches = totalEstimatedMatches;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets the estimated number of webpages that are relevant to the
/// query. Use this number along with the count and offset query
/// parameters to page the results.
/// </summary>
[JsonProperty(PropertyName = "totalEstimatedMatches")]
public long? TotalEstimatedMatches { get; private set; }
}
}

Просмотреть файл

@ -0,0 +1,96 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomImageSearch.Models
{
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Defines a thing.
/// </summary>
public partial class Thing : Response
{
/// <summary>
/// Initializes a new instance of the Thing class.
/// </summary>
public Thing()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the Thing class.
/// </summary>
/// <param name="id">A String identifier.</param>
/// <param name="readLink">The URL that returns this resource.</param>
/// <param name="webSearchUrl">The URL To Bing's search result for this
/// item.</param>
/// <param name="name">The name of the thing represented by this
/// object.</param>
/// <param name="url">The URL to get more information about the thing
/// represented by this object.</param>
/// <param name="image">An image of the item.</param>
/// <param name="description">A short description of the item.</param>
/// <param name="alternateName">An alias for the item</param>
/// <param name="bingId">An ID that uniquely identifies this
/// item.</param>
public Thing(string _type = default(string), string id = default(string), string readLink = default(string), string webSearchUrl = default(string), string name = default(string), string url = default(string), ImageObject image = default(ImageObject), string description = default(string), string alternateName = default(string), string bingId = default(string))
: base(_type, id, readLink, webSearchUrl)
{
Name = name;
Url = url;
Image = image;
Description = description;
AlternateName = alternateName;
BingId = bingId;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets the name of the thing represented by this object.
/// </summary>
[JsonProperty(PropertyName = "name")]
public string Name { get; private set; }
/// <summary>
/// Gets the URL to get more information about the thing represented by
/// this object.
/// </summary>
[JsonProperty(PropertyName = "url")]
public string Url { get; private set; }
/// <summary>
/// Gets an image of the item.
/// </summary>
[JsonProperty(PropertyName = "image")]
public ImageObject Image { get; private set; }
/// <summary>
/// Gets a short description of the item.
/// </summary>
[JsonProperty(PropertyName = "description")]
public string Description { get; private set; }
/// <summary>
/// Gets an alias for the item
/// </summary>
[JsonProperty(PropertyName = "alternateName")]
public string AlternateName { get; private set; }
/// <summary>
/// Gets an ID that uniquely identifies this item.
/// </summary>
[JsonProperty(PropertyName = "bingId")]
public string BingId { get; private set; }
}
}

Просмотреть файл

@ -0,0 +1,58 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomImageSearch.Models
{
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Defines a webpage that is relevant to the query.
/// </summary>
public partial class WebPage : CreativeWork
{
/// <summary>
/// Initializes a new instance of the WebPage class.
/// </summary>
public WebPage()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the WebPage class.
/// </summary>
/// <param name="id">A String identifier.</param>
/// <param name="readLink">The URL that returns this resource.</param>
/// <param name="webSearchUrl">The URL To Bing's search result for this
/// item.</param>
/// <param name="name">The name of the thing represented by this
/// object.</param>
/// <param name="url">The URL to get more information about the thing
/// represented by this object.</param>
/// <param name="image">An image of the item.</param>
/// <param name="description">A short description of the item.</param>
/// <param name="alternateName">An alias for the item</param>
/// <param name="bingId">An ID that uniquely identifies this
/// item.</param>
/// <param name="thumbnailUrl">The URL to a thumbnail of the
/// item.</param>
/// <param name="provider">The source of the creative work.</param>
/// <param name="text">Text content of this creative work</param>
public WebPage(string _type = default(string), string id = default(string), string readLink = default(string), string webSearchUrl = default(string), string name = default(string), string url = default(string), ImageObject image = default(ImageObject), string description = default(string), string alternateName = default(string), string bingId = default(string), string thumbnailUrl = default(string), IList<Thing> provider = default(IList<Thing>), string text = default(string))
: base(_type, id, readLink, webSearchUrl, name, url, image, description, alternateName, bingId, thumbnailUrl, provider, text)
{
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
}
}

Просмотреть файл

@ -0,0 +1,513 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomSearch
{
using Microsoft.Rest;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// CustomInstance operations.
/// </summary>
public partial class CustomInstance : IServiceOperations<CustomSearchClient>, ICustomInstance
{
/// <summary>
/// Initializes a new instance of the CustomInstance class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public CustomInstance(CustomSearchClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the CustomSearchClient
/// </summary>
public CustomSearchClient Client { get; private set; }
/// <summary>
/// The Custom Search API lets you send a search query to Bing and get back web
/// pages found in your custom view of the web.
/// </summary>
/// <param name='customConfig'>
/// The identifier for the custom search configuration
/// </param>
/// <param name='query'>
/// The user's search query term. The term may not be empty. The term may
/// contain Bing Advanced Operators. For example, to limit results to a
/// specific domain, use the site: operator.
/// </param>
/// <param name='acceptLanguage'>
/// A comma-delimited list of one or more languages to use for user interface
/// strings. The list is in decreasing order of preference. For additional
/// information, including expected format, see
/// [RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). This
/// header and the setLang query parameter are mutually exclusive; do not
/// specify both. If you set this header, you must also specify the cc query
/// parameter. Bing will use the first supported language it finds from the
/// list, and combine that language with the cc parameter value to determine
/// the market to return results for. If the list does not include a supported
/// language, Bing will find the closest language and market that supports the
/// request, and may use an aggregated or default market for the results
/// instead of a specified one. You should use this header and the cc query
/// parameter only if you specify multiple languages; otherwise, you should use
/// the mkt and setLang query parameters. A user interface string is a string
/// that's used as a label in a user interface. There are very few user
/// interface strings in the JSON response objects. Any links in the response
/// objects to Bing.com properties will apply the specified language.
/// </param>
/// <param name='userAgent'>
/// The user agent originating the request. Bing uses the user agent to provide
/// mobile users with an optimized experience. Although optional, you are
/// strongly encouraged to always specify this header. The user-agent should be
/// the same string that any commonly used browser would send. For information
/// about user agents, see [RFC
/// 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html).
/// </param>
/// <param name='clientId'>
/// Bing uses this header to provide users with consistent behavior across Bing
/// API calls. Bing often flights new features and improvements, and it uses
/// the client ID as a key for assigning traffic on different flights. If you
/// do not use the same client ID for a user across multiple requests, then
/// Bing may assign the user to multiple conflicting flights. Being assigned to
/// multiple conflicting flights can lead to an inconsistent user experience.
/// For example, if the second request has a different flight assignment than
/// the first, the experience may be unexpected. Also, Bing can use the client
/// ID to tailor web results to that client IDs search history, providing a
/// richer experience for the user. Bing also uses this header to help improve
/// result rankings by analyzing the activity generated by a client ID. The
/// relevance improvements help with better quality of results delivered by
/// Bing APIs and in turn enables higher click-through rates for the API
/// consumer. IMPORTANT: Although optional, you should consider this header
/// required. Persisting the client ID across multiple requests for the same
/// end user and device combination enables 1) the API consumer to receive a
/// consistent user experience, and 2) higher click-through rates via better
/// quality of results from the Bing APIs. Each user that uses your application
/// on the device must have a unique, Bing generated client ID. If you do not
/// include this header in the request, Bing generates an ID and returns it in
/// the X-MSEdge-ClientID response header. The only time that you should NOT
/// include this header in a request is the first time the user uses your app
/// on that device. Use the client ID for each Bing API request that your app
/// makes for this user on the device. Persist the client ID. To persist the ID
/// in a browser app, use a persistent HTTP cookie to ensure the ID is used
/// across all sessions. Do not use a session cookie. For other apps such as
/// mobile apps, use the device's persistent storage to persist the ID. The
/// next time the user uses your app on that device, get the client ID that you
/// persisted. Bing responses may or may not include this header. If the
/// response includes this header, capture the client ID and use it for all
/// subsequent Bing requests for the user on that device. If you include the
/// X-MSEdge-ClientID, you must not include cookies in the request.
/// </param>
/// <param name='clientIp'>
/// The IPv4 or IPv6 address of the client device. The IP address is used to
/// discover the user's location. Bing uses the location information to
/// determine safe search behavior. Although optional, you are encouraged to
/// always specify this header and the X-Search-Location header. Do not
/// obfuscate the address (for example, by changing the last octet to 0).
/// Obfuscating the address results in the location not being anywhere near the
/// device's actual location, which may result in Bing serving erroneous
/// results.
/// </param>
/// <param name='location'>
/// A semicolon-delimited list of key/value pairs that describe the client's
/// geographical location. Bing uses the location information to determine safe
/// search behavior and to return relevant local content. Specify the key/value
/// pair as &lt;key&gt;:&lt;value&gt;. The following are the keys that you use
/// to specify the user's location. lat (required): The latitude of the
/// client's location, in degrees. The latitude must be greater than or equal
/// to -90.0 and less than or equal to +90.0. Negative values indicate southern
/// latitudes and positive values indicate northern latitudes. long (required):
/// The longitude of the client's location, in degrees. The longitude must be
/// greater than or equal to -180.0 and less than or equal to +180.0. Negative
/// values indicate western longitudes and positive values indicate eastern
/// longitudes. re (required): The radius, in meters, which specifies the
/// horizontal accuracy of the coordinates. Pass the value returned by the
/// device's location service. Typical values might be 22m for GPS/Wi-Fi, 380m
/// for cell tower triangulation, and 18,000m for reverse IP lookup. ts
/// (optional): The UTC UNIX timestamp of when the client was at the location.
/// (The UNIX timestamp is the number of seconds since January 1, 1970.) head
/// (optional): The client's relative heading or direction of travel. Specify
/// the direction of travel as degrees from 0 through 360, counting clockwise
/// relative to true north. Specify this key only if the sp key is nonzero. sp
/// (optional): The horizontal velocity (speed), in meters per second, that the
/// client device is traveling. alt (optional): The altitude of the client
/// device, in meters. are (optional): The radius, in meters, that specifies
/// the vertical accuracy of the coordinates. Specify this key only if you
/// specify the alt key. Although many of the keys are optional, the more
/// information that you provide, the more accurate the location results are.
/// Although optional, you are encouraged to always specify the user's
/// geographical location. Providing the location is especially important if
/// the client's IP address does not accurately reflect the user's physical
/// location (for example, if the client uses VPN). For optimal results, you
/// should include this header and the X-MSEdge-ClientIP header, but at a
/// minimum, you should include this header.
/// </param>
/// <param name='countryCode'>
/// A 2-character country code of the country where the results come from. This
/// API supports only the United States market. If you specify this query
/// parameter, it must be set to us. If you set this parameter, you must also
/// specify the Accept-Language header. Bing uses the first supported language
/// it finds from the languages list, and combine that language with the
/// country code that you specify to determine the market to return results
/// for. If the languages list does not include a supported language, Bing
/// finds the closest language and market that supports the request, or it may
/// use an aggregated or default market for the results instead of a specified
/// one. You should use this query parameter and the Accept-Language query
/// parameter only if you specify multiple languages; otherwise, you should use
/// the mkt and setLang query parameters. This parameter and the mkt query
/// parameter are mutually exclusive—do not specify both.
/// </param>
/// <param name='count'>
/// The number of search results to return in the response. The default is 10
/// and the maximum value is 50. The actual number delivered may be less than
/// requested.Use this parameter along with the offset parameter to page
/// results.For example, if your user interface displays 10 search results per
/// page, set count to 10 and offset to 0 to get the first page of results. For
/// each subsequent page, increment offset by 10 (for example, 0, 10, 20). It
/// is possible for multiple pages to include some overlap in results.
/// </param>
/// <param name='market'>
/// The market where the results come from. Typically, mkt is the country where
/// the user is making the request from. However, it could be a different
/// country if the user is not located in a country where Bing delivers
/// results. The market must be in the form &lt;language code&gt;-&lt;country
/// code&gt;. For example, en-US. The string is case insensitive. If known, you
/// are encouraged to always specify the market. Specifying the market helps
/// Bing route the request and return an appropriate and optimal response. If
/// you specify a market that is not listed in Market Codes, Bing uses a best
/// fit market code based on an internal mapping that is subject to change.
/// This parameter and the cc query parameter are mutually exclusive—do not
/// specify both.
/// </param>
/// <param name='offset'>
/// The zero-based offset that indicates the number of search results to skip
/// before returning results. The default is 0. The offset should be less than
/// (totalEstimatedMatches - count). Use this parameter along with the count
/// parameter to page results. For example, if your user interface displays 10
/// search results per page, set count to 10 and offset to 0 to get the first
/// page of results. For each subsequent page, increment offset by 10 (for
/// example, 0, 10, 20). it is possible for multiple pages to include some
/// overlap in results.
/// </param>
/// <param name='safeSearch'>
/// A filter used to filter adult content. Off: Return webpages with adult
/// text, images, or videos. Moderate: Return webpages with adult text, but not
/// adult images or videos. Strict: Do not return webpages with adult text,
/// images, or videos. The default is Moderate. If the request comes from a
/// market that Bing's adult policy requires that safeSearch is set to Strict,
/// Bing ignores the safeSearch value and uses Strict. If you use the site:
/// query operator, there is the chance that the response may contain adult
/// content regardless of what the safeSearch query parameter is set to. Use
/// site: only if you are aware of the content on the site and your scenario
/// supports the possibility of adult content. Possible values include: 'Off',
/// 'Moderate', 'Strict'
/// </param>
/// <param name='setLang'>
/// The language to use for user interface strings. Specify the language using
/// the ISO 639-1 2-letter language code. For example, the language code for
/// English is EN. The default is EN (English). Although optional, you should
/// always specify the language. Typically, you set setLang to the same
/// language specified by mkt unless the user wants the user interface strings
/// displayed in a different language. This parameter and the Accept-Language
/// header are mutually exclusive; do not specify both. A user interface string
/// is a string that's used as a label in a user interface. There are few user
/// interface strings in the JSON response objects. Also, any links to Bing.com
/// properties in the response objects apply the specified language.
/// </param>
/// <param name='textDecorations'>
/// A Boolean value that determines whether display strings should contain
/// decoration markers such as hit highlighting characters. If true, the
/// strings may include markers. The default is false. To specify whether to
/// use Unicode characters or HTML tags as the markers, see the textFormat
/// query parameter.
/// </param>
/// <param name='textFormat'>
/// The type of markers to use for text decorations (see the textDecorations
/// query parameter). Possible values are Raw—Use Unicode characters to mark
/// content that needs special formatting. The Unicode characters are in the
/// range E000 through E019. For example, Bing uses E000 and E001 to mark the
/// beginning and end of query terms for hit highlighting. HTML—Use HTML tags
/// to mark content that needs special formatting. For example, use &lt;b&gt;
/// tags to highlight query terms in display strings. The default is Raw. For
/// display strings that contain escapable HTML characters such as &lt;, &gt;,
/// and &amp;, if textFormat is set to HTML, Bing escapes the characters as
/// appropriate (for example, &lt; is escaped to &amp;lt;). Possible values
/// include: 'Raw', 'Html'
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<SearchResponse>> SearchWithHttpMessagesAsync(string customConfig, string query, string acceptLanguage = default(string), string userAgent = default(string), string clientId = default(string), string clientIp = default(string), string location = default(string), string countryCode = default(string), int? count = default(int?), string market = "en-us", int? offset = default(int?), string safeSearch = default(string), string setLang = default(string), bool? textDecorations = default(bool?), string textFormat = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (customConfig == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "customConfig");
}
if (query == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "query");
}
string xBingApisSDK = "true";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("xBingApisSDK", xBingApisSDK);
tracingParameters.Add("acceptLanguage", acceptLanguage);
tracingParameters.Add("userAgent", userAgent);
tracingParameters.Add("clientId", clientId);
tracingParameters.Add("clientIp", clientIp);
tracingParameters.Add("location", location);
tracingParameters.Add("customConfig", customConfig);
tracingParameters.Add("countryCode", countryCode);
tracingParameters.Add("count", count);
tracingParameters.Add("market", market);
tracingParameters.Add("offset", offset);
tracingParameters.Add("query", query);
tracingParameters.Add("safeSearch", safeSearch);
tracingParameters.Add("setLang", setLang);
tracingParameters.Add("textDecorations", textDecorations);
tracingParameters.Add("textFormat", textFormat);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Search", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "search").ToString();
List<string> _queryParameters = new List<string>();
if (customConfig != null)
{
_queryParameters.Add(string.Format("customConfig={0}", System.Uri.EscapeDataString(customConfig)));
}
if (countryCode != null)
{
_queryParameters.Add(string.Format("cc={0}", System.Uri.EscapeDataString(countryCode)));
}
if (count != null)
{
_queryParameters.Add(string.Format("count={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(count, Client.SerializationSettings).Trim('"'))));
}
if (market != null)
{
_queryParameters.Add(string.Format("mkt={0}", System.Uri.EscapeDataString(market)));
}
if (offset != null)
{
_queryParameters.Add(string.Format("offset={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(offset, Client.SerializationSettings).Trim('"'))));
}
if (query != null)
{
_queryParameters.Add(string.Format("q={0}", System.Uri.EscapeDataString(query)));
}
if (safeSearch != null)
{
_queryParameters.Add(string.Format("safeSearch={0}", System.Uri.EscapeDataString(safeSearch)));
}
if (setLang != null)
{
_queryParameters.Add(string.Format("setLang={0}", System.Uri.EscapeDataString(setLang)));
}
if (textDecorations != null)
{
_queryParameters.Add(string.Format("textDecorations={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(textDecorations, Client.SerializationSettings).Trim('"'))));
}
if (textFormat != null)
{
_queryParameters.Add(string.Format("textFormat={0}", System.Uri.EscapeDataString(textFormat)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (xBingApisSDK != null)
{
if (_httpRequest.Headers.Contains("X-BingApis-SDK"))
{
_httpRequest.Headers.Remove("X-BingApis-SDK");
}
_httpRequest.Headers.TryAddWithoutValidation("X-BingApis-SDK", xBingApisSDK);
}
if (acceptLanguage != null)
{
if (_httpRequest.Headers.Contains("Accept-Language"))
{
_httpRequest.Headers.Remove("Accept-Language");
}
_httpRequest.Headers.TryAddWithoutValidation("Accept-Language", acceptLanguage);
}
if (userAgent != null)
{
if (_httpRequest.Headers.Contains("User-Agent"))
{
_httpRequest.Headers.Remove("User-Agent");
}
_httpRequest.Headers.TryAddWithoutValidation("User-Agent", userAgent);
}
if (clientId != null)
{
if (_httpRequest.Headers.Contains("X-MSEdge-ClientID"))
{
_httpRequest.Headers.Remove("X-MSEdge-ClientID");
}
_httpRequest.Headers.TryAddWithoutValidation("X-MSEdge-ClientID", clientId);
}
if (clientIp != null)
{
if (_httpRequest.Headers.Contains("X-MSEdge-ClientIP"))
{
_httpRequest.Headers.Remove("X-MSEdge-ClientIP");
}
_httpRequest.Headers.TryAddWithoutValidation("X-MSEdge-ClientIP", clientIp);
}
if (location != null)
{
if (_httpRequest.Headers.Contains("X-Search-Location"))
{
_httpRequest.Headers.Remove("X-Search-Location");
}
_httpRequest.Headers.TryAddWithoutValidation("X-Search-Location", location);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<SearchResponse>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<SearchResponse>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}

Просмотреть файл

@ -0,0 +1,242 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomSearch
{
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for CustomInstance.
/// </summary>
public static partial class CustomInstanceExtensions
{
/// <summary>
/// The Custom Search API lets you send a search query to Bing and get back web
/// pages found in your custom view of the web.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='customConfig'>
/// The identifier for the custom search configuration
/// </param>
/// <param name='query'>
/// The user's search query term. The term may not be empty. The term may
/// contain Bing Advanced Operators. For example, to limit results to a
/// specific domain, use the site: operator.
/// </param>
/// <param name='acceptLanguage'>
/// A comma-delimited list of one or more languages to use for user interface
/// strings. The list is in decreasing order of preference. For additional
/// information, including expected format, see
/// [RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). This
/// header and the setLang query parameter are mutually exclusive; do not
/// specify both. If you set this header, you must also specify the cc query
/// parameter. Bing will use the first supported language it finds from the
/// list, and combine that language with the cc parameter value to determine
/// the market to return results for. If the list does not include a supported
/// language, Bing will find the closest language and market that supports the
/// request, and may use an aggregated or default market for the results
/// instead of a specified one. You should use this header and the cc query
/// parameter only if you specify multiple languages; otherwise, you should use
/// the mkt and setLang query parameters. A user interface string is a string
/// that's used as a label in a user interface. There are very few user
/// interface strings in the JSON response objects. Any links in the response
/// objects to Bing.com properties will apply the specified language.
/// </param>
/// <param name='userAgent'>
/// The user agent originating the request. Bing uses the user agent to provide
/// mobile users with an optimized experience. Although optional, you are
/// strongly encouraged to always specify this header. The user-agent should be
/// the same string that any commonly used browser would send. For information
/// about user agents, see [RFC
/// 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html).
/// </param>
/// <param name='clientId'>
/// Bing uses this header to provide users with consistent behavior across Bing
/// API calls. Bing often flights new features and improvements, and it uses
/// the client ID as a key for assigning traffic on different flights. If you
/// do not use the same client ID for a user across multiple requests, then
/// Bing may assign the user to multiple conflicting flights. Being assigned to
/// multiple conflicting flights can lead to an inconsistent user experience.
/// For example, if the second request has a different flight assignment than
/// the first, the experience may be unexpected. Also, Bing can use the client
/// ID to tailor web results to that client IDs search history, providing a
/// richer experience for the user. Bing also uses this header to help improve
/// result rankings by analyzing the activity generated by a client ID. The
/// relevance improvements help with better quality of results delivered by
/// Bing APIs and in turn enables higher click-through rates for the API
/// consumer. IMPORTANT: Although optional, you should consider this header
/// required. Persisting the client ID across multiple requests for the same
/// end user and device combination enables 1) the API consumer to receive a
/// consistent user experience, and 2) higher click-through rates via better
/// quality of results from the Bing APIs. Each user that uses your application
/// on the device must have a unique, Bing generated client ID. If you do not
/// include this header in the request, Bing generates an ID and returns it in
/// the X-MSEdge-ClientID response header. The only time that you should NOT
/// include this header in a request is the first time the user uses your app
/// on that device. Use the client ID for each Bing API request that your app
/// makes for this user on the device. Persist the client ID. To persist the ID
/// in a browser app, use a persistent HTTP cookie to ensure the ID is used
/// across all sessions. Do not use a session cookie. For other apps such as
/// mobile apps, use the device's persistent storage to persist the ID. The
/// next time the user uses your app on that device, get the client ID that you
/// persisted. Bing responses may or may not include this header. If the
/// response includes this header, capture the client ID and use it for all
/// subsequent Bing requests for the user on that device. If you include the
/// X-MSEdge-ClientID, you must not include cookies in the request.
/// </param>
/// <param name='clientIp'>
/// The IPv4 or IPv6 address of the client device. The IP address is used to
/// discover the user's location. Bing uses the location information to
/// determine safe search behavior. Although optional, you are encouraged to
/// always specify this header and the X-Search-Location header. Do not
/// obfuscate the address (for example, by changing the last octet to 0).
/// Obfuscating the address results in the location not being anywhere near the
/// device's actual location, which may result in Bing serving erroneous
/// results.
/// </param>
/// <param name='location'>
/// A semicolon-delimited list of key/value pairs that describe the client's
/// geographical location. Bing uses the location information to determine safe
/// search behavior and to return relevant local content. Specify the key/value
/// pair as &lt;key&gt;:&lt;value&gt;. The following are the keys that you use
/// to specify the user's location. lat (required): The latitude of the
/// client's location, in degrees. The latitude must be greater than or equal
/// to -90.0 and less than or equal to +90.0. Negative values indicate southern
/// latitudes and positive values indicate northern latitudes. long (required):
/// The longitude of the client's location, in degrees. The longitude must be
/// greater than or equal to -180.0 and less than or equal to +180.0. Negative
/// values indicate western longitudes and positive values indicate eastern
/// longitudes. re (required): The radius, in meters, which specifies the
/// horizontal accuracy of the coordinates. Pass the value returned by the
/// device's location service. Typical values might be 22m for GPS/Wi-Fi, 380m
/// for cell tower triangulation, and 18,000m for reverse IP lookup. ts
/// (optional): The UTC UNIX timestamp of when the client was at the location.
/// (The UNIX timestamp is the number of seconds since January 1, 1970.) head
/// (optional): The client's relative heading or direction of travel. Specify
/// the direction of travel as degrees from 0 through 360, counting clockwise
/// relative to true north. Specify this key only if the sp key is nonzero. sp
/// (optional): The horizontal velocity (speed), in meters per second, that the
/// client device is traveling. alt (optional): The altitude of the client
/// device, in meters. are (optional): The radius, in meters, that specifies
/// the vertical accuracy of the coordinates. Specify this key only if you
/// specify the alt key. Although many of the keys are optional, the more
/// information that you provide, the more accurate the location results are.
/// Although optional, you are encouraged to always specify the user's
/// geographical location. Providing the location is especially important if
/// the client's IP address does not accurately reflect the user's physical
/// location (for example, if the client uses VPN). For optimal results, you
/// should include this header and the X-MSEdge-ClientIP header, but at a
/// minimum, you should include this header.
/// </param>
/// <param name='countryCode'>
/// A 2-character country code of the country where the results come from. This
/// API supports only the United States market. If you specify this query
/// parameter, it must be set to us. If you set this parameter, you must also
/// specify the Accept-Language header. Bing uses the first supported language
/// it finds from the languages list, and combine that language with the
/// country code that you specify to determine the market to return results
/// for. If the languages list does not include a supported language, Bing
/// finds the closest language and market that supports the request, or it may
/// use an aggregated or default market for the results instead of a specified
/// one. You should use this query parameter and the Accept-Language query
/// parameter only if you specify multiple languages; otherwise, you should use
/// the mkt and setLang query parameters. This parameter and the mkt query
/// parameter are mutually exclusive—do not specify both.
/// </param>
/// <param name='count'>
/// The number of search results to return in the response. The default is 10
/// and the maximum value is 50. The actual number delivered may be less than
/// requested.Use this parameter along with the offset parameter to page
/// results.For example, if your user interface displays 10 search results per
/// page, set count to 10 and offset to 0 to get the first page of results. For
/// each subsequent page, increment offset by 10 (for example, 0, 10, 20). It
/// is possible for multiple pages to include some overlap in results.
/// </param>
/// <param name='market'>
/// The market where the results come from. Typically, mkt is the country where
/// the user is making the request from. However, it could be a different
/// country if the user is not located in a country where Bing delivers
/// results. The market must be in the form &lt;language code&gt;-&lt;country
/// code&gt;. For example, en-US. The string is case insensitive. If known, you
/// are encouraged to always specify the market. Specifying the market helps
/// Bing route the request and return an appropriate and optimal response. If
/// you specify a market that is not listed in Market Codes, Bing uses a best
/// fit market code based on an internal mapping that is subject to change.
/// This parameter and the cc query parameter are mutually exclusive—do not
/// specify both.
/// </param>
/// <param name='offset'>
/// The zero-based offset that indicates the number of search results to skip
/// before returning results. The default is 0. The offset should be less than
/// (totalEstimatedMatches - count). Use this parameter along with the count
/// parameter to page results. For example, if your user interface displays 10
/// search results per page, set count to 10 and offset to 0 to get the first
/// page of results. For each subsequent page, increment offset by 10 (for
/// example, 0, 10, 20). it is possible for multiple pages to include some
/// overlap in results.
/// </param>
/// <param name='safeSearch'>
/// A filter used to filter adult content. Off: Return webpages with adult
/// text, images, or videos. Moderate: Return webpages with adult text, but not
/// adult images or videos. Strict: Do not return webpages with adult text,
/// images, or videos. The default is Moderate. If the request comes from a
/// market that Bing's adult policy requires that safeSearch is set to Strict,
/// Bing ignores the safeSearch value and uses Strict. If you use the site:
/// query operator, there is the chance that the response may contain adult
/// content regardless of what the safeSearch query parameter is set to. Use
/// site: only if you are aware of the content on the site and your scenario
/// supports the possibility of adult content. Possible values include: 'Off',
/// 'Moderate', 'Strict'
/// </param>
/// <param name='setLang'>
/// The language to use for user interface strings. Specify the language using
/// the ISO 639-1 2-letter language code. For example, the language code for
/// English is EN. The default is EN (English). Although optional, you should
/// always specify the language. Typically, you set setLang to the same
/// language specified by mkt unless the user wants the user interface strings
/// displayed in a different language. This parameter and the Accept-Language
/// header are mutually exclusive; do not specify both. A user interface string
/// is a string that's used as a label in a user interface. There are few user
/// interface strings in the JSON response objects. Also, any links to Bing.com
/// properties in the response objects apply the specified language.
/// </param>
/// <param name='textDecorations'>
/// A Boolean value that determines whether display strings should contain
/// decoration markers such as hit highlighting characters. If true, the
/// strings may include markers. The default is false. To specify whether to
/// use Unicode characters or HTML tags as the markers, see the textFormat
/// query parameter.
/// </param>
/// <param name='textFormat'>
/// The type of markers to use for text decorations (see the textDecorations
/// query parameter). Possible values are Raw—Use Unicode characters to mark
/// content that needs special formatting. The Unicode characters are in the
/// range E000 through E019. For example, Bing uses E000 and E001 to mark the
/// beginning and end of query terms for hit highlighting. HTML—Use HTML tags
/// to mark content that needs special formatting. For example, use &lt;b&gt;
/// tags to highlight query terms in display strings. The default is Raw. For
/// display strings that contain escapable HTML characters such as &lt;, &gt;,
/// and &amp;, if textFormat is set to HTML, Bing escapes the characters as
/// appropriate (for example, &lt; is escaped to &amp;lt;). Possible values
/// include: 'Raw', 'Html'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<SearchResponse> SearchAsync(this ICustomInstance operations, string customConfig, string query, string acceptLanguage = default(string), string userAgent = default(string), string clientId = default(string), string clientIp = default(string), string location = default(string), string countryCode = default(string), int? count = default(int?), string market = "en-us", int? offset = default(int?), string safeSearch = default(string), string setLang = default(string), bool? textDecorations = default(bool?), string textFormat = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.SearchWithHttpMessagesAsync(customConfig, query, acceptLanguage, userAgent, clientId, clientIp, location, countryCode, count, market, offset, safeSearch, setLang, textDecorations, textFormat, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}

Просмотреть файл

@ -0,0 +1,322 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomSearch
{
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
/// <summary>
/// The Bing Custom Search API lets you send a search query to Bing and get
/// back search results customized to meet your custom search definition.
/// </summary>
public partial class CustomSearchClient : ServiceClient<CustomSearchClient>, ICustomSearchClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Subscription credentials which uniquely identify client subscription.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Gets the ICustomInstance.
/// </summary>
public virtual ICustomInstance CustomInstance { get; private set; }
/// <summary>
/// Initializes a new instance of the CustomSearchClient class.
/// </summary>
/// <param name='httpClient'>
/// HttpClient to be used
/// </param>
/// <param name='disposeHttpClient'>
/// True: will dispose the provided httpClient on calling CustomSearchClient.Dispose(). False: will not dispose provided httpClient</param>
protected CustomSearchClient(HttpClient httpClient, bool disposeHttpClient) : base(httpClient, disposeHttpClient)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the CustomSearchClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected CustomSearchClient(params DelegatingHandler[] handlers) : base(handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the CustomSearchClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected CustomSearchClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the CustomSearchClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected CustomSearchClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the CustomSearchClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected CustomSearchClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the CustomSearchClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Subscription credentials which uniquely identify client subscription.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public CustomSearchClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the CustomSearchClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Subscription credentials which uniquely identify client subscription.
/// </param>
/// <param name='httpClient'>
/// HttpClient to be used
/// </param>
/// <param name='disposeHttpClient'>
/// True: will dispose the provided httpClient on calling CustomSearchClient.Dispose(). False: will not dispose provided httpClient</param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public CustomSearchClient(ServiceClientCredentials credentials, HttpClient httpClient, bool disposeHttpClient) : this(httpClient, disposeHttpClient)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the CustomSearchClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Subscription credentials which uniquely identify client subscription.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public CustomSearchClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the CustomSearchClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Subscription credentials which uniquely identify client subscription.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public CustomSearchClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the CustomSearchClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Subscription credentials which uniquely identify client subscription.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public CustomSearchClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
///</summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
CustomInstance = new CustomInstance(this);
BaseUri = new System.Uri("https://api.bing.microsoft.com/v7.0/custom");
SerializationSettings = new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<ResponseBase>("_type"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<ResponseBase>("_type"));
CustomInitialize();
}
}
}

Просмотреть файл

@ -0,0 +1,267 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomSearch
{
using Microsoft.Rest;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// CustomInstance operations.
/// </summary>
public partial interface ICustomInstance
{
/// <summary>
/// The Custom Search API lets you send a search query to Bing and get
/// back web pages found in your custom view of the web.
/// </summary>
/// <param name='customConfig'>
/// The identifier for the custom search configuration
/// </param>
/// <param name='query'>
/// The user's search query term. The term may not be empty. The term
/// may contain Bing Advanced Operators. For example, to limit results
/// to a specific domain, use the site: operator.
/// </param>
/// <param name='acceptLanguage'>
/// A comma-delimited list of one or more languages to use for user
/// interface strings. The list is in decreasing order of preference.
/// For additional information, including expected format, see
/// [RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html).
/// This header and the setLang query parameter are mutually exclusive;
/// do not specify both. If you set this header, you must also specify
/// the cc query parameter. Bing will use the first supported language
/// it finds from the list, and combine that language with the cc
/// parameter value to determine the market to return results for. If
/// the list does not include a supported language, Bing will find the
/// closest language and market that supports the request, and may use
/// an aggregated or default market for the results instead of a
/// specified one. You should use this header and the cc query
/// parameter only if you specify multiple languages; otherwise, you
/// should use the mkt and setLang query parameters. A user interface
/// string is a string that's used as a label in a user interface.
/// There are very few user interface strings in the JSON response
/// objects. Any links in the response objects to Bing.com properties
/// will apply the specified language.
/// </param>
/// <param name='userAgent'>
/// The user agent originating the request. Bing uses the user agent to
/// provide mobile users with an optimized experience. Although
/// optional, you are strongly encouraged to always specify this
/// header. The user-agent should be the same string that any commonly
/// used browser would send. For information about user agents, see
/// [RFC 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html).
/// </param>
/// <param name='clientId'>
/// Bing uses this header to provide users with consistent behavior
/// across Bing API calls. Bing often flights new features and
/// improvements, and it uses the client ID as a key for assigning
/// traffic on different flights. If you do not use the same client ID
/// for a user across multiple requests, then Bing may assign the user
/// to multiple conflicting flights. Being assigned to multiple
/// conflicting flights can lead to an inconsistent user experience.
/// For example, if the second request has a different flight
/// assignment than the first, the experience may be unexpected. Also,
/// Bing can use the client ID to tailor web results to that client
/// IDs search history, providing a richer experience for the user.
/// Bing also uses this header to help improve result rankings by
/// analyzing the activity generated by a client ID. The relevance
/// improvements help with better quality of results delivered by Bing
/// APIs and in turn enables higher click-through rates for the API
/// consumer. IMPORTANT: Although optional, you should consider this
/// header required. Persisting the client ID across multiple requests
/// for the same end user and device combination enables 1) the API
/// consumer to receive a consistent user experience, and 2) higher
/// click-through rates via better quality of results from the Bing
/// APIs. Each user that uses your application on the device must have
/// a unique, Bing generated client ID. If you do not include this
/// header in the request, Bing generates an ID and returns it in the
/// X-MSEdge-ClientID response header. The only time that you should
/// NOT include this header in a request is the first time the user
/// uses your app on that device. Use the client ID for each Bing API
/// request that your app makes for this user on the device. Persist
/// the client ID. To persist the ID in a browser app, use a persistent
/// HTTP cookie to ensure the ID is used across all sessions. Do not
/// use a session cookie. For other apps such as mobile apps, use the
/// device's persistent storage to persist the ID. The next time the
/// user uses your app on that device, get the client ID that you
/// persisted. Bing responses may or may not include this header. If
/// the response includes this header, capture the client ID and use it
/// for all subsequent Bing requests for the user on that device. If
/// you include the X-MSEdge-ClientID, you must not include cookies in
/// the request.
/// </param>
/// <param name='clientIp'>
/// The IPv4 or IPv6 address of the client device. The IP address is
/// used to discover the user's location. Bing uses the location
/// information to determine safe search behavior. Although optional,
/// you are encouraged to always specify this header and the
/// X-Search-Location header. Do not obfuscate the address (for
/// example, by changing the last octet to 0). Obfuscating the address
/// results in the location not being anywhere near the device's actual
/// location, which may result in Bing serving erroneous results.
/// </param>
/// <param name='location'>
/// A semicolon-delimited list of key/value pairs that describe the
/// client's geographical location. Bing uses the location information
/// to determine safe search behavior and to return relevant local
/// content. Specify the key/value pair as &lt;key&gt;:&lt;value&gt;.
/// The following are the keys that you use to specify the user's
/// location. lat (required): The latitude of the client's location, in
/// degrees. The latitude must be greater than or equal to -90.0 and
/// less than or equal to +90.0. Negative values indicate southern
/// latitudes and positive values indicate northern latitudes. long
/// (required): The longitude of the client's location, in degrees. The
/// longitude must be greater than or equal to -180.0 and less than or
/// equal to +180.0. Negative values indicate western longitudes and
/// positive values indicate eastern longitudes. re (required): The
/// radius, in meters, which specifies the horizontal accuracy of the
/// coordinates. Pass the value returned by the device's location
/// service. Typical values might be 22m for GPS/Wi-Fi, 380m for cell
/// tower triangulation, and 18,000m for reverse IP lookup. ts
/// (optional): The UTC UNIX timestamp of when the client was at the
/// location. (The UNIX timestamp is the number of seconds since
/// January 1, 1970.) head (optional): The client's relative heading or
/// direction of travel. Specify the direction of travel as degrees
/// from 0 through 360, counting clockwise relative to true north.
/// Specify this key only if the sp key is nonzero. sp (optional): The
/// horizontal velocity (speed), in meters per second, that the client
/// device is traveling. alt (optional): The altitude of the client
/// device, in meters. are (optional): The radius, in meters, that
/// specifies the vertical accuracy of the coordinates. Specify this
/// key only if you specify the alt key. Although many of the keys are
/// optional, the more information that you provide, the more accurate
/// the location results are. Although optional, you are encouraged to
/// always specify the user's geographical location. Providing the
/// location is especially important if the client's IP address does
/// not accurately reflect the user's physical location (for example,
/// if the client uses VPN). For optimal results, you should include
/// this header and the X-MSEdge-ClientIP header, but at a minimum, you
/// should include this header.
/// </param>
/// <param name='countryCode'>
/// A 2-character country code of the country where the results come
/// from. This API supports only the United States market. If you
/// specify this query parameter, it must be set to us. If you set this
/// parameter, you must also specify the Accept-Language header. Bing
/// uses the first supported language it finds from the languages list,
/// and combine that language with the country code that you specify to
/// determine the market to return results for. If the languages list
/// does not include a supported language, Bing finds the closest
/// language and market that supports the request, or it may use an
/// aggregated or default market for the results instead of a specified
/// one. You should use this query parameter and the Accept-Language
/// query parameter only if you specify multiple languages; otherwise,
/// you should use the mkt and setLang query parameters. This parameter
/// and the mkt query parameter are mutually exclusive—do not specify
/// both.
/// </param>
/// <param name='count'>
/// The number of search results to return in the response. The default
/// is 10 and the maximum value is 50. The actual number delivered may
/// be less than requested.Use this parameter along with the offset
/// parameter to page results.For example, if your user interface
/// displays 10 search results per page, set count to 10 and offset to
/// 0 to get the first page of results. For each subsequent page,
/// increment offset by 10 (for example, 0, 10, 20). It is possible for
/// multiple pages to include some overlap in results.
/// </param>
/// <param name='market'>
/// The market where the results come from. Typically, mkt is the
/// country where the user is making the request from. However, it
/// could be a different country if the user is not located in a
/// country where Bing delivers results. The market must be in the form
/// &lt;language code&gt;-&lt;country code&gt;. For example, en-US. The
/// string is case insensitive. If known, you are encouraged to always
/// specify the market. Specifying the market helps Bing route the
/// request and return an appropriate and optimal response. If you
/// specify a market that is not listed in Market Codes, Bing uses a
/// best fit market code based on an internal mapping that is subject
/// to change. This parameter and the cc query parameter are mutually
/// exclusive—do not specify both.
/// </param>
/// <param name='offset'>
/// The zero-based offset that indicates the number of search results
/// to skip before returning results. The default is 0. The offset
/// should be less than (totalEstimatedMatches - count). Use this
/// parameter along with the count parameter to page results. For
/// example, if your user interface displays 10 search results per
/// page, set count to 10 and offset to 0 to get the first page of
/// results. For each subsequent page, increment offset by 10 (for
/// example, 0, 10, 20). it is possible for multiple pages to include
/// some overlap in results.
/// </param>
/// <param name='safeSearch'>
/// A filter used to filter adult content. Off: Return webpages with
/// adult text, images, or videos. Moderate: Return webpages with adult
/// text, but not adult images or videos. Strict: Do not return
/// webpages with adult text, images, or videos. The default is
/// Moderate. If the request comes from a market that Bing's adult
/// policy requires that safeSearch is set to Strict, Bing ignores the
/// safeSearch value and uses Strict. If you use the site: query
/// operator, there is the chance that the response may contain adult
/// content regardless of what the safeSearch query parameter is set
/// to. Use site: only if you are aware of the content on the site and
/// your scenario supports the possibility of adult content. Possible
/// values include: 'Off', 'Moderate', 'Strict'
/// </param>
/// <param name='setLang'>
/// The language to use for user interface strings. Specify the
/// language using the ISO 639-1 2-letter language code. For example,
/// the language code for English is EN. The default is EN (English).
/// Although optional, you should always specify the language.
/// Typically, you set setLang to the same language specified by mkt
/// unless the user wants the user interface strings displayed in a
/// different language. This parameter and the Accept-Language header
/// are mutually exclusive; do not specify both. A user interface
/// string is a string that's used as a label in a user interface.
/// There are few user interface strings in the JSON response objects.
/// Also, any links to Bing.com properties in the response objects
/// apply the specified language.
/// </param>
/// <param name='textDecorations'>
/// A Boolean value that determines whether display strings should
/// contain decoration markers such as hit highlighting characters. If
/// true, the strings may include markers. The default is false. To
/// specify whether to use Unicode characters or HTML tags as the
/// markers, see the textFormat query parameter.
/// </param>
/// <param name='textFormat'>
/// The type of markers to use for text decorations (see the
/// textDecorations query parameter). Possible values are Raw—Use
/// Unicode characters to mark content that needs special formatting.
/// The Unicode characters are in the range E000 through E019. For
/// example, Bing uses E000 and E001 to mark the beginning and end of
/// query terms for hit highlighting. HTML—Use HTML tags to mark
/// content that needs special formatting. For example, use &lt;b&gt;
/// tags to highlight query terms in display strings. The default is
/// Raw. For display strings that contain escapable HTML characters
/// such as &lt;, &gt;, and &amp;, if textFormat is set to HTML, Bing
/// escapes the characters as appropriate (for example, &lt; is escaped
/// to &amp;lt;). Possible values include: 'Raw', 'Html'
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse<SearchResponse>> SearchWithHttpMessagesAsync(string customConfig, string query, string acceptLanguage = default(string), string userAgent = default(string), string clientId = default(string), string clientIp = default(string), string location = default(string), string countryCode = default(string), int? count = default(int?), string market = "en-us", int? offset = default(int?), string safeSearch = default(string), string setLang = default(string), bool? textDecorations = default(bool?), string textFormat = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}

Просмотреть файл

@ -0,0 +1,47 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomSearch
{
using Microsoft.Rest;
using Models;
using Newtonsoft.Json;
/// <summary>
/// The Bing Custom Search API lets you send a search query to Bing and get
/// back search results customized to meet your custom search definition.
/// </summary>
public partial interface ICustomSearchClient : System.IDisposable
{
/// <summary>
/// The base URI of the service.
/// </summary>
System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
JsonSerializerSettings SerializationSettings { get; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
JsonSerializerSettings DeserializationSettings { get; }
/// <summary>
/// Subscription credentials which uniquely identify client
/// subscription.
/// </summary>
ServiceClientCredentials Credentials { get; }
/// <summary>
/// Gets the ICustomInstance.
/// </summary>
ICustomInstance CustomInstance { get; }
}
}

Просмотреть файл

@ -0,0 +1,49 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomSearch.Models
{
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
[Newtonsoft.Json.JsonObject("Answer")]
public partial class Answer : Response
{
/// <summary>
/// Initializes a new instance of the Answer class.
/// </summary>
public Answer()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the Answer class.
/// </summary>
/// <param name="id">A String identifier.</param>
/// <param name="webSearchUrl">The URL To Bing's search result for this
/// item.</param>
public Answer(string id = default(string), string webSearchUrl = default(string), IList<Query> followUpQueries = default(IList<Query>))
: base(id, webSearchUrl)
{
FollowUpQueries = followUpQueries;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "followUpQueries")]
public IList<Query> FollowUpQueries { get; private set; }
}
}

Просмотреть файл

@ -0,0 +1,73 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomSearch.Models
{
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
[Newtonsoft.Json.JsonObject("CreativeWork")]
public partial class CreativeWork : Thing
{
/// <summary>
/// Initializes a new instance of the CreativeWork class.
/// </summary>
public CreativeWork()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the CreativeWork class.
/// </summary>
/// <param name="id">A String identifier.</param>
/// <param name="webSearchUrl">The URL To Bing's search result for this
/// item.</param>
/// <param name="name">The name of the thing represented by this
/// object.</param>
/// <param name="url">The URL to get more information about the thing
/// represented by this object.</param>
/// <param name="description">A short description of the item.</param>
/// <param name="bingId">An ID that uniquely identifies this
/// item.</param>
/// <param name="thumbnailUrl">The URL to a thumbnail of the
/// item.</param>
/// <param name="provider">The source of the creative work.</param>
public CreativeWork(string id = default(string), string webSearchUrl = default(string), string name = default(string), string url = default(string), string description = default(string), string bingId = default(string), string thumbnailUrl = default(string), IList<Thing> provider = default(IList<Thing>), string text = default(string))
: base(id, webSearchUrl, name, url, description, bingId)
{
ThumbnailUrl = thumbnailUrl;
Provider = provider;
Text = text;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets the URL to a thumbnail of the item.
/// </summary>
[JsonProperty(PropertyName = "thumbnailUrl")]
public string ThumbnailUrl { get; private set; }
/// <summary>
/// Gets the source of the creative work.
/// </summary>
[JsonProperty(PropertyName = "provider")]
public IList<Thing> Provider { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "text")]
public string Text { get; private set; }
}
}

Просмотреть файл

@ -0,0 +1,125 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomSearch.Models
{
using Microsoft.Rest;
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Defines the error that occurred.
/// </summary>
public partial class Error
{
/// <summary>
/// Initializes a new instance of the Error class.
/// </summary>
public Error()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the Error class.
/// </summary>
/// <param name="code">The error code that identifies the category of
/// error. Possible values include: 'None', 'ServerError',
/// 'InvalidRequest', 'RateLimitExceeded', 'InvalidAuthorization',
/// 'InsufficientAuthorization'</param>
/// <param name="message">A description of the error.</param>
/// <param name="subCode">The error code that further helps to identify
/// the error. Possible values include: 'UnexpectedError',
/// 'ResourceError', 'NotImplemented', 'ParameterMissing',
/// 'ParameterInvalidValue', 'HttpNotAllowed', 'Blocked',
/// 'AuthorizationMissing', 'AuthorizationRedundancy',
/// 'AuthorizationDisabled', 'AuthorizationExpired'</param>
/// <param name="moreDetails">A description that provides additional
/// information about the error.</param>
/// <param name="parameter">The parameter in the request that caused
/// the error.</param>
/// <param name="value">The parameter's value in the request that was
/// not valid.</param>
public Error(string code, string message, string subCode = default(string), string moreDetails = default(string), string parameter = default(string), string value = default(string))
{
Code = code;
SubCode = subCode;
Message = message;
MoreDetails = moreDetails;
Parameter = parameter;
Value = value;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets the error code that identifies the category of error.
/// Possible values include: 'None', 'ServerError', 'InvalidRequest',
/// 'RateLimitExceeded', 'InvalidAuthorization',
/// 'InsufficientAuthorization'
/// </summary>
[JsonProperty(PropertyName = "code")]
public string Code { get; set; }
/// <summary>
/// Gets the error code that further helps to identify the error.
/// Possible values include: 'UnexpectedError', 'ResourceError',
/// 'NotImplemented', 'ParameterMissing', 'ParameterInvalidValue',
/// 'HttpNotAllowed', 'Blocked', 'AuthorizationMissing',
/// 'AuthorizationRedundancy', 'AuthorizationDisabled',
/// 'AuthorizationExpired'
/// </summary>
[JsonProperty(PropertyName = "subCode")]
public string SubCode { get; private set; }
/// <summary>
/// Gets or sets a description of the error.
/// </summary>
[JsonProperty(PropertyName = "message")]
public string Message { get; set; }
/// <summary>
/// Gets a description that provides additional information about the
/// error.
/// </summary>
[JsonProperty(PropertyName = "moreDetails")]
public string MoreDetails { get; private set; }
/// <summary>
/// Gets the parameter in the request that caused the error.
/// </summary>
[JsonProperty(PropertyName = "parameter")]
public string Parameter { get; private set; }
/// <summary>
/// Gets the parameter's value in the request that was not valid.
/// </summary>
[JsonProperty(PropertyName = "value")]
public string Value { get; private set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (Code == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Code");
}
if (Message == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Message");
}
}
}
}

Просмотреть файл

@ -0,0 +1,22 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomSearch.Models
{
/// <summary>
/// Defines values for ErrorCode.
/// </summary>
public static class ErrorCode
{
public const string None = "None";
public const string ServerError = "ServerError";
public const string InvalidRequest = "InvalidRequest";
public const string RateLimitExceeded = "RateLimitExceeded";
public const string InvalidAuthorization = "InvalidAuthorization";
public const string InsufficientAuthorization = "InsufficientAuthorization";
}
}

Просмотреть файл

@ -0,0 +1,80 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomSearch.Models
{
using Microsoft.Rest;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// The top-level response that represents a failed request.
/// </summary>
[Newtonsoft.Json.JsonObject("ErrorResponse")]
public partial class ErrorResponse : Response
{
/// <summary>
/// Initializes a new instance of the ErrorResponse class.
/// </summary>
public ErrorResponse()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the ErrorResponse class.
/// </summary>
/// <param name="errors">A list of errors that describe the reasons why
/// the request failed.</param>
/// <param name="id">A String identifier.</param>
/// <param name="webSearchUrl">The URL To Bing's search result for this
/// item.</param>
public ErrorResponse(IList<Error> errors, string id = default(string), string webSearchUrl = default(string))
: base(id, webSearchUrl)
{
Errors = errors;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets a list of errors that describe the reasons why the
/// request failed.
/// </summary>
[JsonProperty(PropertyName = "errors")]
public IList<Error> Errors { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (Errors == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Errors");
}
if (Errors != null)
{
foreach (var element in Errors)
{
if (element != null)
{
element.Validate();
}
}
}
}
}
}

Просмотреть файл

@ -0,0 +1,58 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomSearch.Models
{
using Microsoft.Rest;
/// <summary>
/// Exception thrown for an invalid response with ErrorResponse
/// information.
/// </summary>
public partial class ErrorResponseException : RestException
{
/// <summary>
/// Gets information about the associated HTTP request.
/// </summary>
public HttpRequestMessageWrapper Request { get; set; }
/// <summary>
/// Gets information about the associated HTTP response.
/// </summary>
public HttpResponseMessageWrapper Response { get; set; }
/// <summary>
/// Gets or sets the body object.
/// </summary>
public ErrorResponse Body { get; set; }
/// <summary>
/// Initializes a new instance of the ErrorResponseException class.
/// </summary>
public ErrorResponseException()
{
}
/// <summary>
/// Initializes a new instance of the ErrorResponseException class.
/// </summary>
/// <param name="message">The exception message.</param>
public ErrorResponseException(string message)
: this(message, null)
{
}
/// <summary>
/// Initializes a new instance of the ErrorResponseException class.
/// </summary>
/// <param name="message">The exception message.</param>
/// <param name="innerException">Inner exception.</param>
public ErrorResponseException(string message, System.Exception innerException)
: base(message, innerException)
{
}
}
}

Просмотреть файл

@ -0,0 +1,27 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomSearch.Models
{
/// <summary>
/// Defines values for ErrorSubCode.
/// </summary>
public static class ErrorSubCode
{
public const string UnexpectedError = "UnexpectedError";
public const string ResourceError = "ResourceError";
public const string NotImplemented = "NotImplemented";
public const string ParameterMissing = "ParameterMissing";
public const string ParameterInvalidValue = "ParameterInvalidValue";
public const string HttpNotAllowed = "HttpNotAllowed";
public const string Blocked = "Blocked";
public const string AuthorizationMissing = "AuthorizationMissing";
public const string AuthorizationRedundancy = "AuthorizationRedundancy";
public const string AuthorizationDisabled = "AuthorizationDisabled";
public const string AuthorizationExpired = "AuthorizationExpired";
}
}

Просмотреть файл

@ -0,0 +1,48 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomSearch.Models
{
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Defines the identity of a resource.
/// </summary>
[Newtonsoft.Json.JsonObject("Identifiable")]
public partial class Identifiable : ResponseBase
{
/// <summary>
/// Initializes a new instance of the Identifiable class.
/// </summary>
public Identifiable()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the Identifiable class.
/// </summary>
/// <param name="id">A String identifier.</param>
public Identifiable(string id = default(string))
{
Id = id;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets a String identifier.
/// </summary>
[JsonProperty(PropertyName = "id")]
public string Id { get; private set; }
}
}

Просмотреть файл

@ -0,0 +1,95 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomSearch.Models
{
using Microsoft.Rest;
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Defines a search query.
/// </summary>
public partial class Query
{
/// <summary>
/// Initializes a new instance of the Query class.
/// </summary>
public Query()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the Query class.
/// </summary>
/// <param name="text">The query string. Use this string as the query
/// term in a new search request.</param>
/// <param name="displayText">The display version of the query term.
/// This version of the query term may contain special characters that
/// highlight the search term found in the query string. The string
/// contains the highlighting characters only if the query enabled hit
/// highlighting</param>
/// <param name="webSearchUrl">The URL that takes the user to the Bing
/// search results page for the query.Only related search results
/// include this field.</param>
public Query(string text, string displayText = default(string), string webSearchUrl = default(string), string searchLink = default(string))
{
Text = text;
DisplayText = displayText;
WebSearchUrl = webSearchUrl;
SearchLink = searchLink;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets the query string. Use this string as the query term in
/// a new search request.
/// </summary>
[JsonProperty(PropertyName = "text")]
public string Text { get; set; }
/// <summary>
/// Gets the display version of the query term. This version of the
/// query term may contain special characters that highlight the search
/// term found in the query string. The string contains the
/// highlighting characters only if the query enabled hit highlighting
/// </summary>
[JsonProperty(PropertyName = "displayText")]
public string DisplayText { get; private set; }
/// <summary>
/// Gets the URL that takes the user to the Bing search results page
/// for the query.Only related search results include this field.
/// </summary>
[JsonProperty(PropertyName = "webSearchUrl")]
public string WebSearchUrl { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "searchLink")]
public string SearchLink { get; private set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (Text == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Text");
}
}
}
}

Просмотреть файл

@ -0,0 +1,110 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomSearch.Models
{
using Microsoft.Rest;
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Defines the query context that Bing used for the request.
/// </summary>
public partial class QueryContext
{
/// <summary>
/// Initializes a new instance of the QueryContext class.
/// </summary>
public QueryContext()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the QueryContext class.
/// </summary>
/// <param name="originalQuery">The query string as specified in the
/// request.</param>
/// <param name="alteredQuery">The query string used by Bing to perform
/// the query. Bing uses the altered query string if the original query
/// string contained spelling mistakes. For example, if the query
/// string is "saling downwind", the altered query string will be
/// "sailing downwind". This field is included only if the original
/// query string contains a spelling mistake.</param>
/// <param name="alterationOverrideQuery">The query string to use to
/// force Bing to use the original string. For example, if the query
/// string is "saling downwind", the override query string will be
/// "+saling downwind". Remember to encode the query string which
/// results in "%2Bsaling+downwind". This field is included only if the
/// original query string contains a spelling mistake.</param>
/// <param name="adultIntent">A Boolean value that indicates whether
/// the specified query has adult intent. The value is true if the
/// query has adult intent; otherwise, false.</param>
public QueryContext(string originalQuery, string alteredQuery = default(string), string alterationOverrideQuery = default(string), bool? adultIntent = default(bool?))
{
OriginalQuery = originalQuery;
AlteredQuery = alteredQuery;
AlterationOverrideQuery = alterationOverrideQuery;
AdultIntent = adultIntent;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets the query string as specified in the request.
/// </summary>
[JsonProperty(PropertyName = "originalQuery")]
public string OriginalQuery { get; set; }
/// <summary>
/// Gets the query string used by Bing to perform the query. Bing uses
/// the altered query string if the original query string contained
/// spelling mistakes. For example, if the query string is "saling
/// downwind", the altered query string will be "sailing downwind".
/// This field is included only if the original query string contains a
/// spelling mistake.
/// </summary>
[JsonProperty(PropertyName = "alteredQuery")]
public string AlteredQuery { get; private set; }
/// <summary>
/// Gets the query string to use to force Bing to use the original
/// string. For example, if the query string is "saling downwind", the
/// override query string will be "+saling downwind". Remember to
/// encode the query string which results in "%2Bsaling+downwind". This
/// field is included only if the original query string contains a
/// spelling mistake.
/// </summary>
[JsonProperty(PropertyName = "alterationOverrideQuery")]
public string AlterationOverrideQuery { get; private set; }
/// <summary>
/// Gets a Boolean value that indicates whether the specified query has
/// adult intent. The value is true if the query has adult intent;
/// otherwise, false.
/// </summary>
[JsonProperty(PropertyName = "adultIntent")]
public bool? AdultIntent { get; private set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (OriginalQuery == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "OriginalQuery");
}
}
}
}

Просмотреть файл

@ -0,0 +1,52 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomSearch.Models
{
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Defines a response. All schemas that could be returned at the root of a
/// response should inherit from this
/// </summary>
[Newtonsoft.Json.JsonObject("Response")]
public partial class Response : Identifiable
{
/// <summary>
/// Initializes a new instance of the Response class.
/// </summary>
public Response()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the Response class.
/// </summary>
/// <param name="id">A String identifier.</param>
/// <param name="webSearchUrl">The URL To Bing's search result for this
/// item.</param>
public Response(string id = default(string), string webSearchUrl = default(string))
: base(id)
{
WebSearchUrl = webSearchUrl;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets the URL To Bing's search result for this item.
/// </summary>
[JsonProperty(PropertyName = "webSearchUrl")]
public string WebSearchUrl { get; private set; }
}
}

Просмотреть файл

@ -0,0 +1,30 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomSearch.Models
{
using Newtonsoft.Json;
using System.Linq;
[Newtonsoft.Json.JsonObject("ResponseBase")]
public partial class ResponseBase
{
/// <summary>
/// Initializes a new instance of the ResponseBase class.
/// </summary>
public ResponseBase()
{
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
}
}

Просмотреть файл

@ -0,0 +1,19 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomSearch.Models
{
/// <summary>
/// Defines values for SafeSearch.
/// </summary>
public static class SafeSearch
{
public const string Off = "Off";
public const string Moderate = "Moderate";
public const string Strict = "Strict";
}
}

Просмотреть файл

@ -0,0 +1,87 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomSearch.Models
{
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Defines the top-level object that the response includes when the
/// request succeeds.
/// </summary>
[Newtonsoft.Json.JsonObject("SearchResponse")]
public partial class SearchResponse : Response
{
/// <summary>
/// Initializes a new instance of the SearchResponse class.
/// </summary>
public SearchResponse()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the SearchResponse class.
/// </summary>
/// <param name="id">A String identifier.</param>
/// <param name="webSearchUrl">The URL To Bing's search result for this
/// item.</param>
/// <param name="queryContext">An object that contains the query string
/// that Bing used for the request. This object contains the query
/// string as entered by the user. It may also contain an altered query
/// string that Bing used for the query if the query string contained a
/// spelling mistake.</param>
/// <param name="webPages">A list of webpages that are relevant to the
/// search query.</param>
public SearchResponse(string id = default(string), string webSearchUrl = default(string), QueryContext queryContext = default(QueryContext), WebWebAnswer webPages = default(WebWebAnswer))
: base(id, webSearchUrl)
{
QueryContext = queryContext;
WebPages = webPages;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets an object that contains the query string that Bing used for
/// the request. This object contains the query string as entered by
/// the user. It may also contain an altered query string that Bing
/// used for the query if the query string contained a spelling
/// mistake.
/// </summary>
[JsonProperty(PropertyName = "queryContext")]
public QueryContext QueryContext { get; private set; }
/// <summary>
/// Gets a list of webpages that are relevant to the search query.
/// </summary>
[JsonProperty(PropertyName = "webPages")]
public WebWebAnswer WebPages { get; private set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="Rest.ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (QueryContext != null)
{
QueryContext.Validate();
}
if (WebPages != null)
{
WebPages.Validate();
}
}
}
}

Просмотреть файл

@ -0,0 +1,80 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomSearch.Models
{
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
[Newtonsoft.Json.JsonObject("SearchResultsAnswer")]
public partial class SearchResultsAnswer : Answer
{
/// <summary>
/// Initializes a new instance of the SearchResultsAnswer class.
/// </summary>
public SearchResultsAnswer()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the SearchResultsAnswer class.
/// </summary>
/// <param name="id">A String identifier.</param>
/// <param name="webSearchUrl">The URL To Bing's search result for this
/// item.</param>
/// <param name="totalEstimatedMatches">The estimated number of
/// webpages that are relevant to the query. Use this number along with
/// the count and offset query parameters to page the results.</param>
public SearchResultsAnswer(string id = default(string), string webSearchUrl = default(string), IList<Query> followUpQueries = default(IList<Query>), QueryContext queryContext = default(QueryContext), long? totalEstimatedMatches = default(long?), bool? isFamilyFriendly = default(bool?))
: base(id, webSearchUrl, followUpQueries)
{
QueryContext = queryContext;
TotalEstimatedMatches = totalEstimatedMatches;
IsFamilyFriendly = isFamilyFriendly;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "queryContext")]
public QueryContext QueryContext { get; private set; }
/// <summary>
/// Gets the estimated number of webpages that are relevant to the
/// query. Use this number along with the count and offset query
/// parameters to page the results.
/// </summary>
[JsonProperty(PropertyName = "totalEstimatedMatches")]
public long? TotalEstimatedMatches { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "isFamilyFriendly")]
public bool? IsFamilyFriendly { get; private set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="Rest.ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (QueryContext != null)
{
QueryContext.Validate();
}
}
}
}

Просмотреть файл

@ -0,0 +1,18 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomSearch.Models
{
/// <summary>
/// Defines values for TextFormat.
/// </summary>
public static class TextFormat
{
public const string Raw = "Raw";
public const string Html = "Html";
}
}

Просмотреть файл

@ -0,0 +1,77 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomSearch.Models
{
using Newtonsoft.Json;
using System.Linq;
[Newtonsoft.Json.JsonObject("Thing")]
public partial class Thing : Response
{
/// <summary>
/// Initializes a new instance of the Thing class.
/// </summary>
public Thing()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the Thing class.
/// </summary>
/// <param name="id">A String identifier.</param>
/// <param name="webSearchUrl">The URL To Bing's search result for this
/// item.</param>
/// <param name="name">The name of the thing represented by this
/// object.</param>
/// <param name="url">The URL to get more information about the thing
/// represented by this object.</param>
/// <param name="description">A short description of the item.</param>
/// <param name="bingId">An ID that uniquely identifies this
/// item.</param>
public Thing(string id = default(string), string webSearchUrl = default(string), string name = default(string), string url = default(string), string description = default(string), string bingId = default(string))
: base(id, webSearchUrl)
{
Name = name;
Url = url;
Description = description;
BingId = bingId;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets the name of the thing represented by this object.
/// </summary>
[JsonProperty(PropertyName = "name")]
public string Name { get; private set; }
/// <summary>
/// Gets the URL to get more information about the thing represented by
/// this object.
/// </summary>
[JsonProperty(PropertyName = "url")]
public string Url { get; private set; }
/// <summary>
/// Gets a short description of the item.
/// </summary>
[JsonProperty(PropertyName = "description")]
public string Description { get; private set; }
/// <summary>
/// Gets an ID that uniquely identifies this item.
/// </summary>
[JsonProperty(PropertyName = "bingId")]
public string BingId { get; private set; }
}
}

Просмотреть файл

@ -0,0 +1,55 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomSearch.Models
{
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Defines a webpage's metadata.
/// </summary>
public partial class WebMetaTag
{
/// <summary>
/// Initializes a new instance of the WebMetaTag class.
/// </summary>
public WebMetaTag()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the WebMetaTag class.
/// </summary>
/// <param name="name">The metadata.</param>
/// <param name="content">The name of the metadata.</param>
public WebMetaTag(string name = default(string), string content = default(string))
{
Name = name;
Content = content;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets the metadata.
/// </summary>
[JsonProperty(PropertyName = "name")]
public string Name { get; private set; }
/// <summary>
/// Gets the name of the metadata.
/// </summary>
[JsonProperty(PropertyName = "content")]
public string Content { get; private set; }
}
}

Просмотреть файл

@ -0,0 +1,118 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomSearch.Models
{
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Defines a webpage that is relevant to the query.
/// </summary>
[Newtonsoft.Json.JsonObject("WebPage")]
public partial class WebPage : CreativeWork
{
/// <summary>
/// Initializes a new instance of the WebPage class.
/// </summary>
public WebPage()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the WebPage class.
/// </summary>
/// <param name="id">A String identifier.</param>
/// <param name="webSearchUrl">The URL To Bing's search result for this
/// item.</param>
/// <param name="name">The name of the thing represented by this
/// object.</param>
/// <param name="url">The URL to get more information about the thing
/// represented by this object.</param>
/// <param name="description">A short description of the item.</param>
/// <param name="bingId">An ID that uniquely identifies this
/// item.</param>
/// <param name="thumbnailUrl">The URL to a thumbnail of the
/// item.</param>
/// <param name="provider">The source of the creative work.</param>
/// <param name="displayUrl">The display URL of the webpage. The URL is
/// meant for display purposes only and is not well formed.</param>
/// <param name="snippet">A snippet of text from the webpage that
/// describes its contents.</param>
/// <param name="deepLinks">A list of links to related content that
/// Bing found in the website that contains this webpage. The Webpage
/// object in this context includes only the name, url, urlPingSuffix,
/// and snippet fields.</param>
/// <param name="dateLastCrawled">The last time that Bing crawled the
/// webpage. The date is in the form, YYYY-MM-DDTHH:MM:SS. For example,
/// 2015-04-13T05:23:39.</param>
/// <param name="searchTags">A list of search tags that the webpage
/// owner specified on the webpage. The API returns only indexed search
/// tags. The name field of the MetaTag object contains the indexed
/// search tag. Search tags begin with search.* (for example,
/// search.assetId). The content field contains the tag's
/// value.</param>
public WebPage(string id = default(string), string webSearchUrl = default(string), string name = default(string), string url = default(string), string description = default(string), string bingId = default(string), string thumbnailUrl = default(string), IList<Thing> provider = default(IList<Thing>), string text = default(string), string displayUrl = default(string), string snippet = default(string), IList<WebPage> deepLinks = default(IList<WebPage>), string dateLastCrawled = default(string), IList<WebMetaTag> searchTags = default(IList<WebMetaTag>))
: base(id, webSearchUrl, name, url, description, bingId, thumbnailUrl, provider, text)
{
DisplayUrl = displayUrl;
Snippet = snippet;
DeepLinks = deepLinks;
DateLastCrawled = dateLastCrawled;
SearchTags = searchTags;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets the display URL of the webpage. The URL is meant for display
/// purposes only and is not well formed.
/// </summary>
[JsonProperty(PropertyName = "displayUrl")]
public string DisplayUrl { get; private set; }
/// <summary>
/// Gets a snippet of text from the webpage that describes its
/// contents.
/// </summary>
[JsonProperty(PropertyName = "snippet")]
public string Snippet { get; private set; }
/// <summary>
/// Gets a list of links to related content that Bing found in the
/// website that contains this webpage. The Webpage object in this
/// context includes only the name, url, urlPingSuffix, and snippet
/// fields.
/// </summary>
[JsonProperty(PropertyName = "deepLinks")]
public IList<WebPage> DeepLinks { get; private set; }
/// <summary>
/// Gets the last time that Bing crawled the webpage. The date is in
/// the form, YYYY-MM-DDTHH:MM:SS. For example, 2015-04-13T05:23:39.
/// </summary>
[JsonProperty(PropertyName = "dateLastCrawled")]
public string DateLastCrawled { get; private set; }
/// <summary>
/// Gets a list of search tags that the webpage owner specified on the
/// webpage. The API returns only indexed search tags. The name field
/// of the MetaTag object contains the indexed search tag. Search tags
/// begin with search.* (for example, search.assetId). The content
/// field contains the tag's value.
/// </summary>
[JsonProperty(PropertyName = "searchTags")]
public IList<WebMetaTag> SearchTags { get; private set; }
}
}

Просмотреть файл

@ -0,0 +1,85 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.CustomSearch.Models
{
using Microsoft.Rest;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Defines a list of relevant webpage links.
/// </summary>
[Newtonsoft.Json.JsonObject("Web/WebAnswer")]
public partial class WebWebAnswer : SearchResultsAnswer
{
/// <summary>
/// Initializes a new instance of the WebWebAnswer class.
/// </summary>
public WebWebAnswer()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the WebWebAnswer class.
/// </summary>
/// <param name="value">A list of webpages that are relevant to the
/// query.</param>
/// <param name="id">A String identifier.</param>
/// <param name="webSearchUrl">The URL To Bing's search result for this
/// item.</param>
/// <param name="totalEstimatedMatches">The estimated number of
/// webpages that are relevant to the query. Use this number along with
/// the count and offset query parameters to page the results.</param>
/// <param name="someResultsRemoved">A Boolean value that indicates
/// whether the response excluded some results from the answer. If Bing
/// excluded some results, the value is true.</param>
public WebWebAnswer(IList<WebPage> value, string id = default(string), string webSearchUrl = default(string), IList<Query> followUpQueries = default(IList<Query>), QueryContext queryContext = default(QueryContext), long? totalEstimatedMatches = default(long?), bool? isFamilyFriendly = default(bool?), bool? someResultsRemoved = default(bool?))
: base(id, webSearchUrl, followUpQueries, queryContext, totalEstimatedMatches, isFamilyFriendly)
{
Value = value;
SomeResultsRemoved = someResultsRemoved;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets a list of webpages that are relevant to the query.
/// </summary>
[JsonProperty(PropertyName = "value")]
public IList<WebPage> Value { get; set; }
/// <summary>
/// Gets a Boolean value that indicates whether the response excluded
/// some results from the answer. If Bing excluded some results, the
/// value is true.
/// </summary>
[JsonProperty(PropertyName = "someResultsRemoved")]
public bool? SomeResultsRemoved { get; private set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public override void Validate()
{
base.Validate();
if (Value == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Value");
}
}
}
}

Просмотреть файл

@ -0,0 +1,473 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.EntitySearch
{
using Microsoft.Rest;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// EntitiesOperations operations.
/// </summary>
public partial class EntitiesOperations : IServiceOperations<EntitySearchClient>, IEntitiesOperations
{
/// <summary>
/// Initializes a new instance of the EntitiesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public EntitiesOperations(EntitySearchClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the EntitySearchClient
/// </summary>
public EntitySearchClient Client { get; private set; }
/// <summary>
/// The Entity Search API lets you send a search query to Bing and get back
/// search results that include entities and places. Place results include
/// restaurants, hotel, or other local businesses. For places, the query can
/// specify the name of the local business or it can ask for a list (for
/// example, restaurants near me). Entity results include persons, places, or
/// things. Place in this context is tourist attractions, states, countries,
/// etc.
/// </summary>
/// <param name='query'>
/// The user's search term.
/// </param>
/// <param name='acceptLanguage'>
/// A comma-delimited list of one or more languages to use for user interface
/// strings. The list is in decreasing order of preference. For additional
/// information, including expected format, see
/// [RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). This
/// header and the setLang query parameter are mutually exclusive; do not
/// specify both. If you set this header, you must also specify the cc query
/// parameter. Bing will use the first supported language it finds from the
/// list, and combine that language with the cc parameter value to determine
/// the market to return results for. If the list does not include a supported
/// language, Bing will find the closest language and market that supports the
/// request, and may use an aggregated or default market for the results
/// instead of a specified one. You should use this header and the cc query
/// parameter only if you specify multiple languages; otherwise, you should use
/// the mkt and setLang query parameters. A user interface string is a string
/// that's used as a label in a user interface. There are very few user
/// interface strings in the JSON response objects. Any links in the response
/// objects to Bing.com properties will apply the specified language.
/// </param>
/// <param name='pragma'>
/// By default, Bing returns cached content, if available. To prevent Bing from
/// returning cached content, set the Pragma header to no-cache (for example,
/// Pragma: no-cache).
/// </param>
/// <param name='userAgent'>
/// The user agent originating the request. Bing uses the user agent to provide
/// mobile users with an optimized experience. Although optional, you are
/// strongly encouraged to always specify this header. The user-agent should be
/// the same string that any commonly used browser would send. For information
/// about user agents, see [RFC
/// 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html).
/// </param>
/// <param name='clientId'>
/// Bing uses this header to provide users with consistent behavior across Bing
/// API calls. Bing often flights new features and improvements, and it uses
/// the client ID as a key for assigning traffic on different flights. If you
/// do not use the same client ID for a user across multiple requests, then
/// Bing may assign the user to multiple conflicting flights. Being assigned to
/// multiple conflicting flights can lead to an inconsistent user experience.
/// For example, if the second request has a different flight assignment than
/// the first, the experience may be unexpected. Also, Bing can use the client
/// ID to tailor web results to that client IDs search history, providing a
/// richer experience for the user. Bing also uses this header to help improve
/// result rankings by analyzing the activity generated by a client ID. The
/// relevance improvements help with better quality of results delivered by
/// Bing APIs and in turn enables higher click-through rates for the API
/// consumer. IMPORTANT: Although optional, you should consider this header
/// required. Persisting the client ID across multiple requests for the same
/// end user and device combination enables 1) the API consumer to receive a
/// consistent user experience, and 2) higher click-through rates via better
/// quality of results from the Bing APIs. Each user that uses your application
/// on the device must have a unique, Bing generated client ID. If you do not
/// include this header in the request, Bing generates an ID and returns it in
/// the X-MSEdge-ClientID response header. The only time that you should NOT
/// include this header in a request is the first time the user uses your app
/// on that device. Use the client ID for each Bing API request that your app
/// makes for this user on the device. Persist the client ID. To persist the ID
/// in a browser app, use a persistent HTTP cookie to ensure the ID is used
/// across all sessions. Do not use a session cookie. For other apps such as
/// mobile apps, use the device's persistent storage to persist the ID. The
/// next time the user uses your app on that device, get the client ID that you
/// persisted. Bing responses may or may not include this header. If the
/// response includes this header, capture the client ID and use it for all
/// subsequent Bing requests for the user on that device. If you include the
/// X-MSEdge-ClientID, you must not include cookies in the request.
/// </param>
/// <param name='clientIp'>
/// The IPv4 or IPv6 address of the client device. The IP address is used to
/// discover the user's location. Bing uses the location information to
/// determine safe search behavior. Although optional, you are encouraged to
/// always specify this header and the X-Search-Location header. Do not
/// obfuscate the address (for example, by changing the last octet to 0).
/// Obfuscating the address results in the location not being anywhere near the
/// device's actual location, which may result in Bing serving erroneous
/// results.
/// </param>
/// <param name='location'>
/// A semicolon-delimited list of key/value pairs that describe the client's
/// geographical location. Bing uses the location information to determine safe
/// search behavior and to return relevant local content. Specify the key/value
/// pair as &lt;key&gt;:&lt;value&gt;. The following are the keys that you use
/// to specify the user's location. lat (required): The latitude of the
/// client's location, in degrees. The latitude must be greater than or equal
/// to -90.0 and less than or equal to +90.0. Negative values indicate southern
/// latitudes and positive values indicate northern latitudes. long (required):
/// The longitude of the client's location, in degrees. The longitude must be
/// greater than or equal to -180.0 and less than or equal to +180.0. Negative
/// values indicate western longitudes and positive values indicate eastern
/// longitudes. re (required): The radius, in meters, which specifies the
/// horizontal accuracy of the coordinates. Pass the value returned by the
/// device's location service. Typical values might be 22m for GPS/Wi-Fi, 380m
/// for cell tower triangulation, and 18,000m for reverse IP lookup. ts
/// (optional): The UTC UNIX timestamp of when the client was at the location.
/// (The UNIX timestamp is the number of seconds since January 1, 1970.) head
/// (optional): The client's relative heading or direction of travel. Specify
/// the direction of travel as degrees from 0 through 360, counting clockwise
/// relative to true north. Specify this key only if the sp key is nonzero. sp
/// (optional): The horizontal velocity (speed), in meters per second, that the
/// client device is traveling. alt (optional): The altitude of the client
/// device, in meters. are (optional): The radius, in meters, that specifies
/// the vertical accuracy of the coordinates. Specify this key only if you
/// specify the alt key. Although many of the keys are optional, the more
/// information that you provide, the more accurate the location results are.
/// Although optional, you are encouraged to always specify the user's
/// geographical location. Providing the location is especially important if
/// the client's IP address does not accurately reflect the user's physical
/// location (for example, if the client uses VPN). For optimal results, you
/// should include this header and the X-MSEdge-ClientIP header, but at a
/// minimum, you should include this header.
/// </param>
/// <param name='countryCode'>
/// A 2-character country code of the country where the results come from. This
/// API supports only the United States market. If you specify this query
/// parameter, it must be set to us. If you set this parameter, you must also
/// specify the Accept-Language header. Bing uses the first supported language
/// it finds from the languages list, and combine that language with the
/// country code that you specify to determine the market to return results
/// for. If the languages list does not include a supported language, Bing
/// finds the closest language and market that supports the request, or it may
/// use an aggregated or default market for the results instead of a specified
/// one. You should use this query parameter and the Accept-Language query
/// parameter only if you specify multiple languages; otherwise, you should use
/// the mkt and setLang query parameters. This parameter and the mkt query
/// parameter are mutually exclusive—do not specify both.
/// </param>
/// <param name='market'>
/// The market where the results come from. You are strongly encouraged to
/// always specify the market, if known. Specifying the market helps Bing route
/// the request and return an appropriate and optimal response. This parameter
/// and the cc query parameter are mutually exclusive—do not specify both.
/// </param>
/// <param name='responseFilter'>
/// A comma-delimited list of answers to include in the response. If you do not
/// specify this parameter, the response includes all search answers for which
/// there's relevant data.
/// </param>
/// <param name='responseFormat'>
/// The media type to use for the response. The following are the possible
/// case-insensitive values: JSON, JSONLD. The default is JSON. If you specify
/// JSONLD, the response body includes JSON-LD objects that contain the search
/// results.
/// </param>
/// <param name='safeSearch'>
/// A filter used to filter adult content. Off: Return webpages with adult
/// text, images, or videos. Moderate: Return webpages with adult text, but not
/// adult images or videos. Strict: Do not return webpages with adult text,
/// images, or videos. The default is Moderate. If the request comes from a
/// market that Bing's adult policy requires that safeSearch is set to Strict,
/// Bing ignores the safeSearch value and uses Strict. If you use the site:
/// query operator, there is the chance that the response may contain adult
/// content regardless of what the safeSearch query parameter is set to. Use
/// site: only if you are aware of the content on the site and your scenario
/// supports the possibility of adult content. Possible values include: 'Off',
/// 'Moderate', 'Strict'
/// </param>
/// <param name='setLang'>
/// The language to use for user interface strings. Specify the language using
/// the ISO 639-1 2-letter language code. For example, the language code for
/// English is EN. The default is EN (English). Although optional, you should
/// always specify the language. Typically, you set setLang to the same
/// language specified by mkt unless the user wants the user interface strings
/// displayed in a different language. This parameter and the Accept-Language
/// header are mutually exclusive; do not specify both. A user interface string
/// is a string that's used as a label in a user interface. There are few user
/// interface strings in the JSON response objects. Also, any links to Bing.com
/// properties in the response objects apply the specified language.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<SearchResponse>> SearchWithHttpMessagesAsync(string query, string acceptLanguage = default(string), string pragma = default(string), string userAgent = default(string), string clientId = default(string), string clientIp = default(string), string location = default(string), string countryCode = default(string), string market = "en-us", IList<string> responseFilter = default(IList<string>), IList<string> responseFormat = default(IList<string>), string safeSearch = default(string), string setLang = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (query == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "query");
}
string xBingApisSDK = "true";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("xBingApisSDK", xBingApisSDK);
tracingParameters.Add("acceptLanguage", acceptLanguage);
tracingParameters.Add("pragma", pragma);
tracingParameters.Add("userAgent", userAgent);
tracingParameters.Add("clientId", clientId);
tracingParameters.Add("clientIp", clientIp);
tracingParameters.Add("location", location);
tracingParameters.Add("countryCode", countryCode);
tracingParameters.Add("market", market);
tracingParameters.Add("query", query);
tracingParameters.Add("responseFilter", responseFilter);
tracingParameters.Add("responseFormat", responseFormat);
tracingParameters.Add("safeSearch", safeSearch);
tracingParameters.Add("setLang", setLang);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Search", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "entities").ToString();
List<string> _queryParameters = new List<string>();
if (countryCode != null)
{
_queryParameters.Add(string.Format("cc={0}", System.Uri.EscapeDataString(countryCode)));
}
if (market != null)
{
_queryParameters.Add(string.Format("mkt={0}", System.Uri.EscapeDataString(market)));
}
if (query != null)
{
_queryParameters.Add(string.Format("q={0}", System.Uri.EscapeDataString(query)));
}
if (responseFilter != null)
{
_queryParameters.Add(string.Format("ResponseFilter={0}", System.Uri.EscapeDataString(string.Join(",", responseFilter))));
}
if (responseFormat != null)
{
_queryParameters.Add(string.Format("ResponseFormat={0}", System.Uri.EscapeDataString(string.Join(",", responseFormat))));
}
if (safeSearch != null)
{
_queryParameters.Add(string.Format("SafeSearch={0}", System.Uri.EscapeDataString(safeSearch)));
}
if (setLang != null)
{
_queryParameters.Add(string.Format("SetLang={0}", System.Uri.EscapeDataString(setLang)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (xBingApisSDK != null)
{
if (_httpRequest.Headers.Contains("X-BingApis-SDK"))
{
_httpRequest.Headers.Remove("X-BingApis-SDK");
}
_httpRequest.Headers.TryAddWithoutValidation("X-BingApis-SDK", xBingApisSDK);
}
if (acceptLanguage != null)
{
if (_httpRequest.Headers.Contains("Accept-Language"))
{
_httpRequest.Headers.Remove("Accept-Language");
}
_httpRequest.Headers.TryAddWithoutValidation("Accept-Language", acceptLanguage);
}
if (pragma != null)
{
if (_httpRequest.Headers.Contains("Pragma"))
{
_httpRequest.Headers.Remove("Pragma");
}
_httpRequest.Headers.TryAddWithoutValidation("Pragma", pragma);
}
if (userAgent != null)
{
if (_httpRequest.Headers.Contains("User-Agent"))
{
_httpRequest.Headers.Remove("User-Agent");
}
_httpRequest.Headers.TryAddWithoutValidation("User-Agent", userAgent);
}
if (clientId != null)
{
if (_httpRequest.Headers.Contains("X-MSEdge-ClientID"))
{
_httpRequest.Headers.Remove("X-MSEdge-ClientID");
}
_httpRequest.Headers.TryAddWithoutValidation("X-MSEdge-ClientID", clientId);
}
if (clientIp != null)
{
if (_httpRequest.Headers.Contains("X-MSEdge-ClientIP"))
{
_httpRequest.Headers.Remove("X-MSEdge-ClientIP");
}
_httpRequest.Headers.TryAddWithoutValidation("X-MSEdge-ClientIP", clientIp);
}
if (location != null)
{
if (_httpRequest.Headers.Contains("X-Search-Location"))
{
_httpRequest.Headers.Remove("X-Search-Location");
}
_httpRequest.Headers.TryAddWithoutValidation("X-Search-Location", location);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<SearchResponse>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<SearchResponse>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}

Просмотреть файл

@ -0,0 +1,401 @@
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.EntitySearch
{
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for EntitiesOperations.
/// </summary>
public static partial class EntitiesOperationsExtensions
{
/// <summary>
/// The Entity Search API lets you send a search query to Bing and get back
/// search results that include entities and places. Place results include
/// restaurants, hotel, or other local businesses. For places, the query can
/// specify the name of the local business or it can ask for a list (for
/// example, restaurants near me). Entity results include persons, places, or
/// things. Place in this context is tourist attractions, states, countries,
/// etc.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='query'>
/// The user's search term.
/// </param>
/// <param name='acceptLanguage'>
/// A comma-delimited list of one or more languages to use for user interface
/// strings. The list is in decreasing order of preference. For additional
/// information, including expected format, see
/// [RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). This
/// header and the setLang query parameter are mutually exclusive; do not
/// specify both. If you set this header, you must also specify the cc query
/// parameter. Bing will use the first supported language it finds from the
/// list, and combine that language with the cc parameter value to determine
/// the market to return results for. If the list does not include a supported
/// language, Bing will find the closest language and market that supports the
/// request, and may use an aggregated or default market for the results
/// instead of a specified one. You should use this header and the cc query
/// parameter only if you specify multiple languages; otherwise, you should use
/// the mkt and setLang query parameters. A user interface string is a string
/// that's used as a label in a user interface. There are very few user
/// interface strings in the JSON response objects. Any links in the response
/// objects to Bing.com properties will apply the specified language.
/// </param>
/// <param name='pragma'>
/// By default, Bing returns cached content, if available. To prevent Bing from
/// returning cached content, set the Pragma header to no-cache (for example,
/// Pragma: no-cache).
/// </param>
/// <param name='userAgent'>
/// The user agent originating the request. Bing uses the user agent to provide
/// mobile users with an optimized experience. Although optional, you are
/// strongly encouraged to always specify this header. The user-agent should be
/// the same string that any commonly used browser would send. For information
/// about user agents, see [RFC
/// 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html).
/// </param>
/// <param name='clientId'>
/// Bing uses this header to provide users with consistent behavior across Bing
/// API calls. Bing often flights new features and improvements, and it uses
/// the client ID as a key for assigning traffic on different flights. If you
/// do not use the same client ID for a user across multiple requests, then
/// Bing may assign the user to multiple conflicting flights. Being assigned to
/// multiple conflicting flights can lead to an inconsistent user experience.
/// For example, if the second request has a different flight assignment than
/// the first, the experience may be unexpected. Also, Bing can use the client
/// ID to tailor web results to that client IDs search history, providing a
/// richer experience for the user. Bing also uses this header to help improve
/// result rankings by analyzing the activity generated by a client ID. The
/// relevance improvements help with better quality of results delivered by
/// Bing APIs and in turn enables higher click-through rates for the API
/// consumer. IMPORTANT: Although optional, you should consider this header
/// required. Persisting the client ID across multiple requests for the same
/// end user and device combination enables 1) the API consumer to receive a
/// consistent user experience, and 2) higher click-through rates via better
/// quality of results from the Bing APIs. Each user that uses your application
/// on the device must have a unique, Bing generated client ID. If you do not
/// include this header in the request, Bing generates an ID and returns it in
/// the X-MSEdge-ClientID response header. The only time that you should NOT
/// include this header in a request is the first time the user uses your app
/// on that device. Use the client ID for each Bing API request that your app
/// makes for this user on the device. Persist the client ID. To persist the ID
/// in a browser app, use a persistent HTTP cookie to ensure the ID is used
/// across all sessions. Do not use a session cookie. For other apps such as
/// mobile apps, use the device's persistent storage to persist the ID. The
/// next time the user uses your app on that device, get the client ID that you
/// persisted. Bing responses may or may not include this header. If the
/// response includes this header, capture the client ID and use it for all
/// subsequent Bing requests for the user on that device. If you include the
/// X-MSEdge-ClientID, you must not include cookies in the request.
/// </param>
/// <param name='clientIp'>
/// The IPv4 or IPv6 address of the client device. The IP address is used to
/// discover the user's location. Bing uses the location information to
/// determine safe search behavior. Although optional, you are encouraged to
/// always specify this header and the X-Search-Location header. Do not
/// obfuscate the address (for example, by changing the last octet to 0).
/// Obfuscating the address results in the location not being anywhere near the
/// device's actual location, which may result in Bing serving erroneous
/// results.
/// </param>
/// <param name='location'>
/// A semicolon-delimited list of key/value pairs that describe the client's
/// geographical location. Bing uses the location information to determine safe
/// search behavior and to return relevant local content. Specify the key/value
/// pair as &lt;key&gt;:&lt;value&gt;. The following are the keys that you use
/// to specify the user's location. lat (required): The latitude of the
/// client's location, in degrees. The latitude must be greater than or equal
/// to -90.0 and less than or equal to +90.0. Negative values indicate southern
/// latitudes and positive values indicate northern latitudes. long (required):
/// The longitude of the client's location, in degrees. The longitude must be
/// greater than or equal to -180.0 and less than or equal to +180.0. Negative
/// values indicate western longitudes and positive values indicate eastern
/// longitudes. re (required): The radius, in meters, which specifies the
/// horizontal accuracy of the coordinates. Pass the value returned by the
/// device's location service. Typical values might be 22m for GPS/Wi-Fi, 380m
/// for cell tower triangulation, and 18,000m for reverse IP lookup. ts
/// (optional): The UTC UNIX timestamp of when the client was at the location.
/// (The UNIX timestamp is the number of seconds since January 1, 1970.) head
/// (optional): The client's relative heading or direction of travel. Specify
/// the direction of travel as degrees from 0 through 360, counting clockwise
/// relative to true north. Specify this key only if the sp key is nonzero. sp
/// (optional): The horizontal velocity (speed), in meters per second, that the
/// client device is traveling. alt (optional): The altitude of the client
/// device, in meters. are (optional): The radius, in meters, that specifies
/// the vertical accuracy of the coordinates. Specify this key only if you
/// specify the alt key. Although many of the keys are optional, the more
/// information that you provide, the more accurate the location results are.
/// Although optional, you are encouraged to always specify the user's
/// geographical location. Providing the location is especially important if
/// the client's IP address does not accurately reflect the user's physical
/// location (for example, if the client uses VPN). For optimal results, you
/// should include this header and the X-MSEdge-ClientIP header, but at a
/// minimum, you should include this header.
/// </param>
/// <param name='countryCode'>
/// A 2-character country code of the country where the results come from. This
/// API supports only the United States market. If you specify this query
/// parameter, it must be set to us. If you set this parameter, you must also
/// specify the Accept-Language header. Bing uses the first supported language
/// it finds from the languages list, and combine that language with the
/// country code that you specify to determine the market to return results
/// for. If the languages list does not include a supported language, Bing
/// finds the closest language and market that supports the request, or it may
/// use an aggregated or default market for the results instead of a specified
/// one. You should use this query parameter and the Accept-Language query
/// parameter only if you specify multiple languages; otherwise, you should use
/// the mkt and setLang query parameters. This parameter and the mkt query
/// parameter are mutually exclusive—do not specify both.
/// </param>
/// <param name='market'>
/// The market where the results come from. You are strongly encouraged to
/// always specify the market, if known. Specifying the market helps Bing route
/// the request and return an appropriate and optimal response. This parameter
/// and the cc query parameter are mutually exclusive—do not specify both.
/// </param>
/// <param name='responseFilter'>
/// A comma-delimited list of answers to include in the response. If you do not
/// specify this parameter, the response includes all search answers for which
/// there's relevant data.
/// </param>
/// <param name='responseFormat'>
/// The media type to use for the response. The following are the possible
/// case-insensitive values: JSON, JSONLD. The default is JSON. If you specify
/// JSONLD, the response body includes JSON-LD objects that contain the search
/// results.
/// </param>
/// <param name='safeSearch'>
/// A filter used to filter adult content. Off: Return webpages with adult
/// text, images, or videos. Moderate: Return webpages with adult text, but not
/// adult images or videos. Strict: Do not return webpages with adult text,
/// images, or videos. The default is Moderate. If the request comes from a
/// market that Bing's adult policy requires that safeSearch is set to Strict,
/// Bing ignores the safeSearch value and uses Strict. If you use the site:
/// query operator, there is the chance that the response may contain adult
/// content regardless of what the safeSearch query parameter is set to. Use
/// site: only if you are aware of the content on the site and your scenario
/// supports the possibility of adult content. Possible values include: 'Off',
/// 'Moderate', 'Strict'
/// </param>
/// <param name='setLang'>
/// The language to use for user interface strings. Specify the language using
/// the ISO 639-1 2-letter language code. For example, the language code for
/// English is EN. The default is EN (English). Although optional, you should
/// always specify the language. Typically, you set setLang to the same
/// language specified by mkt unless the user wants the user interface strings
/// displayed in a different language. This parameter and the Accept-Language
/// header are mutually exclusive; do not specify both. A user interface string
/// is a string that's used as a label in a user interface. There are few user
/// interface strings in the JSON response objects. Also, any links to Bing.com
/// properties in the response objects apply the specified language.
/// </param>
public static SearchResponse Search(this IEntitiesOperations operations, string query, string acceptLanguage = default(string), string pragma = default(string), string userAgent = default(string), string clientId = default(string), string clientIp = default(string), string location = default(string), string countryCode = default(string), string market = "en-us", IList<string> responseFilter = default(IList<string>), IList<string> responseFormat = default(IList<string>), string safeSearch = default(string), string setLang = default(string))
{
return operations.SearchAsync(query, acceptLanguage, pragma, userAgent, clientId, clientIp, location, countryCode, market, responseFilter, responseFormat, safeSearch, setLang).GetAwaiter().GetResult();
}
/// <summary>
/// The Entity Search API lets you send a search query to Bing and get back
/// search results that include entities and places. Place results include
/// restaurants, hotel, or other local businesses. For places, the query can
/// specify the name of the local business or it can ask for a list (for
/// example, restaurants near me). Entity results include persons, places, or
/// things. Place in this context is tourist attractions, states, countries,
/// etc.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='query'>
/// The user's search term.
/// </param>
/// <param name='acceptLanguage'>
/// A comma-delimited list of one or more languages to use for user interface
/// strings. The list is in decreasing order of preference. For additional
/// information, including expected format, see
/// [RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). This
/// header and the setLang query parameter are mutually exclusive; do not
/// specify both. If you set this header, you must also specify the cc query
/// parameter. Bing will use the first supported language it finds from the
/// list, and combine that language with the cc parameter value to determine
/// the market to return results for. If the list does not include a supported
/// language, Bing will find the closest language and market that supports the
/// request, and may use an aggregated or default market for the results
/// instead of a specified one. You should use this header and the cc query
/// parameter only if you specify multiple languages; otherwise, you should use
/// the mkt and setLang query parameters. A user interface string is a string
/// that's used as a label in a user interface. There are very few user
/// interface strings in the JSON response objects. Any links in the response
/// objects to Bing.com properties will apply the specified language.
/// </param>
/// <param name='pragma'>
/// By default, Bing returns cached content, if available. To prevent Bing from
/// returning cached content, set the Pragma header to no-cache (for example,
/// Pragma: no-cache).
/// </param>
/// <param name='userAgent'>
/// The user agent originating the request. Bing uses the user agent to provide
/// mobile users with an optimized experience. Although optional, you are
/// strongly encouraged to always specify this header. The user-agent should be
/// the same string that any commonly used browser would send. For information
/// about user agents, see [RFC
/// 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html).
/// </param>
/// <param name='clientId'>
/// Bing uses this header to provide users with consistent behavior across Bing
/// API calls. Bing often flights new features and improvements, and it uses
/// the client ID as a key for assigning traffic on different flights. If you
/// do not use the same client ID for a user across multiple requests, then
/// Bing may assign the user to multiple conflicting flights. Being assigned to
/// multiple conflicting flights can lead to an inconsistent user experience.
/// For example, if the second request has a different flight assignment than
/// the first, the experience may be unexpected. Also, Bing can use the client
/// ID to tailor web results to that client IDs search history, providing a
/// richer experience for the user. Bing also uses this header to help improve
/// result rankings by analyzing the activity generated by a client ID. The
/// relevance improvements help with better quality of results delivered by
/// Bing APIs and in turn enables higher click-through rates for the API
/// consumer. IMPORTANT: Although optional, you should consider this header
/// required. Persisting the client ID across multiple requests for the same
/// end user and device combination enables 1) the API consumer to receive a
/// consistent user experience, and 2) higher click-through rates via better
/// quality of results from the Bing APIs. Each user that uses your application
/// on the device must have a unique, Bing generated client ID. If you do not
/// include this header in the request, Bing generates an ID and returns it in
/// the X-MSEdge-ClientID response header. The only time that you should NOT
/// include this header in a request is the first time the user uses your app
/// on that device. Use the client ID for each Bing API request that your app
/// makes for this user on the device. Persist the client ID. To persist the ID
/// in a browser app, use a persistent HTTP cookie to ensure the ID is used
/// across all sessions. Do not use a session cookie. For other apps such as
/// mobile apps, use the device's persistent storage to persist the ID. The
/// next time the user uses your app on that device, get the client ID that you
/// persisted. Bing responses may or may not include this header. If the
/// response includes this header, capture the client ID and use it for all
/// subsequent Bing requests for the user on that device. If you include the
/// X-MSEdge-ClientID, you must not include cookies in the request.
/// </param>
/// <param name='clientIp'>
/// The IPv4 or IPv6 address of the client device. The IP address is used to
/// discover the user's location. Bing uses the location information to
/// determine safe search behavior. Although optional, you are encouraged to
/// always specify this header and the X-Search-Location header. Do not
/// obfuscate the address (for example, by changing the last octet to 0).
/// Obfuscating the address results in the location not being anywhere near the
/// device's actual location, which may result in Bing serving erroneous
/// results.
/// </param>
/// <param name='location'>
/// A semicolon-delimited list of key/value pairs that describe the client's
/// geographical location. Bing uses the location information to determine safe
/// search behavior and to return relevant local content. Specify the key/value
/// pair as &lt;key&gt;:&lt;value&gt;. The following are the keys that you use
/// to specify the user's location. lat (required): The latitude of the
/// client's location, in degrees. The latitude must be greater than or equal
/// to -90.0 and less than or equal to +90.0. Negative values indicate southern
/// latitudes and positive values indicate northern latitudes. long (required):
/// The longitude of the client's location, in degrees. The longitude must be
/// greater than or equal to -180.0 and less than or equal to +180.0. Negative
/// values indicate western longitudes and positive values indicate eastern
/// longitudes. re (required): The radius, in meters, which specifies the
/// horizontal accuracy of the coordinates. Pass the value returned by the
/// device's location service. Typical values might be 22m for GPS/Wi-Fi, 380m
/// for cell tower triangulation, and 18,000m for reverse IP lookup. ts
/// (optional): The UTC UNIX timestamp of when the client was at the location.
/// (The UNIX timestamp is the number of seconds since January 1, 1970.) head
/// (optional): The client's relative heading or direction of travel. Specify
/// the direction of travel as degrees from 0 through 360, counting clockwise
/// relative to true north. Specify this key only if the sp key is nonzero. sp
/// (optional): The horizontal velocity (speed), in meters per second, that the
/// client device is traveling. alt (optional): The altitude of the client
/// device, in meters. are (optional): The radius, in meters, that specifies
/// the vertical accuracy of the coordinates. Specify this key only if you
/// specify the alt key. Although many of the keys are optional, the more
/// information that you provide, the more accurate the location results are.
/// Although optional, you are encouraged to always specify the user's
/// geographical location. Providing the location is especially important if
/// the client's IP address does not accurately reflect the user's physical
/// location (for example, if the client uses VPN). For optimal results, you
/// should include this header and the X-MSEdge-ClientIP header, but at a
/// minimum, you should include this header.
/// </param>
/// <param name='countryCode'>
/// A 2-character country code of the country where the results come from. This
/// API supports only the United States market. If you specify this query
/// parameter, it must be set to us. If you set this parameter, you must also
/// specify the Accept-Language header. Bing uses the first supported language
/// it finds from the languages list, and combine that language with the
/// country code that you specify to determine the market to return results
/// for. If the languages list does not include a supported language, Bing
/// finds the closest language and market that supports the request, or it may
/// use an aggregated or default market for the results instead of a specified
/// one. You should use this query parameter and the Accept-Language query
/// parameter only if you specify multiple languages; otherwise, you should use
/// the mkt and setLang query parameters. This parameter and the mkt query
/// parameter are mutually exclusive—do not specify both.
/// </param>
/// <param name='market'>
/// The market where the results come from. You are strongly encouraged to
/// always specify the market, if known. Specifying the market helps Bing route
/// the request and return an appropriate and optimal response. This parameter
/// and the cc query parameter are mutually exclusive—do not specify both.
/// </param>
/// <param name='responseFilter'>
/// A comma-delimited list of answers to include in the response. If you do not
/// specify this parameter, the response includes all search answers for which
/// there's relevant data.
/// </param>
/// <param name='responseFormat'>
/// The media type to use for the response. The following are the possible
/// case-insensitive values: JSON, JSONLD. The default is JSON. If you specify
/// JSONLD, the response body includes JSON-LD objects that contain the search
/// results.
/// </param>
/// <param name='safeSearch'>
/// A filter used to filter adult content. Off: Return webpages with adult
/// text, images, or videos. Moderate: Return webpages with adult text, but not
/// adult images or videos. Strict: Do not return webpages with adult text,
/// images, or videos. The default is Moderate. If the request comes from a
/// market that Bing's adult policy requires that safeSearch is set to Strict,
/// Bing ignores the safeSearch value and uses Strict. If you use the site:
/// query operator, there is the chance that the response may contain adult
/// content regardless of what the safeSearch query parameter is set to. Use
/// site: only if you are aware of the content on the site and your scenario
/// supports the possibility of adult content. Possible values include: 'Off',
/// 'Moderate', 'Strict'
/// </param>
/// <param name='setLang'>
/// The language to use for user interface strings. Specify the language using
/// the ISO 639-1 2-letter language code. For example, the language code for
/// English is EN. The default is EN (English). Although optional, you should
/// always specify the language. Typically, you set setLang to the same
/// language specified by mkt unless the user wants the user interface strings
/// displayed in a different language. This parameter and the Accept-Language
/// header are mutually exclusive; do not specify both. A user interface string
/// is a string that's used as a label in a user interface. There are few user
/// interface strings in the JSON response objects. Also, any links to Bing.com
/// properties in the response objects apply the specified language.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<SearchResponse> SearchAsync(this IEntitiesOperations operations, string query, string acceptLanguage = default(string), string pragma = default(string), string userAgent = default(string), string clientId = default(string), string clientIp = default(string), string location = default(string), string countryCode = default(string), string market = "en-us", IList<string> responseFilter = default(IList<string>), IList<string> responseFormat = default(IList<string>), string safeSearch = default(string), string setLang = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.SearchWithHttpMessagesAsync(query, acceptLanguage, pragma, userAgent, clientId, clientIp, location, countryCode, market, responseFilter, responseFormat, safeSearch, setLang, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}

Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше