Skip to content

Commit f02d0af

Browse files
authored
Update structure
1 parent 451b266 commit f02d0af

File tree

1 file changed

+24
-131
lines changed

1 file changed

+24
-131
lines changed

dotnet/Search/BingImageSearchv7.cs

Lines changed: 24 additions & 131 deletions
Original file line numberDiff line numberDiff line change
@@ -1,164 +1,57 @@
1-
//Copyright (c) Microsoft Corporation. All rights reserved.
2-
//Licensed under the MIT License.
1+
// Copyright (c) Microsoft Corporation. All rights reserved.
2+
// Licensed under the MIT License.
33

4+
using Newtonsoft.Json;
45
using System;
56
using System.Text;
67
using System.Net;
78
using System.IO;
89
using System.Collections.Generic;
910

10-
namespace BingSearchApisQuickstart
11-
{
11+
/* This sample makes a call to the Bing Search API with a text query and returns relevant data from the web.
12+
* Documentation: https://docs.microsoft.com/en-us/azure/cognitive-services/bing-web-search/
13+
*/
1214

15+
namespace BingImageSearch
16+
{
1317
class Program
1418
{
15-
// **********************************************
16-
// *** Update or verify the following values. ***
17-
// **********************************************
18-
19-
// Add your Azure Bing Search V7 subscription key to your environment variables.
20-
const string accessKey = Environment.GetEnvironmentVariable("BING_SEARCH_V7_SUBSCRIPTION_KEY");
21-
22-
// Add your Azure Bing Search V7 endpoint to your environment variables.
23-
const string uriBase = Environment.GetEnvironmentVariable("BING_SEARCH_V7_ENDPOINT") + "/bing/v7.0/images/search";
19+
// Add your Azure Bing Search V7 subscription key and endpoint to your environment variables.
20+
static string subscriptionKey = Environment.GetEnvironmentVariable("BING_SEARCH_V7_SUBSCRIPTION_KEY");
21+
static string endpoint = Environment.GetEnvironmentVariable("BING_SEARCH_V7_ENDPOINT") + "/bing/v7.0/images/search";
2422

25-
const string searchTerm = "puppies";
26-
27-
// Used to return image search results including relevant headers
28-
struct SearchResult
29-
{
30-
public String jsonResult;
31-
public Dictionary<String, String> relevantHeaders;
32-
}
23+
const string query = "puppies";
3324

3425
static void Main()
3526
{
36-
Console.OutputEncoding = System.Text.Encoding.UTF8;
37-
38-
if (accessKey.Length == 32)
39-
{
40-
Console.WriteLine("Searching images for: " + searchTerm);
41-
42-
SearchResult result = BingImageSearch(searchTerm);
43-
44-
Console.WriteLine("\nRelevant HTTP Headers:\n");
45-
foreach (var header in result.relevantHeaders)
46-
Console.WriteLine(header.Key + ": " + header.Value);
47-
48-
Console.WriteLine("\nJSON Response:\n");
49-
Console.WriteLine(JsonPrettyPrint(result.jsonResult));
50-
}
51-
else
52-
{
53-
Console.WriteLine("Invalid Bing Search API subscription key!");
54-
Console.WriteLine("Please paste yours into the source code.");
55-
}
27+
Console.OutputEncoding = Encoding.UTF8;
28+
Dictionary<String, String> relevantHeaders = new Dictionary<String, String>();
5629

57-
Console.Write("\nPress Enter to exit ");
58-
Console.ReadLine();
59-
}
30+
Console.WriteLine("Searching images for: " + query);
6031

61-
/// <summary>
62-
/// Performs a Bing Image search and return the results as a SearchResult.
63-
/// </summary>
64-
static SearchResult BingImageSearch(string searchQuery)
65-
{
6632
// Construct the URI of the search request
67-
var uriQuery = uriBase + "?q=" + Uri.EscapeDataString(searchQuery);
33+
var uriQuery = endpoint + "?q=" + Uri.EscapeDataString(query);
6834

6935
// Perform the Web request and get the response
7036
WebRequest request = HttpWebRequest.Create(uriQuery);
71-
request.Headers["Ocp-Apim-Subscription-Key"] = accessKey;
37+
request.Headers["Ocp-Apim-Subscription-Key"] = subscriptionKey;
7238
HttpWebResponse response = (HttpWebResponse)request.GetResponseAsync().Result;
7339
string json = new StreamReader(response.GetResponseStream()).ReadToEnd();
7440

75-
// Create result object for return
76-
var searchResult = new SearchResult()
77-
{
78-
jsonResult = json,
79-
relevantHeaders = new Dictionary<String, String>()
80-
};
81-
8241
// Extract Bing HTTP headers
8342
foreach (String header in response.Headers)
8443
{
8544
if (header.StartsWith("BingAPIs-") || header.StartsWith("X-MSEdge-"))
86-
searchResult.relevantHeaders[header] = response.Headers[header];
45+
relevantHeaders[header] = response.Headers[header];
8746
}
8847

89-
return searchResult;
90-
}
91-
92-
/// <summary>
93-
/// Formats the given JSON string by adding line breaks and indents.
94-
/// </summary>
95-
/// <param name="json">The raw JSON string to format.</param>
96-
/// <returns>The formatted JSON string.</returns>
97-
static string JsonPrettyPrint(string json)
98-
{
99-
if (string.IsNullOrEmpty(json))
100-
return string.Empty;
101-
102-
json = json.Replace(Environment.NewLine, "").Replace("\t", "");
103-
104-
StringBuilder sb = new StringBuilder();
105-
bool quote = false;
106-
bool ignore = false;
107-
char last = ' ';
108-
int offset = 0;
109-
int indentLength = 2;
110-
111-
foreach (char ch in json)
112-
{
113-
switch (ch)
114-
{
115-
case '"':
116-
if (!ignore) quote = !quote;
117-
break;
118-
case '\\':
119-
if (quote && last != '\\') ignore = true;
120-
break;
121-
}
122-
123-
if (quote)
124-
{
125-
sb.Append(ch);
126-
if (last == '\\' && ignore) ignore = false;
127-
}
128-
else
129-
{
130-
switch (ch)
131-
{
132-
case '{':
133-
case '[':
134-
sb.Append(ch);
135-
sb.Append(Environment.NewLine);
136-
sb.Append(new string(' ', ++offset * indentLength));
137-
break;
138-
case '}':
139-
case ']':
140-
sb.Append(Environment.NewLine);
141-
sb.Append(new string(' ', --offset * indentLength));
142-
sb.Append(ch);
143-
break;
144-
case ',':
145-
sb.Append(ch);
146-
sb.Append(Environment.NewLine);
147-
sb.Append(new string(' ', offset * indentLength));
148-
break;
149-
case ':':
150-
sb.Append(ch);
151-
sb.Append(' ');
152-
break;
153-
default:
154-
if (quote || ch != ' ') sb.Append(ch);
155-
break;
156-
}
157-
}
158-
last = ch;
159-
}
48+
Console.WriteLine("\nRelevant HTTP Headers:\n");
49+
foreach (var header in relevantHeaders)
50+
Console.WriteLine(header.Key + ": " + header.Value);
16051

161-
return sb.ToString().Trim();
52+
Console.WriteLine("\nJSON Response:\n");
53+
dynamic parsedJson = JsonConvert.DeserializeObject(json);
54+
Console.WriteLine(JsonConvert.SerializeObject(parsedJson, Formatting.Indented));
16255
}
16356
}
16457
}

0 commit comments

Comments
 (0)