@@ -63,15 +63,38 @@ The `dotnet new console` command that you ran earlier created a project, includi
63
63
using System ;
64
64
using System .Net .Http ;
65
65
using System .Text ;
66
+ using System .Threading .Tasks ;
67
+ // Install Newtonsoft.Json with NuGet
66
68
using Newtonsoft .Json ;
67
69
```
68
70
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 BreakSentenceResult
80
+ {
81
+ public int [] SentLen { get ; set ; }
82
+ public DetectedLanguage DetectedLanguage { get ; set ; }
83
+ }
84
+
85
+ public class DetectedLanguage
86
+ {
87
+ public string Language { get ; set ; }
88
+ public float Score { get ; set ; }
89
+ }
90
+ ```
91
+
69
92
## Create a function to determine sentence length
70
93
71
- Within the ` Program ` class, create a function called ` BreakSentence ` . This class encapsulates the code used to call the BreakSentence resource and prints the result to console .
94
+ Within the ` Program ` class, create a function called ` BreakSentence ` . This function takes four arguments: ` subscriptionKey ` , ` host ` , ` route ` , and ` inputText ` .
72
95
73
96
``` csharp
74
- static void BreakSentence ( )
97
+ static public async Task BreakSentenceRequest ( string subscriptionKey , string host , string route , string inputText )
75
98
{
76
99
/*
77
100
* The code for your call to the translation service will be added to this
@@ -80,20 +103,12 @@ static void BreakSentence()
80
103
}
81
104
```
82
105
83
- ## Set the subscription key, host name, and path
84
-
85
- Add these lines to the ` BreakSentence ` function. You'll notice that along with the ` api-version ` , you can define the input language. In this sample it's English.
86
-
87
- ``` csharp
88
- string host = " https://api.cognitive.microsofttranslator.com" ;
89
- string route = " /breaksentence?api-version=3.0&language=en" ;
90
- string subscriptionKey = " YOUR_SUBSCRIPTION_KEY" ;
91
- ```
106
+ ## Serialize the Break Sentence request
92
107
93
108
Next, you need to create and serialize the JSON object that includes the text. Keep in mind, you can pass more than one object in the ` body ` array.
94
109
95
110
``` csharp
96
- System . Object [] body = new System . Object [] { new { Text = @" How are you? I am fine. What did you do today? " } };
111
+ object [] body = new object [] { new { Text = inputText } };
97
112
var requestBody = JsonConvert .SerializeObject (body );
98
113
```
99
114
@@ -123,36 +138,48 @@ Inside the `HttpRequestMessage` you'll:
123
138
Add this code to the ` HttpRequestMessage ` :
124
139
125
140
``` csharp
141
+ // Build the request.
126
142
// Set the method to POST
127
143
request .Method = HttpMethod .Post ;
128
-
129
- // Construct the full URI
144
+ // Construct the URI and add headers.
130
145
request .RequestUri = new Uri (host + route );
131
-
132
- // Add the serialized JSON object to your request
133
146
request .Content = new StringContent (requestBody , Encoding .UTF8 , " application/json" );
134
-
135
- // Add the authorization header
136
147
request .Headers .Add (" Ocp-Apim-Subscription-Key" , subscriptionKey );
137
148
138
- // Send request, get response
139
- var response = client .SendAsync (request ).Result ;
140
- var jsonResponse = response .Content .ReadAsStringAsync ().Result ;
141
-
142
- // Print the response
143
- Console .WriteLine (jsonResponse );
144
- Console .WriteLine (" Press any key to continue." );
149
+ // Send the request and get response.
150
+ HttpResponseMessage response = await client .SendAsync (request ).ConfigureAwait (false );
151
+ // Read response as a string.
152
+ string result = await response .Content .ReadAsStringAsync ();
153
+ // Deserialize the response using the classes created earlier.
154
+ BreakSentenceResult [] deserializedOutput = JsonConvert .DeserializeObject <BreakSentenceResult []>(result );
155
+ foreach (BreakSentenceResult o in deserializedOutput )
156
+ {
157
+ Console .WriteLine (" The detected language is '{0}'. Confidence is: {1}." , o .DetectedLanguage .Language , o .DetectedLanguage .Score );
158
+ Console .WriteLine (" The first sentence length is: {0}" , o .SentLen [0 ]);
159
+ }
145
160
```
146
161
147
162
## Put it all together
148
163
149
- The last step is to call ` BreakSentence ()` in the ` Main ` function. Locate ` static void Main(string[] args) ` and add these lines :
164
+ The last step is to call ` BreakSentenceRequest ()` in the ` Main ` function. Locate ` static void Main(string[] args) ` and add replace it with this code :
150
165
151
166
``` csharp
152
- BreakSentence ();
153
- Console .ReadLine ();
167
+ static async Task Main (string [] args )
168
+ {
169
+ // This is our main function.
170
+ // Output languages are defined in the route.
171
+ // For a complete list of options, see API reference.
172
+ string subscriptionKey = " YOUR_TRANSLATOR_TEXT_KEY_GOES_HERE" ;
173
+ string host = " https://api.cognitive.microsofttranslator.com" ;
174
+ string route = " /breaksentence?api-version=3.0" ;
175
+ // Feel free to use any string.
176
+ string breakSentenceText = @" How are you doing today? The weather is pretty pleasant. Have you been to the movies lately?" ;
177
+ await BreakSentenceRequest (subscriptionKey , host , route , breakSentenceText );
178
+ }
154
179
```
155
180
181
+ You'll notice that in ` Main ` , you're declaring ` subscriptionKey ` , ` host ` , ` route ` , and the text to evaluate ` breakSentenceText ` .
182
+
156
183
## Run the sample app
157
184
158
185
That's it, you're ready to run your sample app. From the command line (or terminal session), navigate to your project directory and run:
@@ -163,14 +190,24 @@ dotnet run
163
190
164
191
## Sample response
165
192
193
+ After you run the sample, you should see the following printed to terminal:
194
+
195
+ ``` bash
196
+ The detected language is \' en\' . Confidence is: 1.
197
+ The first sentence length is: 25
198
+ ```
199
+
200
+ This message is built from the raw JSON, which will look like this:
201
+
166
202
``` json
167
203
[
168
204
{
169
- "sentLen" : [
170
- 13 ,
171
- 11 ,
172
- 22
173
- ]
205
+ "detectedLanguage" :
206
+ {
207
+ "language" :" en" ,
208
+ "score" :1.0
209
+ },
210
+ "sentLen" :[25 ,32 ,35 ]
174
211
}
175
212
]
176
213
```
0 commit comments