Beispiel #1
0
        private static string Translate(string input, ref Language sourceLanguage, Language targetLanguage)
        {
            string results = "";

            if ((input == null) || (input == ""))
            {
                return("");
            }
            string NewLine = "!!!!";

            input = input.Replace(Environment.NewLine, NewLine);
            //  phrase= phrase.Replace(Environment.NewLine, "<br>");
            string url = string.Format(LanguageTranslatePostString, LanguageApiVersion,
                                       HttpUtility.UrlEncode(input, Encoding.UTF8),
                                       LanguageHelper.GetLanguageString(sourceLanguage),
                                       LanguageHelper.GetLanguageString(targetLanguage));

            //string responseData = CoreHelper.PerformRequest(url);
            string responseData = CoreHelper.BuildWebRequest(LanguageTranslateUrl, url);

            JsonObject jsonObject = CoreHelper.ParseGoogleAjaxAPIResponse(responseData);

            // Translation response validation
            // Get 'responseData'
            if (jsonObject.ContainsKey("responseData") == false)
            {
                throw new GapiException("Invalid response - no responseData: " + responseData);
            }

            if (!(jsonObject["responseData"] is JsonObject))
            {
                throw new GapiException("Invalid response - responseData is not JsonObject: " + responseData);
            }

            // Get 'translatedText'
            JsonObject responseContent = (JsonObject)jsonObject["responseData"];

            if (responseContent.ContainsKey("translatedText") == false)
            {
                throw new GapiException("Invalid response - no translatedText: " + responseData);
            }

            if (!(responseContent["translatedText"] is JsonString))
            {
                throw new GapiException("Invalid response - translatedText is not JsonString: " + responseData);
            }

            string translatedPhrase = ((JsonString)responseContent["translatedText"]).Value;

            // If there's a detected language - return it
            if ((responseContent.ContainsKey("detectedSourceLanguage") == true) &&
                (responseContent["detectedSourceLanguage"] is JsonString))
            {
                JsonString detectedSourceLanguage = (JsonString)responseContent["detectedSourceLanguage"];
                sourceLanguage = LanguageHelper.GetLanguage(detectedSourceLanguage.Value);
            }

            results += HttpUtility.HtmlDecode(translatedPhrase) + Environment.NewLine;

            results = results.Replace(NewLine, Environment.NewLine);
            return(results);
        }