Inheritance: System.Data.Services.Client.DataServiceContext
Beispiel #1
0
        public static TranslatorContainer InitializeTranslatorContainer()
        {
            var tc = new TranslatorContainer(serviceRootUri);
            tc.Credentials = new NetworkCredential(accountKey, accountKey);

            return tc;
        }
 private static string Translate(TranslatorContainer tc, string text, string to, string from)
 {
     var query = tc.Translate(text, to, from);
     var results = query.Execute().ToList();
     var result = results.First();
     return result.Text;
 }
        private static void Main()
        {
            var serviceRootUri = new Uri("https://api.datamarket.azure.com/Bing/MicrosoftTranslator/v1/Translate");
            string accountKey = Secrets.AccountInfo.Instance.AccountKey;
            var tc = new TranslatorContainer(serviceRootUri) {Credentials = new NetworkCredential(accountKey, accountKey)};

            const string origin = "I'm going to feed the dogs then take them out for a walk.";
            const string @from = "en";
            const string to = "es";

            string start = origin;
            int i = 0;
            for (; i < 10; i++)
            {
                string trans = Translate(tc, start, to, @from);
                string backTrans = Translate(tc, trans, @from, to);

                string currentState = string.Format("Iteration {0}: {1} - {2}", i + 1, start, trans);
                Console.WriteLine(currentState);
                Debug.WriteLine(currentState);

                if (backTrans == start)
                    break;
                start = backTrans;
            }

            Console.ReadKey();
        }
 private static TranslatorContainer CreateTranslatorContainer()
 {
     var serviceUri = new Uri(ConfigurationManager.ConnectionStrings["TranslationServices"].ConnectionString);
     var serviceCredentials = new NetworkCredential(ConfigurationManager.AppSettings["TranslationServicesKey"],
         ConfigurationManager.AppSettings["TranslationServicesKey"]);
     var result = new TranslatorContainer(serviceUri) { Credentials = serviceCredentials };
     return result;
 }
Beispiel #5
0
        public static Microsoft.Translation TranslateString(TranslatorContainer tc, string text, Language source, Language dest)
        {
            var translationQuery = tc.Translate(text, source.Code, dest.Code);
            var translationResults = translationQuery.Execute().ToList();

            var translationResult = translationResults.FirstOrDefault();

            return translationResult;
        }
Beispiel #6
0
        /// <summary>
        /// Asks the service represented by the TranslatorContainer for a list
        /// of all supported languages.
        /// </summary>
        /// <returns>All supported Languages.</returns>
        public static Language[] GetSupportedLanguages(String accountKey)
        {
            // Call a InitializeTranslatorContainer to get a TranslatorContainer
            // that is configured to use your account.
            TranslatorContainer tc = InitializeTranslatorContainer(accountKey);

            // Generate the query
            var languagesForTranslationQuery = tc.GetLanguagesForTranslation();

            // Call the query to get the results as an Array
            var availableLanguages = languagesForTranslationQuery.Execute().ToArray();

            // Return list of supported languages
            return(availableLanguages);
        }
Beispiel #7
0
        /// <summary>
        /// Uses the TranslatorContainer to translate inputString from sourceLanguage
        /// to targetLanguage.
        /// </summary>
        /// <param name="tc">The TranslatorContainer to use</param>
        /// <param name="inputString">The string to translate</param>
        /// <param name="sourceLanguage">The Language Code to use in interpreting the input string.</param>
        /// <param name="targetLanguage">The Language Code to translate the input string to.</param>
        /// <returns>The translated string, or null if no translation results were found.</returns>
        private static Translation TranslateString(TranslatorContainer tc, string inputString, DetectedLanguage sourceLanguage, Language targetLanguage)
        {
            // Generate the query
            var translationQuery = tc.Translate(inputString, targetLanguage.Code, sourceLanguage.Code);

            // Call the query and get the results as a List
            var translationResults = translationQuery.Execute().ToList();

            // Verify there was a result
            if (translationResults.Count() <= 0)
            {
                return(null);
            }

            // In case there were multiple results, pick the first one
            var translationResult = translationResults.First();

            return(translationResult);
        }
