├── BreakSentence.cs ├── Detect.cs ├── DictionaryExamples.cs ├── DictionaryLookup.cs ├── LICENSE.txt ├── Languages.cs ├── README.md ├── Translate.cs └── Transliterate.cs /BreakSentence.cs: -------------------------------------------------------------------------------- 1 | // This sample uses C# 7.1 or later for async/await. 2 | 3 | using System; 4 | using System.Net.Http; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | // Install Newtonsoft.Json with NuGet 8 | using Newtonsoft.Json; 9 | 10 | namespace BreakSentenceSample 11 | { 12 | /// 13 | /// The C# classes that represents the JSON returned by the Translator Text API. 14 | /// 15 | public class BreakSentenceResult 16 | { 17 | public int[] SentLen { get; set; } 18 | public DetectedLanguage DetectedLanguage { get; set; } 19 | } 20 | 21 | public class DetectedLanguage 22 | { 23 | public string Language { get; set; } 24 | public float Score { get; set; } 25 | } 26 | 27 | class Program 28 | { 29 | private const string key_var = "TRANSLATOR_TEXT_SUBSCRIPTION_KEY"; 30 | private static readonly string subscriptionKey = Environment.GetEnvironmentVariable(key_var); 31 | 32 | private const string endpoint_var = "TRANSLATOR_TEXT_ENDPOINT"; 33 | private static readonly string endpoint = Environment.GetEnvironmentVariable(endpoint_var); 34 | 35 | static Program() 36 | { 37 | if (null == subscriptionKey) 38 | { 39 | throw new Exception("Please set/export the environment variable: " + key_var); 40 | } 41 | if (null == endpoint) 42 | { 43 | throw new Exception("Please set/export the environment variable: " + endpoint_var); 44 | } 45 | } 46 | 47 | // Async call to the Translator Text API 48 | static public async Task BreakSentenceRequest(string subscriptionKey, string endpoint, string route, string inputText) 49 | { 50 | object[] body = new object[] { new { Text = inputText } }; 51 | var requestBody = JsonConvert.SerializeObject(body); 52 | 53 | using (var client = new HttpClient()) 54 | using (var request = new HttpRequestMessage()) 55 | { 56 | // Build the request. 57 | request.Method = HttpMethod.Post; 58 | request.RequestUri = new Uri(endpoint + route); 59 | request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json"); 60 | request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey); 61 | 62 | // Send the request and get response. 63 | HttpResponseMessage response = await client.SendAsync(request).ConfigureAwait(false); 64 | // Read response as a string. 65 | string result = await response.Content.ReadAsStringAsync(); 66 | BreakSentenceResult[] deserializedOutput = JsonConvert.DeserializeObject(result); 67 | foreach (BreakSentenceResult o in deserializedOutput) 68 | { 69 | Console.WriteLine("The detected language is '{0}'. Confidence is: {1}.", o.DetectedLanguage.Language, o.DetectedLanguage.Score); 70 | Console.WriteLine("The first sentence length is: {0}", o.SentLen[0]); 71 | } 72 | } 73 | } 74 | 75 | static async Task Main(string[] args) 76 | { 77 | // This is our main function. 78 | // Output languages are defined in the route. 79 | // For a complete list of options, see API reference. 80 | // https://docs.microsoft.com/azure/cognitive-services/translator/reference/v3-0-break-sentence 81 | string route = "/breaksentence?api-version=3.0"; 82 | string breakSentenceText = @"How are you doing today? The weather is pretty pleasant. Have you been to the movies lately?"; 83 | await BreakSentenceRequest(subscriptionKey, endpoint, route, breakSentenceText); 84 | Console.WriteLine("Press any key to continue."); 85 | Console.ReadKey(); 86 | } 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /Detect.cs: -------------------------------------------------------------------------------- 1 | // This sample requires C# 7.1 or later for async/await. 2 | 3 | using System; 4 | using System.Net.Http; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | // Install Newtonsoft.Json with NuGet 8 | using Newtonsoft.Json; 9 | 10 | namespace DetectSample 11 | { 12 | /// 13 | /// The C# classes that represents the JSON returned by the Translator Text API. 14 | /// 15 | public class DetectResult 16 | { 17 | public string Language { get; set; } 18 | public float Score { get; set; } 19 | public bool IsTranslationSupported { get; set; } 20 | public bool IsTransliterationSupported { get; set; } 21 | public AltTranslations[] Alternatives { get; set; } 22 | } 23 | public class AltTranslations 24 | { 25 | public string Language { get; set; } 26 | public float Score { get; set; } 27 | public bool IsTranslationSupported { get; set; } 28 | public bool IsTransliterationSupported { get; set; } 29 | } 30 | 31 | class Program 32 | { 33 | private const string key_var = "TRANSLATOR_TEXT_SUBSCRIPTION_KEY"; 34 | private static readonly string subscriptionKey = Environment.GetEnvironmentVariable(key_var); 35 | 36 | private const string endpoint_var = "TRANSLATOR_TEXT_ENDPOINT"; 37 | private static readonly string endpoint = Environment.GetEnvironmentVariable(endpoint_var); 38 | 39 | static Program() 40 | { 41 | if (null == subscriptionKey) 42 | { 43 | throw new Exception("Please set/export the environment variable: " + key_var); 44 | } 45 | if (null == endpoint) 46 | { 47 | throw new Exception("Please set/export the environment variable: " + endpoint_var); 48 | } 49 | } 50 | 51 | // Async call to the Translator Text API 52 | static public async Task DetectTextRequest(string subscriptionKey, string endpoint, string route, string inputText) 53 | { 54 | object[] body = new object[] { new { Text = inputText } }; 55 | var requestBody = JsonConvert.SerializeObject(body); 56 | 57 | using (var client = new HttpClient()) 58 | using (var request = new HttpRequestMessage()) 59 | { 60 | // Build the request. 61 | request.Method = HttpMethod.Post; 62 | request.RequestUri = new Uri(endpoint + route); 63 | request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json"); 64 | request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey); 65 | 66 | // Send the request and get response. 67 | HttpResponseMessage response = await client.SendAsync(request).ConfigureAwait(false); 68 | // Read response as a string. 69 | string result = await response.Content.ReadAsStringAsync(); 70 | DetectResult[] deserializedOutput = JsonConvert.DeserializeObject(result); 71 | //Iterate through the response. 72 | foreach (DetectResult o in deserializedOutput) 73 | { 74 | Console.WriteLine("The detected language is '{0}'. Confidence is: {1}.\nTranslation supported: {2}.\nTransliteration supported: {3}.\n", 75 | o.Language, o.Score, o.IsTranslationSupported, o.IsTransliterationSupported); 76 | int counter = 0; 77 | // Iterate through alternatives. Use counter for alternative number. 78 | foreach (AltTranslations a in o.Alternatives) 79 | { 80 | counter++; 81 | Console.WriteLine("Alternative {0}", counter); 82 | Console.WriteLine("The detected language is '{0}'. Confidence is: {1}.\nTranslation supported: {2}.\nTransliteration supported: {3}.\n", 83 | a.Language, a.Score, a.IsTranslationSupported, a.IsTransliterationSupported); 84 | } 85 | } 86 | } 87 | } 88 | 89 | static async Task Main(string[] args) 90 | { 91 | // This is our main function. 92 | // Output languages are defined in the route. 93 | // For a complete list of options, see API reference. 94 | // https://docs.microsoft.com/azure/cognitive-services/translator/reference/v3-0-detect 95 | string route = "/detect?api-version=3.0"; 96 | string detectSentenceText = @"How are you doing today? The weather is pretty pleasant. Have you been to the movies lately?"; 97 | await DetectTextRequest(subscriptionKey, endpoint, route, detectSentenceText); 98 | Console.WriteLine("Press any key to continue."); 99 | Console.ReadKey(); 100 | } 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /DictionaryExamples.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net.Http; 3 | using System.Text; 4 | // NOTE: Install the Newtonsoft.Json NuGet package. 5 | using Newtonsoft.Json; 6 | 7 | namespace TranslatorTextQuickStart 8 | { 9 | class Program 10 | { 11 | private const string key_var = "TRANSLATOR_TEXT_SUBSCRIPTION_KEY"; 12 | private static readonly string subscriptionKey = Environment.GetEnvironmentVariable(key_var); 13 | 14 | private const string endpoint_var = "TRANSLATOR_TEXT_ENDPOINT"; 15 | private static readonly string endpoint = Environment.GetEnvironmentVariable(endpoint_var); 16 | 17 | static Program() 18 | { 19 | if (null == subscriptionKey) 20 | { 21 | throw new Exception("Please set/export the environment variable: " + key_var); 22 | } 23 | if (null == endpoint) 24 | { 25 | throw new Exception("Please set/export the environment variable: " + endpoint_var); 26 | } 27 | } 28 | 29 | static string route = "/dictionary/examples?api-version=3.0"; 30 | // Translate from English to French. 31 | static string params_ = "&from=en&to=fr"; 32 | 33 | static string uri = endpoint + route + params_; 34 | 35 | static string text = "great"; 36 | static string translation = "formidable"; 37 | 38 | async static void Examples() 39 | { 40 | System.Object[] body = new System.Object[] { new { Text = text, Translation = translation } }; 41 | var requestBody = JsonConvert.SerializeObject(body); 42 | 43 | using (var client = new HttpClient()) 44 | using (var request = new HttpRequestMessage()) 45 | { 46 | request.Method = HttpMethod.Post; 47 | request.RequestUri = new Uri(uri); 48 | request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json"); 49 | request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey); 50 | 51 | var response = await client.SendAsync(request); 52 | var responseBody = await response.Content.ReadAsStringAsync(); 53 | var result = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(responseBody), Formatting.Indented); 54 | 55 | Console.OutputEncoding = UnicodeEncoding.UTF8; 56 | Console.WriteLine(result); 57 | } 58 | } 59 | 60 | static void Main(string[] args) 61 | { 62 | Examples(); 63 | Console.ReadKey(); 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /DictionaryLookup.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net.Http; 3 | using System.Text; 4 | using Newtonsoft.Json; 5 | 6 | namespace AltTranslation 7 | { 8 | class Program 9 | { 10 | private const string key_var = "TRANSLATOR_TEXT_SUBSCRIPTION_KEY"; 11 | private static readonly string subscriptionKey = Environment.GetEnvironmentVariable(key_var); 12 | 13 | private const string endpoint_var = "TRANSLATOR_TEXT_ENDPOINT"; 14 | private static readonly string endpoint = Environment.GetEnvironmentVariable(endpoint_var); 15 | 16 | static Program() 17 | { 18 | if (null == subscriptionKey) 19 | { 20 | throw new Exception("Please set/export the environment variable: " + key_var); 21 | } 22 | if (null == endpoint) 23 | { 24 | throw new Exception("Please set/export the environment variable: " + endpoint_var); 25 | } 26 | } 27 | 28 | static void AltTranslation() 29 | { 30 | string route = "/dictionary/lookup?api-version=3.0&from=en&to=es"; 31 | 32 | System.Object[] body = new System.Object[] { new { Text = @"Elephants" } }; 33 | var requestBody = JsonConvert.SerializeObject(body); 34 | 35 | using (var client = new HttpClient()) 36 | using (var request = new HttpRequestMessage()) 37 | { 38 | // Set the method to POST 39 | request.Method = HttpMethod.Post; 40 | // Construct the full URI 41 | request.RequestUri = new Uri(endpoint + route); 42 | // Add the serialized JSON object to your request 43 | request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json"); 44 | // Add the authorization header 45 | request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey); 46 | // Send request, get response 47 | var response = client.SendAsync(request).Result; 48 | var jsonResponse = response.Content.ReadAsStringAsync().Result; 49 | // Print the response 50 | Console.WriteLine(jsonResponse); 51 | Console.WriteLine("Press any key to continue."); 52 | } 53 | } 54 | static void Main(string[] args) 55 | { 56 | AltTranslation(); 57 | Console.ReadKey(); 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Microsoft Corporation. All rights reserved. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE 22 | 23 | Third Party Programs: The software may include third party programs that Microsoft, 24 | not the third party, licenses to you under this agreement. Notices, if any, for the 25 | third party programs are included for your information only. 26 | -------------------------------------------------------------------------------- /Languages.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net.Http; 3 | using System.Text; 4 | using Newtonsoft.Json; 5 | 6 | namespace GetLanguages 7 | { 8 | class Program 9 | { 10 | private const string endpoint_var = "TRANSLATOR_TEXT_ENDPOINT"; 11 | private static readonly string endpoint = Environment.GetEnvironmentVariable(endpoint_var); 12 | 13 | static Program() 14 | { 15 | if (null == endpoint) 16 | { 17 | throw new Exception("Please set/export the environment variable: " + endpoint_var); 18 | } 19 | } 20 | 21 | static void GetLanguages() 22 | { 23 | string route = "/languages?api-version=3.0"; 24 | 25 | using (var client = new HttpClient()) 26 | using (var request = new HttpRequestMessage()) 27 | { 28 | // Set the method to GET 29 | request.Method = HttpMethod.Get; 30 | // Construct the full URI 31 | request.RequestUri = new Uri(endpoint + route); 32 | // Send request, get response 33 | var response = client.SendAsync(request).Result; 34 | var jsonResponse = response.Content.ReadAsStringAsync().Result; 35 | // Print the response 36 | Console.WriteLine(jsonResponse); 37 | Console.WriteLine("Press any key to continue."); 38 | } 39 | } 40 | static void Main(string[] args) 41 | { 42 | GetLanguages(); 43 | Console.ReadKey(); 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | --- 2 | page_type: sample 3 | name: Microsoft Translator C# samples (v3) 4 | description: This repository includes C# code samples for Microsoft Translator. 5 | urlFragment: translator-c-sharp-v3 6 | languages: 7 | - csharp 8 | products: 9 | - azure 10 | - azure-cognitive-services 11 | - azure-translator 12 | --- 13 | 14 | # Translator API V3 - .NET Core Samples, C# 15 | 16 | This repository includes .NET Core samples for Microsoft Translator. Each sample corresponds to a **Quickstart** activity on [doc.microsoft.com](https://docs.microsoft.com/azure/cognitive-services/translator/), including: 17 | 18 | * Translating text 19 | * Transliterating text 20 | * Identifying the language of source text 21 | * Getting alternate translations 22 | * Getting a complete list of supported languages 23 | * Determining sentence length 24 | 25 | [Get started with the Translator quickstart](https://docs.microsoft.com/azure/cognitive-services/translator/quickstart-translator). 26 | 27 | ## Prerequisites 28 | 29 | Here's what you'll need before you use these samples: 30 | 31 | * [.NET Core 3.1 SDK](https://dotnet.microsoft.com/download) 32 | * [Json.NET NuGet Package](https://www.nuget.org/packages/Newtonsoft.Json/) 33 | * [Visual Studio](https://visualstudio.microsoft.com/downloads/), [Visual Studio Code](https://code.visualstudio.com/download), or your favorite text editor 34 | * An Azure subscription - [Sign-up for a free account](https://docs.microsoft.com/azure/cognitive-services/translator/translator-text-how-to-signup)! 35 | * A Translator resource - [Create a Translator resource](https://ms.portal.azure.com/#create/Microsoft.CognitiveServicesTextTranslation) 36 | 37 | ## Code samples 38 | 39 | This repository includes a sample for each of the methods made available by the Microsoft Translator API v3. To use each of the samples, follow these instructions: 40 | 41 | * Create a new project: `dotnet new console -o your_project_name` 42 | * Copy the code from one of the samples into `Program.cs`. 43 | * Set your subscription key. 44 | * Run the program from the project directory: `dotnet run`. 45 | 46 | ## Resources 47 | 48 | * [What is Translator?](https://docs.microsoft.com/azure/cognitive-services/translator/translator-info-overview) 49 | * [v3 Translator API Reference](https://docs.microsoft.com/azure/cognitive-services/translator/) 50 | * [Supported languages](https://docs.microsoft.com/azure/cognitive-services/translator/language-support) 51 | -------------------------------------------------------------------------------- /Translate.cs: -------------------------------------------------------------------------------- 1 | // This sample requires C# 7.1 or later for async/await. 2 | 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Net.Http; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | // Install Newtonsoft.Json with NuGet 9 | using Newtonsoft.Json; 10 | 11 | namespace TranslateTextSample 12 | { 13 | /// 14 | /// The C# classes that represents the JSON returned by the Translator Text API. 15 | /// 16 | public class TranslationResult 17 | { 18 | public DetectedLanguage DetectedLanguage { get; set; } 19 | public TextResult SourceText { get; set; } 20 | public Translation[] Translations { get; set; } 21 | } 22 | 23 | public class DetectedLanguage 24 | { 25 | public string Language { get; set; } 26 | public float Score { get; set; } 27 | } 28 | 29 | public class TextResult 30 | { 31 | public string Text { get; set; } 32 | public string Script { get; set; } 33 | } 34 | 35 | public class Translation 36 | { 37 | public string Text { get; set; } 38 | public TextResult Transliteration { get; set; } 39 | public string To { get; set; } 40 | public Alignment Alignment { get; set; } 41 | public SentenceLength SentLen { get; set; } 42 | } 43 | 44 | public class Alignment 45 | { 46 | public string Proj { get; set; } 47 | } 48 | 49 | public class SentenceLength 50 | { 51 | public int[] SrcSentLen { get; set; } 52 | public int[] TransSentLen { get; set; } 53 | } 54 | 55 | class Program 56 | { 57 | 58 | private const string region_var = "TRANSLATOR_SERVICE_REGION"; 59 | private static readonly string region = Environment.GetEnvironmentVariable(region_var); 60 | 61 | private const string key_var = "TRANSLATOR_TEXT_SUBSCRIPTION_KEY"; 62 | private static readonly string subscriptionKey = Environment.GetEnvironmentVariable(key_var); 63 | 64 | private const string endpoint_var = "TRANSLATOR_TEXT_ENDPOINT"; 65 | private static readonly string endpoint = Environment.GetEnvironmentVariable(endpoint_var); 66 | 67 | static Program() 68 | { 69 | if (null == region) 70 | { 71 | throw new Exception("Please set/export the environment variable: " + region_var); 72 | } 73 | if (null == subscriptionKey) 74 | { 75 | throw new Exception("Please set/export the environment variable: " + key_var); 76 | } 77 | if (null == endpoint) 78 | { 79 | throw new Exception("Please set/export the environment variable: " + endpoint_var); 80 | } 81 | } 82 | 83 | // Async call to the Translator Text API 84 | static public async Task TranslateTextRequest(string subscriptionKey, string endpoint, string route, string inputText) 85 | { 86 | object[] body = new object[] { new { Text = inputText } }; 87 | var requestBody = JsonConvert.SerializeObject(body); 88 | 89 | using(var client = new HttpClient()) 90 | using(var request = new HttpRequestMessage()) 91 | { 92 | // Build the request. 93 | request.Method = HttpMethod.Post; 94 | request.RequestUri = new Uri(endpoint + route); 95 | request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json"); 96 | request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey); 97 | request.Headers.Add("Ocp-Apim-Subscription-Region", region); 98 | 99 | // Send the request and get response. 100 | HttpResponseMessage response = await client.SendAsync(request).ConfigureAwait(false); 101 | // Read response as a string. 102 | string result = await response.Content.ReadAsStringAsync(); 103 | TranslationResult[] deserializedOutput = JsonConvert.DeserializeObject(result); 104 | // Iterate over the deserialized results. 105 | foreach (TranslationResult o in deserializedOutput) 106 | { 107 | // Print the detected input languge and confidence score. 108 | Console.WriteLine("Detected input language: {0}\nConfidence score: {1}\n", o.DetectedLanguage.Language, o.DetectedLanguage.Score); 109 | // Iterate over the results and print each translation. 110 | foreach (Translation t in o.Translations) 111 | { 112 | Console.WriteLine("Translated to {0}: {1}", t.To, t.Text); 113 | } 114 | } 115 | } 116 | } 117 | 118 | static async Task Main(string[] args) 119 | { 120 | // This is our main function. 121 | // Output languages are defined in the route. 122 | // For a complete list of options, see API reference. 123 | // https://docs.microsoft.com/azure/cognitive-services/translator/reference/v3-0-translate 124 | string route = "/translate?api-version=3.0&to=de&to=it&to=ja&to=th"; 125 | // Prompts you for text to translate. If you'd prefer, you can 126 | // provide a string as textToTranslate. 127 | Console.Write("Type the phrase you'd like to translate? "); 128 | string textToTranslate = Console.ReadLine(); 129 | await TranslateTextRequest(subscriptionKey, endpoint, route, textToTranslate); 130 | Console.WriteLine("Press any key to continue."); 131 | Console.ReadKey(); 132 | } 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /Transliterate.cs: -------------------------------------------------------------------------------- 1 | // This sample requires C# 7.1 or later for async/await. 2 | 3 | using System; 4 | using System.Net.Http; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | // Install Newtonsoft.Json with NuGet 8 | using Newtonsoft.Json; 9 | 10 | namespace TransliterateTextSample 11 | { 12 | /// 13 | /// The C# classes that represents the JSON returned by the Translator Text API. 14 | /// 15 | public class TransliterationResult 16 | { 17 | public string Text { get; set; } 18 | public string Script { get; set; } 19 | } 20 | 21 | class Program 22 | { 23 | private const string key_var = "TRANSLATOR_TEXT_SUBSCRIPTION_KEY"; 24 | private static readonly string subscriptionKey = Environment.GetEnvironmentVariable(key_var); 25 | 26 | private const string endpoint_var = "TRANSLATOR_TEXT_ENDPOINT"; 27 | private static readonly string endpoint = Environment.GetEnvironmentVariable(endpoint_var); 28 | 29 | static Program() 30 | { 31 | if (null == subscriptionKey) 32 | { 33 | throw new Exception("Please set/export the environment variable: " + key_var); 34 | } 35 | if (null == endpoint) 36 | { 37 | throw new Exception("Please set/export the environment variable: " + endpoint_var); 38 | } 39 | } 40 | 41 | // Async call to the Translator Text API 42 | static public async Task TransliterateTextRequest(string subscriptionKey, string endpoint, string route, string inputText) 43 | { 44 | object[] body = new object[] { new { Text = inputText } }; 45 | var requestBody = JsonConvert.SerializeObject(body); 46 | 47 | using (var client = new HttpClient()) 48 | using (var request = new HttpRequestMessage()) 49 | { 50 | // Build the request. 51 | request.Method = HttpMethod.Post; 52 | request.RequestUri = new Uri(endpoint + route); 53 | request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json"); 54 | request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey); 55 | 56 | // Send the request and get response. 57 | HttpResponseMessage response = await client.SendAsync(request).ConfigureAwait(false); 58 | // Read response as a string. 59 | string result = await response.Content.ReadAsStringAsync(); 60 | TransliterationResult[] deserializedOutput = JsonConvert.DeserializeObject(result); 61 | // Iterate over the deserialized results. 62 | foreach (TransliterationResult o in deserializedOutput) 63 | { 64 | Console.WriteLine("Transliterated to {0} script: {1}", o.Script, o.Text); 65 | } 66 | } 67 | } 68 | 69 | static async Task Main(string[] args) 70 | { 71 | // This is our main function. 72 | // Output languages are defined in the route. 73 | // For a complete list of options, see API reference. 74 | // https://docs.microsoft.com/azure/cognitive-services/translator/reference/v3-0-transliterate 75 | string route = "/transliterate?api-version=3.0&language=ja&fromScript=jpan&toScript=latn"; 76 | string textToTransliterate = @"こんにちは"; 77 | await TransliterateTextRequest(subscriptionKey, endpoint, route, textToTransliterate); 78 | Console.WriteLine("Press any key to continue."); 79 | Console.ReadKey(); 80 | } 81 | } 82 | } 83 | --------------------------------------------------------------------------------