public async Task GetTranslatedPokemonData_GetsYodaTranslation_IfHabitatIsCave() { // Arrange Fixture fixture = new Fixture(); string pokemonName = fixture.Create <string>(); TranslationResponse translation = fixture.Create <TranslationResponse>(); PokemonSpeciesData speciesData = fixture.Create <PokemonSpeciesData>(); PokemonData data = fixture.Create <PokemonData>(); data.Habitat = "cave"; data.Description = pokemonName; this.mockPokemonDataRepository.Setup(x => x.GetPokemonData(pokemonName)) .ReturnsAsync(speciesData); this.mockPokemonDataParser.Setup(x => x.BuildPokemonData(speciesData)) .Returns(data); this.mockPokemonDataRepository.Setup(x => x.GetTranslation(data.Description, "yoda")) .ReturnsAsync(translation); // Act PokemonData response = await this.pokemonDataService.GetTranslatedPokemonData(pokemonName); // Assert this.mockPokemonDataRepository.Verify(x => x.GetTranslation(pokemonName, "yoda"), Times.Once()); response.Description.Should().BeEquivalentTo(translation.Contents.Translated); }
static TranslationResponse HealthCheck(Configuration conf) { TranslationApi api = new TranslationApi(conf); TranslationResponse response = api.RunHealthCheck(); return(response); }
public async Task Translate(string text, Action <TranslationRequest> requestAction, Action <TranslationResponse> responseAction) { TranslationResponse response; try { var request = new TranslationRequest(); request.From = (TranslationLanguage)Model.FromLanguageId; request.To = (TranslationLanguage)Model.ToLanguageId; request.Items.Add(new TranslationItem { Text = text }); requestAction?.Invoke(request); response = await _translationApiClient.Send(request, CancellationToken.None); } catch (Exception ex) { response = new TranslationResponse(); response.IsSuccess = false; response.ErrorMessage = ex.Message; } responseAction?.Invoke(response); }
private void AddTranslatedTextToPopup(TranslationResponse response) { AddTranslatedText(response); var text = response?.TranslatedResults.FirstOrDefault()?.Translations.FirstOrDefault()?.Text; SetPopUpText(text); }
// handlers private void TranslateSuccessEventHandler(TranslationResponse value) { ResetState(true); foreach (var translation in value.data.translations) { _textNetworkResultInputField.text += translation.translatedText + "\n---------\n"; } }
public void TranslationTranslateGetTest() { TranslationResponse response = new TranslationResponse(); List <string> sample = new List <string>(); sample.Add("this is a test"); response = translationApi.TranslationTranslateGet(sample, "en", "fr", null, null, true, false, null, null, false, null, null, false, null, null); Assert.IsNotNull(response.Outputs); }
public async Task <JsonResult> Translate([FromBody] TranslationRequest request) { var response = new TranslationResponse(); response.Translation = await translationService.Translate( request.Text, request.To, request.From); return(Json(response)); }
static void Main(string[] args) { // add your ClientId and ClientSecret Configuration conf = new Configuration(); conf.ClientId = ""; conf.ClientSecret = ""; if (string.IsNullOrEmpty(conf.ClientId) || string.IsNullOrEmpty(conf.ClientSecret)) { throw new Exception("Please, get and set your ClientId and ClientSecret. https://dashboard.groupdocs.cloud/#/"); } TranslationResponse hcResponse = new TranslationResponse(); TextResponse textResponse = new TextResponse(); NET.Model.FileInfo fileInfo = new NET.Model.FileInfo(); TextInfo textInfo = new TextInfo(); Dictionary <string, string[]> pairs = new Dictionary <string, string[]>(); Console.WriteLine("Example #1:\nDocument translation of file in GroupDocs Storage"); TranslateDocument(conf); Console.WriteLine("Example #2:\nText translation"); textResponse = TranslateText(conf); Console.WriteLine(textResponse); Console.WriteLine("Example #3:\nHealth check"); hcResponse = HealthCheck(conf); Console.WriteLine(hcResponse); Console.WriteLine("Example #4:\nGet structure of document request"); fileInfo = GetDocRequest(conf); Console.WriteLine(fileInfo.ToString()); Console.WriteLine("Example #5:\nGet structure of text request"); textInfo = GetTextRequest(conf); Console.WriteLine(textInfo.ToString()); Console.WriteLine("Example #6:\nGet language pairs"); pairs = GetLanguagePairs(conf); foreach (var key in pairs.Keys) { Console.WriteLine(key + ": "); foreach (var value in pairs[key]) { Console.WriteLine("- " + value); } } }
private void HandleTranslationResponse(TranslationResponse message) { lock ( _sync ) { if (_transactionHandles.TryGetValue(message.Id, out var result)) { result.SetCompleted(message.TranslatedTexts, null, StatusCode.OK); _transactionHandles.Remove(message.Id); } } }
private Promise <string> QueryForTranslation(string data, string from, string to) { Deferred <string> deferred = new Deferred <string>(); // register callback support (required for WebClient) if (ServicePointManager.ServerCertificateValidationCallback == null) { AddCertificateChainValidation(); } // get an access token using (WebClient client = new WebClient()) { //client.Headers.Add("Authorization", "Bearer " + accessToken); client.DownloadDataCompleted += (object sender, DownloadDataCompletedEventArgs e) => { try { if (e.Cancelled) { _status = StatusOptions.failed; deferred.Reject("web call was cancelled."); } else if (e.Error != null) { _status = StatusOptions.failed; deferred.Reject(e.Error.Message); } else { string response_string = System.Text.Encoding.Default.GetString(e.Result); string encapsulated = "<xml>" + response_string + "</xml>"; XmlSerializer serializer = new XmlSerializer(typeof(TranslationResponse)); using (TextReader reader = new StringReader(encapsulated)) { TranslationResponse result = (TranslationResponse)serializer.Deserialize(reader); deferred.Resolve(result.text); } } } catch (Exception ex) { _status = StatusOptions.failed; deferred.Reject(ex.Message); } Reset(); }; string parameters = "appid=Bearer " + Uri.EscapeUriString(accessToken) + "&text=" + Uri.EscapeUriString(data) + "&from=" + Uri.EscapeUriString(from) + "&to=" + Uri.EscapeUriString(to); client.DownloadDataAsync(new System.Uri("https://api.microsofttranslator.com/v2/http.svc/Translate?" + parameters)); } return(deferred.Promise()); }
static void TranslateDocument(Configuration conf) { // request parameters for translation string name = "test.docx"; string folder = ""; string pair = "en-fr"; string format = "docx"; string outformat = ""; string storage = "First Storage"; string saveFile = "translated_d.docx"; string savePath = ""; bool masters = false; List <int> elements = new List <int>(); // local paths to upload and download files string uploadPath = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.Parent.FullName + "/" + name; string downloadPath = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.Parent.FullName + "/" + saveFile; TranslationApi api = new TranslationApi(conf); FileApi fileApi = new FileApi(conf); Stream stream = File.Open(uploadPath, FileMode.Open); UploadFileRequest uploadRequest = new UploadFileRequest { File = stream, path = name, storageName = storage }; FilesUploadResult uploadResult = fileApi.UploadFile(uploadRequest); Console.WriteLine("Files uploaded: " + uploadResult.Uploaded.Count); TranslateDocumentRequest request = api.CreateDocumentRequest(name, folder, pair, format, outformat, storage, saveFile, savePath, masters, elements); TranslationResponse response = api.RunTranslationTask(request); Console.WriteLine(response.Message); foreach (var key in response.Details.Keys) { Console.WriteLine(key + ": " + response.Details[key]); } DownloadFileRequest downloadRequest = new DownloadFileRequest { storageName = storage, path = saveFile }; Stream result = fileApi.DownloadFile(downloadRequest); Console.WriteLine("Translated file downloaded"); using (FileStream file = new FileStream(downloadPath, FileMode.Create, FileAccess.Write)) { result.CopyTo(file); } Console.WriteLine("Translated file saved"); }
public void TranslationTranslateGetAsyncTest() { TranslationResponse response = new TranslationResponse(); List <string> sample = new List <string>(); sample.Add("this is a test"); Task.Run(async() => { response = await translationApi.TranslationTranslateGetAsync(sample, "en", "fr", null, null, true, false, null, null, false, null, null, false, null, null); }).Wait(); Assert.IsNotNull(response.Outputs[0]); }
public TranslationResponse Translate(TranslationRequest translationRequest) { var translationResponse = new TranslationResponse { Success = false }; const string apiUrl = "https://www.googleapis.com/language/translate/v2?key={0}&source={1}&target={2}&q={3}"; var url = String.Format( apiUrl, TranslatorAppId, translationRequest.LanguageFrom, translationRequest.LanguageTo, translationRequest.TextToTranslate); try { var req = WebRequest.Create(url); // set the request method req.Method = "GET"; // get the response using (var res = req.GetResponse()) { if (res != null) { using (var sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8)) { var json = sr.ReadToEnd(); var jsonobject = JObject.Parse(json); IEnumerable <JToken> results = jsonobject["data"]["translations"].Children(); var translationResults = new List <TranslationResult>(); foreach (var result in results) { var ret = JsonConvert.DeserializeObject <TranslationResult>(result.ToString()); translationResults.Add(ret); } translationResponse.Result = translationResults[0].TranslatedText; translationResponse.Success = true; } } } } catch (Exception ex) { translationResponse.Error = ex.ToString(); translationResponse.Success = false; } return(translationResponse); }
public async Task <IActionResult> Get([FromBody][Required] TranslationParameters parameters, [FromHeader][Required] string accept) { TranslationResponse response = await Task.FromResult <TranslationResponse>(this._translationService.Tanslate(parameters)); if (response.AreErrors) { return(BadRequest(error: response.Exceptions.Select(e => e.Message).ToArray())); } return(accept switch { "text/plain" => File(GenerateStreamFromString(response.Result), "text/plain", "result.txt"), "application/json" => Ok(GenerateJsonFromString(response.Result)), _ => Ok(response.Result) });
public async Task <TranslationResponse> Translate(TranslationRequest translationRequest, string apiKey, string formality) { var translationEngine = _languageService.GetLanguagesFromEngineId(translationRequest.EngineId); var translationsResponse = new TranslationResponse { Translations = new List <string>() }; var translations = GetTranslations(translationRequest, translationEngine, apiKey, formality); translationsResponse.Translations.AddRange(translations); return(translationsResponse); }
public TranslationResponse Get(TranslationRequest translationRequest) { TranslationResponse response = new TranslationResponse() { Lang = translationRequest.Lang }; response.Values = translationRequest.Keys.Aggregate(new Dictionary <string, string>(), (accumlater, key) => { string value = _translationService.Translate(key, translationRequest.Lang); accumlater.Add(key, value); return(accumlater); }); return(response); }
private void btnTranslate_Click(object sender, EventArgs e) { pgBar.Value = 0; pgBar.Visible = true; btnSave.Enabled = false; this.Cursor = Cursors.WaitCursor; try { DataTable table = new DataTable(); table.Columns.Add("Source Key"); table.Columns.Add("Source Value"); table.Columns.Add("Translation"); var resource = ReadResourceValues(txtResourceFile.Text); pgBar.Maximum = resource.Keys.Count; foreach (string key in resource.Keys) { var row = table.NewRow(); row[0] = key; row[1] = resource[key]; //try { TranslationResponse response = Google.Translate(resource[key], Language.Unknown, cbDestLang.SelectedValue.ToString(), TextFormat.Text); row[2] = response.ResponseData.TranslatedText; } //catch { //row[2] = "?"; } table.Rows.Add(row); pgBar.Value += 1; } grid.DataSource = table; } finally { this.Cursor = Cursors.Default; pgBar.Visible = false; btnSave.Enabled = true; } }
public void TranslationService_Target_NotExist() { TranslationParameters parameters = new TranslationParameters() { DataMappers = new Dictionary <string, string>(), DefaultNamespace = string.Empty, DataSources = new List <DataSource>() { }, Experession = string.Empty, Target = "test" }; TranslationResponse response = _translationService.Tanslate(parameters); Assert.True(response.AreErrors); Assert.Equal("Unexpected target type.", response.Exceptions.First().Message); }
public void AddTranslatedText(TranslationResponse response) { if (!Dispatcher.CheckAccess()) { Dispatcher.Invoke(() => AddTranslatedText(response)); return; } var responseParagraph = new Paragraph(); if (!response.IsSuccess) { var redSpan = new Span(new Run(response.ErrorMessage)); redSpan.Foreground = Brushes.OrangeRed; responseParagraph.Inlines.Add(new Run("Error: ")); responseParagraph.Inlines.Add(redSpan); } else { var resultSpan = new Span(new Run(response.ErrorMessage)); resultSpan.Foreground = Brushes.DarkGreen; foreach (var responseTranslatedResult in response.TranslatedResults) { if (responseTranslatedResult != null) { foreach (var translatedItem in responseTranslatedResult.Translations) { resultSpan.Inlines.Add(translatedItem.Text); } } } responseParagraph.Inlines.Add(resultSpan); } TranslationAreaDocument.Blocks.Add(responseParagraph); TranslatorFlowDocumentScrollViewer.ScrollToEnd(); }
public TranslationResponse Get([FromUri] TranslationRequest request) { var plugins = PluginLoader.Load(_mapper.MapPath(ConfigurationManager.AppSettings["PluginsDirectory"])); var engine = new TranslatorEngine(plugins, ConfigurationManager.AppSettings["DefaultLanguage"]); var plugin = engine[request.Language]; var response = new TranslationResponse(); if (plugin is NoAvailableLanguagesTranlastor) { response.Code = HttpStatusCode.NotFound; } else { response.Code = HttpStatusCode.OK; } response.Translation = plugin.Translate(request.Text); response.Language = plugin.LanguageCode; return(response); }
/// <summary> /// Gets the name in hindi /// </summary> /// <param name="name"></param> /// <returns></returns> private async Task <string> GetTranslatedText(string name) { System.Object[] body = new System.Object[] { new { Text = name } }; var requestBody = JsonConvert.SerializeObject(body); StringContent content = new StringContent(requestBody, Encoding.UTF8, "application/json"); _httpClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", _appSettings.AccessKey); var result = await _httpClient.PostAsync($"{_appSettings.TranslationApiUrl}/translate?api-version=3.0&to=hi", content); result.EnsureSuccessStatusCode(); string translatedJson = await result.Content.ReadAsStringAsync(); TranslationResponse response = Newtonsoft.Json.JsonConvert.DeserializeObject <TranslationResponse>(JArray.Parse(translatedJson)[0].ToString()); return(response.translations[0].text); }
public TranslationResponse Translate(TranslationRequest translationRequest) { var client = new LanguageServiceClient(); var translationResponse = new TranslationResponse(); translationResponse.Success = false; try { translationResponse.Result = client.Translate(TranslatorAppId, translationRequest.TextToTranslate, translationRequest.LanguageFrom, translationRequest.LanguageTo, "text/plain", "general"); translationResponse.Success = true; } catch (Exception ex) { translationResponse.Error = ex.ToString(); translationResponse.Success = false; } return(translationResponse); }
/// <inheritdoc/> public async Task <PokemonData> GetTranslatedPokemonData(string pokemonName) { //TODO : validate pokemonName exists by cross checking against data obtained from //https://pokeapi.co/api/v2/pokemon?limit=10000 (arbitrary upper limit of known pokemon, currently 1118) PokemonSpeciesData response = await this.pokemonDataRepository.GetPokemonData(pokemonName); PokemonData data = this.pokemonDataParser.BuildPokemonData(response); if (data.Habitat == "cave" || data.IsLegendary) { try { TranslationResponse translation = await this.pokemonDataRepository.GetTranslation(data.Description, "yoda"); data.Description = translation.Contents.Translated; } catch (Exception) { //TODO : Add logging } } else { try { TranslationResponse translation = await this.pokemonDataRepository.GetTranslation(data.Description, "shakespeare"); data.Description = translation.Contents.Translated; } catch (Exception) { //TODO : Add logging } } return(data); }
/// <summary> /// 翻译 /// </summary> /// <param name="language">语言结构</param> public void Translate(LanguageStructure language) { SearchRequest searchRequest = new SearchRequest(); searchRequest.AppId = _appID; searchRequest.Query = language.OriginalText; searchRequest.Market = "en-US"; TranslationRequest transRequest = new TranslationRequest(); transRequest.SourceLanguage = "En"; //English transRequest.TargetLanguage = "zh-CHS"; //China TranslationResponse response = API.Translation(searchRequest, transRequest); if (response.TranslationResults.Count > 0) { language.Translation = response.TranslationResults[0].TranslatedTerm; On_Sucess(language); } else { On_Error("Error"); } }
public ActionResult <TranslationResponse> TranslateToAttributes(string issuerName, [FromBody] object json) { var provider = _dataAccessService.GetExternalIdentityProvider(issuerName); AccountDescriptor account = _accountsService.GetById(provider.AccountId); var validator = _externalIdpDataValidatorsRepository.GetInstance(issuerName); if (validator == null) { throw new Exception($"No validator found for {issuerName}"); } TranslationResponse response = new TranslationResponse { Issuer = account.PublicSpendKey.ToHexString(), ActionUri = $"{Request.Scheme}://{Request.Host}".AppendPathSegments("IdentityProvider", "IssueExternalIdpAttributes", account.PublicSpendKey.ToHexString()).ToString() }; string jsonString = json?.ToString(); switch (issuerName) { case "BlinkID-DrivingLicense": case "BlinkID-Passport": var request = JsonConvert.DeserializeObject <BlinkIdIdentityRequest>(jsonString); validator.Validate(request); var translator = _translatorsRepository.GetInstance <BlinkIdIdentityRequest, Dictionary <string, string> >(); var attributes = translator.Translate(request); response.Attributes = attributes; break; default: return(BadRequest("unknown issuer name")); } return(Ok(response)); }
public async Task <IReadOnlyList <TranslationResponse> > GetWorkTranslationsAsync(int workId) { // TODO: rework when EF7 will supports GroupBy with InnerJoin var sql = @" SELECT tw.translation_work_id, et.name FROM translation_works tw INNER JOIN edition_translations et ON et.translation_work_id = tw.translation_work_id WHERE tw.work_id = @work_id GROUP BY tw.translation_work_id, tw.work_id, et.name ORDER BY tw.translation_work_id, COUNT(*) DESC"; List <TranslationResponse> translationNames = new List <TranslationResponse>(); var connection = _bookContext.Database.GetDbConnection() as SqlConnection; if (connection != null) { connection.Open(); using (var command = new SqlCommand(sql, connection)) { command.Parameters.AddWithValue("@work_id", workId); using (var reader = await command.ExecuteReaderAsync()) { while (await reader.ReadAsync()) { var name = new TranslationResponse { TranslationWorkId = reader.GetValue <int>("translation_work_id"), WorkName = reader.GetValue <string>("name") }; translationNames.Add(name); } } } connection.Close(); } var query = from tw in _bookContext.TranslationWorks join twp in _bookContext.TranslationWorkPersons on tw.Id equals twp.TranslationWorkId join p in _bookContext.Persons on twp.PersonId equals p.Id where tw.WorkId == workId orderby tw.LanguageId, tw.Year, tw.Id, twp.PersonOrder select new { TranslationWorkId = tw.Id, PersonId = twp.PersonId, Name = p.Name, LanguageId = tw.LanguageId, Year = tw.Year }; var result = await query.ToListAsync(); // TODO: try to optimize it later List <TranslationResponse> responses = new List <TranslationResponse>(); foreach (var item in result.GroupBy(c => c.TranslationWorkId).Select(c => c.Key)) { TranslationResponse response = new TranslationResponse(); var items = result.Where(c => c.TranslationWorkId == item).ToList(); response.LanguageId = items.First().LanguageId; response.TranslationWorkId = item; response.TranslationYear = items.First().Year; response.Names = translationNames.Where(c => c.TranslationWorkId == item).Select(c => c.WorkName).ToList(); response.Translators = new List <PersonResponse>(); foreach (var person in items) { response.Translators.Add(new PersonResponse { PersonId = person.PersonId, Name = person.Name }); } responses.Add(response); } return(responses); }
static void Main(string[] args) { try { if (args.Length == 0) { Console.WriteLine("This program is automatically run during a game session if ezTrans is selected, and will be automatically stopped afterwards. This program cannot be run independently."); Console.WriteLine("Press any key to exit."); Console.ReadKey(); return; } var powerTranslatorPathPayload = args[0]; var powerTranslatorPath = Encoding.UTF8.GetString(Convert.FromBase64String(powerTranslatorPathPayload)); var datPath = Path.Combine(powerTranslatorPath, @"Dat"); //initialize path var dllPath = Path.Combine(powerTranslatorPath, @"J2KEngineH.dll"); //Ehnd engine path if (!File.Exists(dllPath)) { dllPath = Path.Combine(powerTranslatorPath, @"J2KEngine.dll"); } using (var translator = new ezTransTranslationLibrary(dllPath)) { if (!translator.InitEx("CSUSER123455", datPath)) //initialize ezTrans { throw new Exception("J2K_InitializeEx Failed."); } using (var stdout = Console.OpenStandardOutput()) using (var writer = new StreamWriter(stdout)) using (var stdin = Console.OpenStandardInput()) using (var reader = new StreamReader(stdin)) { writer.AutoFlush = true; while (true) { var receivedPayload = reader.ReadLine(); if (string.IsNullOrEmpty(receivedPayload)) { return; } var message = ExtProtocolConvert.Decode(receivedPayload) as TranslationRequest; if (message == null) { return; } var translatedTexts = new string[message.UntranslatedTexts.Length]; for (int i = 0; i < message.UntranslatedTexts.Length; i++) { var untranslatedText = message.UntranslatedTexts[i]; var translatedText = translator.Translate(untranslatedText); translatedTexts[i] = translatedText; } var response = new TranslationResponse { Id = message.Id, TranslatedTexts = translatedTexts }; var translatedPayload = ExtProtocolConvert.Encode(response); writer.WriteLine(translatedPayload); } } } } catch (Exception) { // "Graceful shutdown" } }
public async Task RunAsync() { using (var stdout = Console.OpenStandardOutput()) using (var writer = new StreamWriter(stdout)) using (var stdin = Console.OpenStandardInput()) using (var reader = new StreamReader(stdin)) { writer.AutoFlush = true; while (true) { var receivedPayload = reader.ReadLine(); if (string.IsNullOrEmpty(receivedPayload)) { return; } var message = ExtProtocolConvert.Decode(receivedPayload) as TranslationRequest; if (message == null) { return; } var context = new TranslationContext(message.UntranslatedTexts, message.SourceLanguage, message.DestinationLanguage); try { await Endpoint.Translate(context); } catch (Exception e) { context.FailWithoutThrowing("An error occurred in the pipeline.", e); } ProtocolMessage response; if (!string.IsNullOrEmpty(context.ErrorMessage) || context.Error != null) { string errorMessage = context.ErrorMessage; if (context.Error != null) { if (!string.IsNullOrEmpty(errorMessage)) { errorMessage += Environment.NewLine; } errorMessage += context.Error.ToString(); } response = new TranslationError { Id = message.Id, Reason = errorMessage }; } else { response = new TranslationResponse { Id = message.Id, TranslatedTexts = context.TranslatedTexts }; } var translatedPayload = ExtProtocolConvert.Encode(response); writer.WriteLine(translatedPayload); } } }
static void Main(string[] args) { // Implementation of this is based off of texel-sensei's LEC implementation try { if (args.Length == 0) { Console.WriteLine("This program is automatically run during a game session if LEC is selected, and will be automatically stopped afterwards. This program cannot be run independently."); Console.WriteLine("Press any key to exit."); Console.ReadKey(); return; } var powerTranslatorPathPayload = args[0]; var powerTranslatorPath = Encoding.UTF8.GetString(Convert.FromBase64String(powerTranslatorPathPayload)); var dllPath = Path.Combine(powerTranslatorPath, @"Nova\JaEn\EngineDll_je.dll"); using (var translator = new LecTranslationLibrary(dllPath)) { using (var stdout = Console.OpenStandardOutput()) using (var writer = new StreamWriter(stdout)) using (var stdin = Console.OpenStandardInput()) using (var reader = new StreamReader(stdin)) { writer.AutoFlush = true; while (true) { var receivedPayload = reader.ReadLine(); if (string.IsNullOrEmpty(receivedPayload)) { return; } var message = ExtProtocolConvert.Decode(receivedPayload) as TranslationRequest; if (message == null) { return; } var translatedTexts = new string[message.UntranslatedTexts.Length]; for (int i = 0; i < message.UntranslatedTexts.Length; i++) { var untranslatedText = message.UntranslatedTexts[i]; var translatedText = translator.Translate(untranslatedText); translatedTexts[i] = translatedText; } var response = new TranslationResponse { Id = message.Id, TranslatedTexts = translatedTexts }; var translatedPayload = ExtProtocolConvert.Encode(response); writer.WriteLine(translatedPayload); } } } } catch (Exception) { // "Graceful shutdown" } }