Skip to content

Commit e1dbd3f

Browse files
authored
Merge pull request #115591 from dksimpson/DKS-US1712683-bing-visual-search
[Cog Svcs] Refresh Bing Visual Search REST API quickstarts
2 parents ebb1fb8 + 20cda2c commit e1dbd3f

File tree

7 files changed

+206
-194
lines changed

7 files changed

+206
-194
lines changed

articles/cognitive-services/bing-visual-search/quickstarts/csharp.md

Lines changed: 90 additions & 90 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,13 @@ manager: nitinme
99
ms.service: cognitive-services
1010
ms.subservice: bing-visual-search
1111
ms.topic: quickstart
12-
ms.date: 12/17/2019
12+
ms.date: 05/22/2020
1313
ms.author: scottwhi
1414
---
1515

1616
# Quickstart: Get image insights using the Bing Visual Search REST API and C#
1717

18-
This quickstart demonstrates how to upload an image to the Bing Visual Search API and to view the insights that it returns.
18+
This quickstart demonstrates how to upload an image to the Bing Visual Search API and view the insights that it returns.
1919

2020
## Prerequisites
2121

@@ -37,15 +37,15 @@ This quickstart demonstrates how to upload an image to the Bing Visual Search AP
3737
using System.Collections.Generic;
3838
```
3939

40-
2. Add variables for your subscription key, endpoint, and path to the image you want to upload. `uriBase` can be the global endpoint below, or the [custom subdomain](../../../cognitive-services/cognitive-services-custom-subdomains.md) endpoint displayed in the Azure portal for your resource:
40+
2. Add variables for your subscription key, endpoint, and path to the image you want to upload. For the `uriBase` value, you can use the global endpoint in the following code, or use the [custom subdomain](../../../cognitive-services/cognitive-services-custom-subdomains.md) endpoint displayed in the Azure portal for your resource.
4141

4242
```csharp
4343
const string accessKey = "<my_subscription_key>";
4444
const string uriBase = "https://api.cognitive.microsoft.com/bing/v7.0/images/visualsearch";
4545
static string imagePath = @"<path_to_image>";
4646
```
4747

48-
3. Create a method named `GetImageFileName()` to get the path for your image:
48+
3. Create a method named `GetImageFileName()` to get the path for your image.
4949

5050
```csharp
5151
static string GetImageFileName(string path)
@@ -54,7 +54,7 @@ This quickstart demonstrates how to upload an image to the Bing Visual Search AP
5454
}
5555
```
5656

57-
4. Create a method to get the binary data of the image:
57+
4. Create a method to get the binary data of the image.
5858

5959
```csharp
6060
static byte[] GetImageBinary(string path)
@@ -65,7 +65,7 @@ This quickstart demonstrates how to upload an image to the Bing Visual Search AP
6565

6666
## Build the form data
6767

68-
To upload a local image, you first build the form data to send to the API. The form data must include the `Content-Disposition` header, its `name` parameter must be set to "image", and the `filename` parameter can be set to any string. The contents of the form contain the binary data of the image. The maximum image size you can upload is 1 MB.
68+
1. To upload a local image, first build the form data to send to the API. The form data includes the `Content-Disposition` header, the `name` parameter set to "image", and the `filename` parameter set to the file name of the image. The contents of the form contain the binary data of the image. The maximum image size you can upload is 1 MB.
6969

7070
```
7171
--boundary_1234-abcd
@@ -76,7 +76,7 @@ To upload a local image, you first build the form data to send to the API. The f
7676
--boundary_1234-abcd--
7777
```
7878

79-
1. Add boundary strings to format the POST form data. Boundary strings determine the start, end, and newline characters for the data:
79+
2. Add boundary strings to format the POST form data. Boundary strings determine the start, end, and newline characters for the data.
8080

8181
```csharp
8282
// Boundary strings for form data in body of POST.
@@ -86,14 +86,14 @@ To upload a local image, you first build the form data to send to the API. The f
8686
static string EndBoundaryTemplate = "--{0}--";
8787
```
8888

89-
2. Use the following variables to add parameters to the form data:
89+
3. Use the following variables to add parameters to the form data:
9090

9191
```csharp
9292
const string CONTENT_TYPE_HEADER_PARAMS = "multipart/form-data; boundary={0}";
9393
const string POST_BODY_DISPOSITION_HEADER = "Content-Disposition: form-data; name=\"image\"; filename=\"{0}\"" + CRLF +CRLF;
9494
```
9595

96-
3. Create a function named `BuildFormDataStart()` to create the start of the form data using the boundary strings and image path:
96+
4. Create a function named `BuildFormDataStart()` to create the start of the form data by using the boundary strings and image path.
9797

