Skip to content

Commit 4b5fa26

Browse files
authored
Merge pull request #79418 from erhopf/translator-csharp-updates
[CogSvcs]Updating C# Translate sample with classes for JSON.
2 parents 783b96b + bc9fd5e commit 4b5fa26

File tree

4 files changed

+414
-160
lines changed

4 files changed

+414
-160
lines changed

articles/cognitive-services/Translator/quickstart-csharp-detect.md

Lines changed: 123 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -8,18 +8,19 @@ manager: nitinme
88
ms.service: cognitive-services
99
ms.subservice: translator-text
1010
ms.topic: quickstart
11-
ms.date: 06/04/2019
11+
ms.date: 06/13/2019
1212
ms.author: erhopf
1313
---
1414

1515
# Quickstart: Use the Translator Text API to detect text language using C#
1616

17-
In this quickstart, you'll learn how to detect the language of provided text using .NET Core and the Translator Text REST API.
17+
In this quickstart, you'll learn how to detect the language of provided text using .NET Core, C# 7.1 or later, and the Translator Text REST API.
1818

1919
This quickstart requires an [Azure Cognitive Services account](https://docs.microsoft.com/azure/cognitive-services/cognitive-services-apis-create-account) with a Translator Text resource. If you don't have an account, you can use the [free trial](https://azure.microsoft.com/try/cognitive-services/) to get a subscription key.
2020

2121
## Prerequisites
2222

23+
* C# 7.1 or later
2324
* [.NET SDK](https://www.microsoft.com/net/learn/dotnet/hello-world-tutorial)
2425
* [Json.NET NuGet Package](https://www.nuget.org/packages/Newtonsoft.Json/)
2526
* [Visual Studio](https://visualstudio.microsoft.com/downloads/), [Visual Studio Code](https://code.visualstudio.com/download), or your favorite text editor
@@ -42,6 +43,18 @@ Next, you'll need to install Json.Net. From your project's directory, run:
4243
dotnet add package Newtonsoft.Json --version 11.0.2
4344
```
4445

46+
## Select the C# language version
47+
48+
This quickstart requires C# 7.1 or later. There are a few ways to change the C# version for your project. In this guide, we'll show you how to adjust the `detect-sample.csproj` file. For all available options, such as changing the language in Visual Studio, see [Select the C# language version](https://docs.microsoft.com/dotnet/csharp/language-reference/configure-language-version).
49+
50+
Open your project, then open `detect-sample.csproj`. Make sure that `LangVersion` is set to 7.1 or later. If there isn't a property group for the language version, add these lines:
51+
52+
```xml
53+
<PropertyGroup>
54+
<LangVersion>7.1</LangVersion>
55+
</PropertyGroup>
56+
```
57+
4558
## Add required namespaces to your project
4659

4760
The `dotnet new console` command that you ran earlier created a project, including `Program.cs`. This file is where you'll put your application code. Open `Program.cs`, and replace the existing using statements. These statements ensure that you have access to all the types required to build and run the sample app.
@@ -50,15 +63,42 @@ The `dotnet new console` command that you ran earlier created a project, includi
5063
using System;
5164
using System.Net.Http;
5265
using System.Text;
66+
using System.Threading.Tasks;
67+
// Install Newtonsoft.Json with NuGet
5368
using Newtonsoft.Json;
5469
```
5570

71+
## Create classes for the JSON response
72+
73+
Next, we're going to create a class that's used when deserializing the JSON response returned by the Translator Text API.
74+
75+
```csharp
76+
/// <summary>
77+
/// The C# classes that represents the JSON returned by the Translator Text API.
78+
/// </summary>
79+
public class DetectResult
80+
{
81+
public string Language { get; set; }
82+
public float Score { get; set; }
83+
public bool IsTranslationSupported { get; set; }
84+
public bool IsTransliterationSupported { get; set; }
85+
public AltTranslations[] Alternatives { get; set; }
86+
}
87+
public class AltTranslations
88+
{
89+
public string Language { get; set; }
90+
public float Score { get; set; }
91+
public bool IsTranslationSupported { get; set; }
92+
public bool IsTransliterationSupported { get; set; }
93+
}
94+
```
95+
5696
## Create a function to detect the source text's language
5797

58-
Within the `Program` class, create a function called `Detect`. This class encapsulates the code used to call the Detect resource and prints the result to console.
98+
Within the `Program` class, create a function called `DetectTextRequest()`. This class encapsulates the code used to call the Detect resource and prints the result to console.
5999

60100
```csharp
61-
static void Detect()
101+
static public async Task DetectTextRequest(string subscriptionKey, string host, string route, string inputText)
62102
{
63103
/*
64104
* The code for your call to the translation service will be added to this
@@ -67,20 +107,12 @@ static void Detect()
67107
}
68108
```
69109

70-
## Set the subscription key, host name, and path
71-
72-
Add these lines to the `Detect` function.
73-
74-
```csharp
75-
string host = "https://api.cognitive.microsofttranslator.com";
76-
string route = "/detect?api-version=3.0";
77-
string subscriptionKey = "YOUR_SUBSCRIPTION_KEY";
78-
```
110+
## Serialize the detect request
79111

80112
Next, we need to create and serialize the JSON object that includes the text that will undergo language detection.
81113

82114
```csharp
83-
System.Object[] body = new System.Object[] { new { Text = @"Salve mondo!" } };
115+
System.Object[] body = new System.Object[] { new { Text = inputText } };
84116
var requestBody = JsonConvert.SerializeObject(body);
85117
```
86118

@@ -110,42 +142,53 @@ Inside the `HttpRequestMessage` you'll:
110142
Add this code to the `HttpRequestMessage`:
111143

112144
```csharp
113-
// Set the method to POST
145+
// Build the request.
114146
request.Method = HttpMethod.Post;
115-
116-
// Construct the full URI
147+
// Construct the URI and add headers.
117148
request.RequestUri = new Uri(host + route);
118-
119-
// Add the serialized JSON object to your request
120149
request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
121-
122-
// Add the authorization header
123150
request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
124151

125-
// Send request, get response
126-
var response = client.SendAsync(request).Result;
127-
var jsonResponse = response.Content.ReadAsStringAsync().Result;
128-
129-
// Pretty print the response
130-
Console.WriteLine(PrettyPrint(jsonResponse));
131-
Console.WriteLine("Press any key to continue.");
132-
```
133-
134-
To print the response with "Pretty Print" (formatting for the response), add this function to your Program class:
135-
```
136-
static string PrettyPrint(string s)
152+
// Send the request and get response.
153+
HttpResponseMessage response = await client.SendAsync(request).ConfigureAwait(false);
154+
// Read response as a string.
155+
string result = await response.Content.ReadAsStringAsync();
156+
// Deserialize the response using the classes created earlier.
157+
DetectResult[] deserializedOutput = JsonConvert.DeserializeObject<DetectResult[]>(result);
158+
// Iterate over the deserialized response.
159+
foreach (DetectResult o in deserializedOutput)
137160
{
138-
return JsonConvert.SerializeObject(JsonConvert.DeserializeObject(s), Formatting.Indented);
161+
Console.WriteLine("The detected language is '{0}'. Confidence is: {1}.\nTranslation supported: {2}.\nTransliteration supported: {3}.\n",
162+
o.Language, o.Score, o.IsTranslationSupported, o.IsTransliterationSupported);
163+
// Create a counter
164+
int counter = 0;
165+
// Iterate over alternate translations.
166+
foreach (AltTranslations a in o.Alternatives)
167+
{
168+
counter++;
169+
Console.WriteLine("Alternative {0}", counter);
170+
Console.WriteLine("The detected language is '{0}'. Confidence is: {1}.\nTranslation supported: {2}.\nTransliteration supported: {3}.\n",
171+
a.Language, a.Score, a.IsTranslationSupported, a.IsTransliterationSupported);
172+
}
139173
}
140174
```
141175

142176
## Put it all together
143177

144-
The last step is to call `Detect()` in the `Main` function. Locate `static void Main(string[] args)` and add these lines:
178+
The last step is to call `DetectTextRequest()` in the `Main` function. Locate `static void Main(string[] args)` and replace it with this code:
145179

146180
```csharp
147-
Detect();
148-
Console.ReadLine();
181+
static async Task Main(string[] args)
182+
{
183+
// This is our main function.
184+
// Output languages are defined in the route.
185+
// For a complete list of options, see API reference.
186+
string subscriptionKey = "YOUR_TRANSLATOR_TEXT_KEY_GOES_HERE";
187+
string host = "https://api.cognitive.microsofttranslator.com";
188+
string route = "/detect?api-version=3.0";
189+
string breakSentenceText = @"How are you doing today? The weather is pretty pleasant. Have you been to the movies lately?";
190+
await DetectTextRequest(subscriptionKey, host, route, breakSentenceText);
191+
}
149192
```
150193

151194
## Run the sample app
@@ -158,30 +201,51 @@ dotnet run
158201

159202
## Sample response
160203

161-
Find the country/region abbreviation in this [list of languages](https://docs.microsoft.com/azure/cognitive-services/translator/language-support).
204+
After you run the sample, you should see the following printed to terminal:
205+
206+
> [!NOTE]
207+
> Find the country/region abbreviation in this [list of languages](https://docs.microsoft.com/azure/cognitive-services/translator/language-support).
208+
209+
```bash
210+
The detected language is 'en'. Confidence is: 1.
211+
Translation supported: True.
212+
Transliteration supported: False.
213+
214+
Alternative 1
215+
The detected language is 'fil'. Confidence is: 0.82.
216+
Translation supported: True.
217+
Transliteration supported: False.
218+
219+
Alternative 2
220+
The detected language is 'ro'. Confidence is: 1.
221+
Translation supported: True.
222+
Transliteration supported: False.
223+
```
224+
225+
This message is built from the raw JSON, which will look like this:
162226

163227
```json
164-
[
165-
{
166-
"language": "it",
167-
"score": 1.0,
168-
"isTranslationSupported": true,
169-
"isTransliterationSupported": false,
170-
"alternatives": [
171-
{
172-
"language": "pt",
173-
"score": 1.0,
174-
"isTranslationSupported": true,
175-
"isTransliterationSupported": false
176-
},
177-
{
178-
"language": "en",
179-
"score": 1.0,
180-
"isTranslationSupported": true,
181-
"isTransliterationSupported": false
182-
}
183-
]
184-
}
228+
[
229+
{
230+
"language":"en",
231+
"score":1.0,
232+
"isTranslationSupported":true,
233+
"isTransliterationSupported":false,
234+
"alternatives":[
235+
{
236+
"language":"fil",
237+
"score":0.82,
238+
"isTranslationSupported":true,
239+
"isTransliterationSupported":false
240+
},
241+
{
242+
"language":"ro",
243+
"score":1.0,
244+
"isTranslationSupported":true,
245+
"isTransliterationSupported":false
246+
}
247+
]
248+
}
185249
]
186250
```
187251

0 commit comments

Comments
 (0)