Beispiel #8
0
        /// <summary>
        /// Asks the service represented by the TranslatorContainer for a list
        /// of all supported languages and then picks one at random.
        /// </summary>
        /// <param name="tc">The TranslatorContainer to use.</param>
        /// <returns>A randomly selected Language.</returns>
        private static Language PickRandomLanguage(TranslatorContainer tc)
        {
            // Used to generate a random index
            var random = new Random();

            // Generate the query
            var languagesForTranslationQuery = tc.GetLanguagesForTranslation();

            // Call the query to get the results as an Array
            var availableLanguages = languagesForTranslationQuery.Execute().ToArray();

            // Generate a random index between 0 and the total number of items in the array
            var randomIndex = random.Next(availableLanguages.Count());

            // Select the randomIndex'th value from the array
            var selectedLanguage = availableLanguages[randomIndex];

            return(selectedLanguage);
        }
Beispiel #9
0
        /// <summary>
        /// Creates an instance of a TranslatorContainer that calls the public
        /// production MicrosoftTranslator service
        /// </summary>
        /// <returns>The generated TranslatorContainer</returns>
        private static TranslatorContainer InitializeTranslatorContainer(String accountKey)
        {
            // this is the service root uri for the Microsoft Translator service
            var serviceRootUri = new Uri("https://api.datamarket.azure.com/Bing/MicrosoftTranslator/");

            // this is the Account Key I generated for this app
            //var accountKey = "D0VUOytsM8NnicdPNpRaDY3tH79HOIhFY+CWyLYe3oo";

            // Replace the account key above with your own and then delete
            // the following line of code. You can get your own account key
            // for from here: https://datamarket.azure.com/account/keys
            //throw new Exception("Invalid Account Key");

            // the TranslatorContainer gives us access to the Microsoft Translator services
            var tc = new TranslatorContainer(serviceRootUri);

            // Give the TranslatorContainer access to your subscription
            tc.Credentials = new NetworkCredential(accountKey, accountKey);
            return(tc);
        }
Beispiel #10
0
        /// <summary>
        /// Uses the TranslatorContainer to identify the Language in which inputString was written
        /// </summary>
        /// <param name="tc">The TranslatorContainer to use</param>
        /// <param name="inputString">The string to identify</param>
        /// <returns>The Language Code for a language that this string could represent,
        /// or null if one is not found.</returns>
        private static DetectedLanguage DetectSourceLanguage(TranslatorContainer tc, string inputString)
        {
            // calling Detect gives us a DataServiceQuery which we can use to call the service
            var translateQuery = tc.Detect(inputString);

            // since this is a console application, we do not want to do an asynchronous
            // call to the service. Otherwise, the program thread would likely terminate
            // before the result came back, causing our app to appear broken.
            var detectedLanguages = translateQuery.Execute().ToList();

            // since the result of the query is a list, there might be multiple
            // detected languages. In practice, however, I have only seen one.
            // Some input strings, 'hi' for example, are obviously valid in
            // English but produce other results, suggesting that the service
            // only returns the first result.
            if (detectedLanguages.Count() > 1)
            {
                Console.WriteLine("Possible source languages:");

                foreach (var language in detectedLanguages)
                {
                    Console.WriteLine("\t" + language.Code);
                }

                Console.WriteLine();
            }

            // only continue if the Microsoft Translator identified the source language
            // if there are multiple, let's go with the first.
            if (detectedLanguages.Count() > 0)
            {
                return(detectedLanguages.First());
            }
            else
            {
                return(null);
            }
        }
    public string AutoTranslateSync(string untranslatedPhraseText, string untranslatedPhraseLanguage, string targetLanguageText)
    {
      //PREPARE THE TRANSLATOR CONTAINER (TRANSLATION SERVICE CLIENT)
      var serviceRootUri = new Uri(CommonResources.AzureServiceRootUriAddress);
//#if DEBUG
      var accountKey = CommonResources.LearnLanguagesAccountKey;
//#else
//      string accountKey = (string)System.Windows.Application.Current.Resources[CommonResources.AzureLearnLanguagesAccountKey];
//#endif
      TranslatorContainer translatorContainer = new TranslatorContainer(serviceRootUri);
      translatorContainer.Credentials = new NetworkCredential(accountKey, accountKey);

      //TURN THE LANGUAGE TEXTS INTO LANGUAGE CODES THAT SERVICE UNDERSTANDS
      var fromLanguageCode = TranslationHelper.GetLanguageCode(untranslatedPhraseLanguage);
      var toLanguageCode = TranslationHelper.GetLanguageCode(targetLanguageText);

      //BUILDS THE TRANSLATION QUERY
      var translationQuery = translatorContainer.Translate(untranslatedPhraseText,
                                                           toLanguageCode,
                                                           fromLanguageCode);

      //ACTUALLY EXECUTE THE TRANSLATION QUERY
      var translations = translationQuery.Execute().ToList();

      //INTERPRET THE TRANSLATION RESULTS
      if (translations.Count > 0)
      {
        var translationText = translations.First().Text;
        //RETURN TRANSLATION (FIRST TRANSLATION, IF MULTIPLE EXIST)
        return translationText;
      }
      else
      {
        //RETURN EMPTY STRING
        return string.Empty;
      }
    }
        public string Translate(string translateMe, CultureInfo fromCultureInfo, CultureInfo toCultureInfo)
        {
            if (fromCultureInfo == null)
            {
                throw new ArgumentNullException("fromCultureInfo is null");
            }
            if (toCultureInfo == null)
            {
                throw new ArgumentNullException("toCultureInfo is null");
            }

            if (string.IsNullOrEmpty(translateMe))
            {
                return translateMe;
            }

            string sourceLanguage = fromCultureInfo.TwoLetterISOLanguageName;
            string targetLanguage = toCultureInfo.TwoLetterISOLanguageName;

            TranslatorContainer tc = new TranslatorContainer(new System.Uri(SERVICE_URL));
            tc.Credentials = new System.Net.NetworkCredential(_username, _password);

            var translationQuery = tc.Translate(translateMe, targetLanguage, sourceLanguage);

            List<Microsoft.Translation> translationResults = translationQuery.Execute().ToList();

            // Verify there was a result
            if (translationResults.Count() <= 0)
            {
                return null;
            }

            // In case there were multiple results, pick the first one
            Microsoft.Translation translationResult = translationResults.First();

            return translationResult.Text;
        }