9898
```csharp
9999
static string BuildFormDataStart(string boundary, string filename)
@@ -107,7 +107,7 @@ To upload a local image, you first build the form data to send to the API. The f
107107
}
108108
```
109109

110-
4. Create a function named `BuildFormDataEnd()` to create the end of the form data using the boundary strings:
110+
5. Create a function named `BuildFormDataEnd()` to create the end of the form data by using the boundary strings.
111111

112112
```csharp
113113
static string BuildFormDataEnd(string boundary)
@@ -122,7 +122,7 @@ To upload a local image, you first build the form data to send to the API. The f
122122

123123
2. Use a `WebRequest` to store your URI, contentType value, and headers.
124124

125-
3. Use `request.GetRequestStream()` to write your form and image data, then get the response. Your function should be similar to the one below:
125+
3. Use `request.GetRequestStream()` to write your form and image data, and then get the response. Your function should be similar to the following code:
126126

127127
```csharp
128128
static string BingImageSearch(string startFormData, string endFormData, byte[] image, string contentTypeValue)
@@ -154,14 +154,14 @@ To upload a local image, you first build the form data to send to the API. The f
154154

155155
## Create the Main method
156156

157-
1. In the `Main` method of your application, get the filename and binary data of your image:
157+
1. In the `Main()` method of your application, get the filename and binary data of your image.
158158

159159
```csharp
160160
var filename = GetImageFileName(imagePath);
161161
var imageBinary = GetImageBinary(imagePath);
162162
```
163163

164-
2. Set up the POST body by formatting the boundary for it. Then call `startFormData()` and `endFormData` to create the form data:
164+
2. Set up the POST body by formatting its boundary. Then, call `BuildFormDataStart()` and `BuildFormDataEnd()` to create the form data.
165165

166166
```csharp
167167
// Set up POST body.
@@ -170,13 +170,13 @@ To upload a local image, you first build the form data to send to the API. The f
170170
var endFormData = BuildFormDataEnd(boundary);
171171
```
172172

173-
3. Create the `ContentType` value by formatting `CONTENT_TYPE_HEADER_PARAMS` and the form data boundary:
173+
3. Create the `ContentType` value by formatting `CONTENT_TYPE_HEADER_PARAMS` and the form data boundary.
174174

175175
```csharp
176176
var contentTypeHdrValue = string.Format(CONTENT_TYPE_HEADER_PARAMS, boundary);
177177
```
178178

179-
4. Get the API response by calling `BingImageSearch()` and print the response:
179+
4. Get the API response by calling `BingImageSearch()`, and then print the response.
180180

