Beispiel #1
0
        protected override List <string> Translate(List <string> input, ITranslationOptions translationOptions)
        {
            if (translationOptions == null)
            {
                throw new ArgumentException(GetTranslаteArgumentExceptionMessage(nameof(translationOptions)));
            }

            var fromLanguageCode = translationOptions.SourceLanguage;
            var toLanguageCode   = translationOptions.TargetLanguage;

            if (string.IsNullOrWhiteSpace(fromLanguageCode))
            {
                throw new ArgumentException(GetTranslаteArgumentExceptionMessage($"{nameof(translationOptions)}.{nameof(translationOptions.SourceLanguage)}"));
            }

            if (string.IsNullOrWhiteSpace(toLanguageCode))
            {
                throw new ArgumentException(GetTranslаteArgumentExceptionMessage($"{nameof(translationOptions)}.{nameof(translationOptions.TargetLanguage)}"));
            }

            if (input == null || input.Count == 0)
            {
                throw new ArgumentException(GetTranslаteArgumentExceptionMessage(nameof(input)));
            }

            if (fromLanguageCode == toLanguageCode)
            {
                return(input);
            }

            string uri = GetAzureTranslateEndpointUri(fromLanguageCode, toLanguageCode);

            var body = new List <object>();

            foreach (var text in input)
            {
                body.Add(new { Text = text ?? string.Empty });
            }

            var    serializer  = new JavaScriptSerializer();
            string requestBody = serializer.Serialize(body);

            using (var client = this.GetClient())
                using (var request = new HttpRequestMessage())
                {
                    request.Method     = HttpMethod.Post;
                    request.RequestUri = new Uri(uri);
                    request.Content    = new StringContent(requestBody, Encoding.UTF8, "application/json");
                    request.Headers.Add("Ocp-Apim-Subscription-Key", this.key);
                    request.Headers.Add("X-ClientTraceId", Guid.NewGuid().ToString());

                    var response = client.SendAsync(request).Result;

                    var responseBody = response.Content.ReadAsStringAsync().Result;

                    if (!response.IsSuccessStatusCode)
                    {
                        this.HandleApiError(responseBody, response);
                    }

                    dynamic result;
                    try
                    {
                        result = serializer.DeserializeObject(responseBody);
                    }
                    catch (Exception ex)
                    {
                        if (IsSerializationException(ex))
                        {
                            throw new MicrosoftTranslatorConnectorSerializationException($"{Constants.ExceptionMessages.ErrorSerializingResponseFromServer} Server response: {response.StatusCode} {response.ReasonPhrase} {responseBody}");
                        }

                        throw;
                    }

                    var translations = new List <string>();
                    try
                    {
                        for (int i = 0; i < input.Count(); i++)
                        {
                            // currently Sitefinity does not support sending multiple languages at once, only multiple strings
                            var translation = result[i]["translations"][0]["text"];
                            translations.Add(translation);
                        }
                    }
                    catch (Exception ex)
                    {
                        if (ex is KeyNotFoundException || ex is NullReferenceException)
                        {
                            throw new MicrosoftTranslatorConnectorResponseFormatException($"{Constants.ExceptionMessages.UnexpectedResponseFormat} Server response: {response.StatusCode} {response.ReasonPhrase} {responseBody}");
                        }

                        throw;
                    }

                    return(translations);
                }
        }
        protected override List <string> Translate(List <string> input, ITranslationOptions translationOptions)
        {
            if (translationOptions == null)
            {
                throw new ArgumentException(GetTranslаteArgumentExceptionMessage(nameof(translationOptions)));
            }

            var fromLanguageCode = translationOptions.SourceLanguage;
            var toLanguageCode   = translationOptions.TargetLanguage;

            if (string.IsNullOrWhiteSpace(fromLanguageCode))
            {
                throw new ArgumentException(GetTranslаteArgumentExceptionMessage($"{nameof(translationOptions)}.{nameof(translationOptions.SourceLanguage)}"));
            }

            if (string.IsNullOrWhiteSpace(toLanguageCode))
            {
                throw new ArgumentException(GetTranslаteArgumentExceptionMessage($"{nameof(translationOptions)}.{nameof(translationOptions.TargetLanguage)}"));
            }

            if (input == null || input.Count == 0)
            {
                throw new ArgumentException(GetTranslаteArgumentExceptionMessage(nameof(input)));
            }

            if (fromLanguageCode == toLanguageCode)
            {
                return(input);
            }

            bool translateIndividually = false;

            // Because the connector does not removeHtmlTags is set to false, we expect to have only 1 input
            foreach (string text in input)
            {
                if (!string.IsNullOrWhiteSpace(text) && text.Length >= MaxTranslateRequestSize)
                {
                    translateIndividually = true;
                }
            }
            if (translateIndividually)
            {
                List <string> resultlist = new List <string>();
                foreach (string text in input)
                {
                    List <string> splitstring     = SplitString(text, fromLanguageCode);
                    var           linetranslation = new StringBuilder();
                    foreach (string innerText in splitstring)
                    {
                        var hasTrailingWhiteSpace = innerText.EndsWith(" ");
                        var innertranslation      = TranslateCore(new List <string> {
                            innerText
                        }, translationOptions);
                        linetranslation.Append(innertranslation[0]);
                        // The translator trims whitespaces by default, so add space if it was there before
                        if (hasTrailingWhiteSpace)
                        {
                            linetranslation.Append(" ");
                        }
                    }
                    resultlist.Add(linetranslation.ToString());
                }
                return(resultlist.ToList());
            }
            else
            {
                return(TranslateCore(input, translationOptions));
            }
        }
        protected override List <string> Translate(List <string> input, ITranslationOptions translationOptions)
        {
            if (translationOptions == null)
            {
                throw new ArgumentException(GetTranslаteArgumentExceptionMessage(nameof(translationOptions)));
            }

            var fromLanguageCode = translationOptions.SourceLanguage;
            var toLanguageCode   = translationOptions.TargetLanguage;

            if (string.IsNullOrWhiteSpace(fromLanguageCode))
            {
                throw new ArgumentException(GetTranslаteArgumentExceptionMessage($"{nameof(translationOptions)}.{nameof(translationOptions.SourceLanguage)}"));
            }

            if (string.IsNullOrWhiteSpace(toLanguageCode))
            {
                throw new ArgumentException(GetTranslаteArgumentExceptionMessage($"{nameof(translationOptions)}.{nameof(translationOptions.TargetLanguage)}"));
            }

            if (input == null || input.Count == 0)
            {
                throw new ArgumentException(GetTranslаteArgumentExceptionMessage(nameof(input)));
            }

            if (fromLanguageCode == toLanguageCode)
            {
                return(input);
            }

            string uri = GetAzureTranslateEndpointUri(fromLanguageCode, toLanguageCode);

            bool translateindividually = false;

            foreach (string text in input)
            {
                if (!string.IsNullOrWhiteSpace(text) && text.Length >= MaxTranslateRequestSize)
                {
                    translateindividually = true;
                }
            }
            if (translateindividually)
            {
                List <string> resultlist = new List <string>();
                foreach (string text in input)
                {
                    List <string> splitstring     = SplitString(text, fromLanguageCode);
                    string        linetranslation = string.Empty;
                    foreach (string innertext in splitstring)
                    {
                        var innertranslation = TranslateCore(new List <string> {
                            innertext
                        }, translationOptions);
                        linetranslation += string.Join(" ", innertranslation);
                    }
                    resultlist.Add(linetranslation);
                }
                return(resultlist.ToList());
            }
            else
            {
                return(TranslateCore(input, translationOptions));
            }
        }
 public List <string> TranslateCallMock(List <string> input, ITranslationOptions translationOptions)
 {
     return(base.Translate(input, translationOptions));
 }