Beispiel #13
0
        /// <summary>
        /// Translate a text
        /// </summary>
        /// <param name="accountKey">Bing account key</param>
        /// <param name="sourceLng">source language</param>
        /// <param name="targetLng">target language</param>
        /// <param name="inputString">text to translate</param>
        /// <param name="outputString">translated text</param>
        /// <returns>error code:
        /// 0 : translation successful
        /// -1: inputstring is empty
        /// -2: text cannot be translated (invalid source language or not detected source language)
        /// -3: error during translation
        /// </returns>
        public static int TranslateMethod(String accountKey, string sourceLng, string targetLng, string inputString, out string outputString)
        {
            outputString = "";
            // Call GetInputString to manage the input
            //inputString = "This is a lovely slice of text that I'd like to translate";//GetInputString(args);

            // Verify that the user actually provided some input
            if (inputString == "")
            {
                //Console.WriteLine("Usage: RandomTranslator.exe Some Input Text");
                return(-1);
            }

            // Improved support for unicode
            //Console.OutputEncoding = Encoding.UTF8;

            // Print the input string
            //Console.WriteLine("Input: " + inputString);

            //Console.WriteLine();

            // Call a InitializeTranslatorContainer to get a TranslatorContainer
            // that is configured to use your account.
            TranslatorContainer tc = InitializeTranslatorContainer(accountKey);

            // DetectSourceLanguage encapsulates the work required for language
            // detection
            DetectedLanguage sourceLanguage = null;

            if ((sourceLng == null) || (sourceLng == ""))
            {
                sourceLanguage = DetectSourceLanguage(tc, inputString);
            }
            else
            {
                sourceLanguage      = new DetectedLanguage();
                sourceLanguage.Code = sourceLng;
            }

            // Handle the error condition
            if (sourceLanguage == null)
            {
                //Console.WriteLine("\tThis string cannot be translated");

                return(-2);
            }

            // Print the detected language code
            //Console.WriteLine("Detected Source Language: " + sourceLanguage.Code);

            //Console.WriteLine();

            // PickRandomLanguage encapsulates the work required to detect all
            // languages supported by the service and then to pick one at random
            var targetLanguage = PickRandomLanguage(tc);

            targetLanguage.Code = targetLng;

            // Print the selected language code
            //Console.WriteLine("Randomly Selected Target Language: " + targetLanguage.Code);

            //Console.WriteLine();

            // TranslateString encapsulates the work required to translate
            // a string from the source language to the target language
            var translationResult = TranslateString(tc, inputString, sourceLanguage, targetLanguage);

            // Handle the error condition
            if (translationResult == null)
            {
                //Console.WriteLine("Translation Failed.");
                return(-3);
            }

            // Print the result of the translation
            //Console.WriteLine("Translated String: " + translationResult.Text);
            outputString = translationResult.Text;
            return(0);
        }