181181
```csharp
182182
var json = BingImageSearch(startFormData, endFormData, imageBinary, contentTypeHdrValue);
@@ -187,81 +187,81 @@ To upload a local image, you first build the form data to send to the API. The f
187187

188188
## Using HttpClient
189189

190-
If you use `HttpClient`, you can use the `MultipartFormDataContent` class to build the form data. Just use the following sections of code to replace the corresponding methods in the previous example.
191-
192-
Replace the `Main` method with this code:
193-
194-
```csharp
195-
static void Main()
196-
{
197-
try
198-
{
199-
Console.OutputEncoding = System.Text.Encoding.UTF8;
200-
201-
if (accessKey.Length == 32)
202-
{
203-
if (IsImagePathSet(imagePath))
204-
{
205-
var filename = GetImageFileName(imagePath);
206-
Console.WriteLine("Getting image insights for image: " + filename);
207-
var imageBinary = GetImageBinary(imagePath);
208-
209-
var boundary = string.Format(BoundaryTemplate, Guid.NewGuid());
210-
var json = BingImageSearch(imageBinary, boundary, uriBase, accessKey);
211-
212-
Console.WriteLine("\nJSON Response:\n");
213-
Console.WriteLine(JsonPrettyPrint(json));
214-
}
215-
}
216-
else
217-
{
218-
Console.WriteLine("Invalid Bing Visual Search API subscription key!");
219-
Console.WriteLine("Please paste yours into the source code.");
220-
}
221-
222-
Console.Write("\nPress Enter to exit ");
223-
Console.ReadLine();
224-
}
225-
catch (Exception e)
226-
{
227-
Console.WriteLine(e.Message);
228-
}
229-
}
230-
```
231-
232-
Replace the `BingImageSearch` method with this code:
233-
234-
```csharp
235-
/// <summary>
236-
/// Calls the Bing visual search endpoint and returns the JSON response.
237-
/// </summary>
238-
static string BingImageSearch(byte[] image, string boundary, string uri, string subscriptionKey)
239-
{
240-
var requestMessage = new HttpRequestMessage(HttpMethod.Post, uri);
241-
requestMessage.Headers.Add("Ocp-Apim-Subscription-Key", accessKey);
242-
243-
var content = new MultipartFormDataContent(boundary);
244-
content.Add(new ByteArrayContent(image), "image", "myimage");
245-
requestMessage.Content = content;
246-
247-
var httpClient = new HttpClient();
248-
249-
Task<HttpResponseMessage> httpRequest = httpClient.SendAsync(requestMessage, HttpCompletionOption.ResponseContentRead, CancellationToken.None);
250-
HttpResponseMessage httpResponse = httpRequest.Result;
251-
HttpStatusCode statusCode = httpResponse.StatusCode;
252-
HttpContent responseContent = httpResponse.Content;
253-
254-
string json = null;
255-
256-
if (responseContent != null)
257-
{
258-
Task<String> stringContentsTask = responseContent.ReadAsStringAsync();
259-
json = stringContentsTask.Result;
260-
}
261-
262-
return json;
263-
}
264-
```
190+
If you use `HttpClient`, you can use the `MultipartFormDataContent` class to build the form data. Use the following sections of code to replace the corresponding methods in the previous example:
191+
192+
1. Replace the `Main()` method with the following code:
193+
194+
```csharp
195+
static void Main()
196+
{
197+
try
198+
{
199+
Console.OutputEncoding = System.Text.Encoding.UTF8;
200+
201+
if (accessKey.Length == 32)
202+
{
203+
if (IsImagePathSet(imagePath))
204+
{
205+
var filename = GetImageFileName(imagePath);
206+
Console.WriteLine("Getting image insights for image: " + filename);
207+
var imageBinary = GetImageBinary(imagePath);
208+
209+
var boundary = string.Format(BoundaryTemplate, Guid.NewGuid());
210+
var json = BingImageSearch(imageBinary, boundary, uriBase, accessKey);
211+
212+
Console.WriteLine("\nJSON Response:\n");
213+
Console.WriteLine(JsonPrettyPrint(json));
214+
}
215+
}
216+
else
217+
{
218+
Console.WriteLine("Invalid Bing Visual Search API subscription key!");
219+
Console.WriteLine("Please paste yours into the source code.");
220+
}
221+
222+
Console.Write("\nPress Enter to exit ");
223+
Console.ReadLine();
224+
}
225+
catch (Exception e)
226+
{
227+
Console.WriteLine(e.Message);
228+
}
229+
}
230+
```
231+
232+
2. Replace the `BingImageSearch()` method with the following code:
233+
234+
```csharp
235+
/// <summary>
236+
/// Calls the Bing visual search endpoint and returns the JSON response.
237+
/// </summary>
238+
static string BingImageSearch(byte[] image, string boundary, string uri, string subscriptionKey)
239+
{
240+
var requestMessage = new HttpRequestMessage(HttpMethod.Post, uri);
241+
requestMessage.Headers.Add("Ocp-Apim-Subscription-Key", accessKey);
242+
243+
var content = new MultipartFormDataContent(boundary);
244+
content.Add(new ByteArrayContent(image), "image", "myimage");
245+
requestMessage.Content = content;
246+
247+
var httpClient = new HttpClient();
248+
249+
Task<HttpResponseMessage> httpRequest = httpClient.SendAsync(requestMessage, HttpCompletionOption.ResponseContentRead, CancellationToken.None);
250+
HttpResponseMessage httpResponse = httpRequest.Result;
251+
HttpStatusCode statusCode = httpResponse.StatusCode;
252+
HttpContent responseContent = httpResponse.Content;
253+
254+
string json = null;
255+
256+
if (responseContent != null)
257+
{
258+
Task<String> stringContentsTask = responseContent.ReadAsStringAsync();
259+
json = stringContentsTask.Result;
260+
}
261+
262+
return json;
263+
}
264+
```
265265

266266
## Next steps
267267

articles/cognitive-services/bing-visual-search/quickstarts/go.md

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -9,24 +9,24 @@ manager: nitinme
99
ms.service: cognitive-services
1010
ms.subservice: bing-visual-search
1111
ms.topic: quickstart
12-
ms.date: 12/17/2019
12+
ms.date: 05/22/2020
1313
ms.author: aahi
1414
---
1515

1616
# Quickstart: Get image insights using the Bing Visual Search REST API and Go
1717

18-
This quickstart uses the Go programming language to call the Bing Visual Search API and display results. A POST request uploads an image to the API endpoint. The results include URLs and descriptive information about images similar to the uploaded image.
18+
Use this quickstart to make your first call to the Bing Visual Search API using the Go programming language. A POST request uploads an image to the API endpoint. The results include URLs and descriptive information about images similar to the uploaded image.
1919

2020
## Prerequisites
2121

2222
* Install the [Go binaries](https://golang.org/dl/).
23-
* The go-spew deep pretty printer is used to display results. You can install go-spew with the `$ go get -u https://github.com/davecgh/go-spew` command.
23+
* Install the go-spew deep pretty printer, which is used to display results. To install go-spew, use the `$ go get -u https://github.com/davecgh/go-spew` command.
2424

