public override async void Translate(ITranslationSession translationSession) { try { var authenticationKey = AuthenticationKey; if (string.IsNullOrEmpty(authenticationKey)) { translationSession.AddMessage("Azure Translator requires subscription secret."); return; } var token = await AzureAuthentication.GetBearerAccessTokenAsync(authenticationKey).ConfigureAwait(false); using (var client = new HttpClient()) { client.DefaultRequestHeaders.Add("Authorization", token); foreach (var languageGroup in translationSession.Items.GroupBy(item => item.TargetCulture)) { var cultureKey = languageGroup.Key; var targetLanguage = cultureKey.Culture ?? translationSession.NeutralResourcesLanguage; var uri = new Uri($"https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&from={translationSession.SourceLanguage.IetfLanguageTag}&to={targetLanguage.IetfLanguageTag}"); using (var itemsEnumerator = languageGroup.GetEnumerator()) { while (true) { var sourceItems = itemsEnumerator.Take(10); var sourceStrings = sourceItems // ReSharper disable once PossibleNullReferenceException .Select(item => item.Source) .Select(RemoveKeyboardShortcutIndicators) .ToArray(); if (!sourceStrings.Any()) { break; } var response = await client.PostAsync(uri, CreateRequestContent(sourceStrings)).ConfigureAwait(false); if (response.IsSuccessStatusCode) { var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); using (var reader = new StreamReader(stream, Encoding.UTF8)) { var translations = JsonConvert.DeserializeObject <List <AzureTranslationResponse> >(reader.ReadToEnd()); if (translations != null) { #pragma warning disable CS4014 // Because this call is not awaited ... => just push out results, no need to wait. translationSession.Dispatcher.BeginInvoke(() => ReturnResults(sourceItems, translations)); } } } else { var errorMessage = await response.Content.ReadAsStringAsync().ConfigureAwait(false); translationSession.AddMessage("Azure translator reported a problem: " + errorMessage); } if (translationSession.IsCanceled) { break; } } } } } } catch (Exception ex) { translationSession.AddMessage("Azure translator reported a problem: " + ex); } }
public override async void Translate(ITranslationSession translationSession) { try { var authenticationKey = Credentials[0].Value; if (string.IsNullOrEmpty(authenticationKey)) { translationSession.AddMessage("Azure Translator requires subscription secret."); return; } var token = await AzureAuthentication.GetBearerAccessTokenAsync(authenticationKey); var binding = new BasicHttpBinding(); var endpointAddress = new EndpointAddress("http://api.microsofttranslator.com/V2/soap.svc"); using (var client = new LanguageServiceClient(binding, endpointAddress)) { var innerChannel = client.InnerChannel; // ReSharper disable once ConditionIsAlwaysTrueOrFalse if (innerChannel == null) { // ReSharper disable once HeuristicUnreachableCode return; } using (new OperationContextScope(innerChannel)) { var httpRequestProperty = new HttpRequestMessageProperty(); httpRequestProperty.Headers.Add("Authorization", token); var operationContext = OperationContext.Current; Contract.Assume(operationContext != null); // because we are inside OperationContextScope operationContext.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty; foreach (var languageGroup in translationSession.Items.GroupBy(item => item.TargetCulture)) { Contract.Assume(languageGroup != null); var cultureKey = languageGroup.Key; Contract.Assume(cultureKey != null); var targetLanguage = cultureKey.Culture ?? translationSession.NeutralResourcesLanguage; using (var itemsEnumerator = languageGroup.GetEnumerator()) { while (true) { var sourceItems = itemsEnumerator.Take(10); var sourceStrings = sourceItems.Select(item => item.Source).ToArray(); if (!sourceStrings.Any()) { break; } var translateOptions = new TranslateOptions() { ContentType = "text/plain", IncludeMultipleMTAlternatives = true }; var response = client.GetTranslationsArray("", sourceStrings, translationSession.SourceLanguage.IetfLanguageTag, targetLanguage.IetfLanguageTag, 5, translateOptions); if (response != null) { #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed => just push out results, no need to wait. translationSession.Dispatcher.BeginInvoke(() => ReturnResults(sourceItems, response)); } if (translationSession.IsCanceled) { break; } } } } } } } catch (Exception ex) { translationSession.AddMessage("Azure translator reported a problem: " + ex); } }