2525
[!INCLUDE [cognitive-services-bing-visual-search-signup-requirements](../../../../includes/cognitive-services-bing-visual-search-signup-requirements.md)]
2626

2727
## Project and libraries
2828

29-
Create a Go project in your IDE or editor. Then import `net/http` for requests, `ioutil` to read the response, and `encoding/json` to handle the JSON text of results. The `go-spew` library is used to parse JSON results.
29+
Create a Go project in your IDE or editor. Then, import `net/http` for requests, `ioutil` to read the response, and `encoding/json` to handle the JSON text of results. Use the `go-spew` library to parse JSON results.
3030

3131
```go
3232
package main
@@ -105,7 +105,12 @@ type BingAnswer struct {
105105

106106
## Main function and variables
107107

108-
The following code declares the main function and assigns required variables. Confirm that the endpoint is correct and replace the `token` value with a valid subscription key from your Azure account. The `batchNumber` is a GUID required for leading and trailing boundaries of the POST data. The `fileName` variable identifies the image file for the POST. `endpoint` can be the global endpoint below, or the [custom subdomain](../../../cognitive-services/cognitive-services-custom-subdomains.md) endpoint displayed in the Azure portal for your resource:
108+
The following code declares the main function and assigns the required variables:
109+
110+
1. Confirm that the endpoint is correct and replace the `token` value with a valid subscription key from your Azure account.
111+
2. For `batchNumber`, assign a GUID, which is required for the leading and trailing boundaries of the POST data.
112+
3. For `fileName`, assign the image file to use for the POST.
113+
4. For `endpoint`, you can use the global endpoint in the following code, or use the [custom subdomain](../../../cognitive-services/cognitive-services-custom-subdomains.md) endpoint displayed in the Azure portal for your resource.
109114

110115
```go
111116
func main() {
@@ -155,7 +160,12 @@ func main() {
155160

156161
## Boundaries of POST body
157162

158-
A POST request to the Visual Search endpoint requires leading and trailing boundaries enclosing the POST data. The leading boundary includes a batch number, the content type identifier `Content-Disposition: form-data; name="image"; filename=`, plus the filename of the image to POST. The trailing boundary is simply the batch number. These functions are not included in the `main` block:
163+
A POST request to the Visual Search endpoint requires leading and trailing boundaries to enclose the POST data. These functions aren't included in the `main()` block.
164+
165+
The leading boundary includes a batch number, the content type identifier `Content-Disposition: form-data; name="image"; filename=`, and the filename of the image to POST.
166+
167+
The trailing boundary includes the batch number only.
168+
159169

160170
```go
161171
func BuildFormDataStart(batNum string, fileName string) string{
@@ -174,7 +184,7 @@ func BuildFormDataEnd(batNum string) string{
174184
```
175185
## Add image bytes to POST body
176186

177-
This code segment creates the POST request that contains image data:
187+
The following code creates the POST request that contains image data:
178188

179189
```go
180190
func createRequestBody(fileName string, batchNumber string) (*bytes.Buffer, string) {
@@ -222,7 +232,7 @@ resp, err := client.Do(req)
222232

223233
## Handle the response
224234

225-
The `Unmarshall` function extracts information from the JSON text returned by the Visual Search API. The `go-spew` pretty printer displays the results:
235+
The `Unmarshall` function extracts information from the JSON text returned by the Visual Search API. The `go-spew` pretty printer displays the results.
226236

227237
```go
228238
// Create a new answer.
@@ -245,7 +255,7 @@ The `Unmarshall` function extracts information from the JSON text returned by th
245255
246256
## Results
247257

248-
The results identify images similar to the image contained in the POST body. The useful fields are `WebSearchUrl` and `Name`:
258+
The results identify images similar to the image contained in the POST body. The useful fields are `WebSearchUrl` and `Name`.
249259

250260
```go
251261
Value: ([]struct { WebSearchUrl string "json:\"webSearchUrl\""; Name string "json:\"name\"" }) (len=66 cap=94) {

0 commit comments

Comments
 (0)