/// <summary>
        /// Translate to all languages
        /// </summary>
        /// <param name="text"></param>
        /// <param name="from"></param>
        /// <param name="category"></param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        private async Task <SortedDictionary <string, string> > TranslateToAllLanguages(string text, string from, string category, TranslationServiceFacade.ContentType contentType)
        {
            EventHandler handler = OneTranslationDone;
            List <Task <KeyValuePair <string, string> > > tasklist = new List <Task <KeyValuePair <string, string> > >();

            foreach (KeyValuePair <string, string> language in await AvailableLanguages.GetLanguages())
            {
                Task <KeyValuePair <string, string> > task = TranslateInternal(text, from, language.Key, category, contentType);
                tasklist.Add(task);
                handler(this, EventArgs.Empty);
            }
            ;
            KeyValuePair <string, string>[] resultkv = await Task.WhenAll(tasklist);

            SortedDictionary <string, string> translatedDictionary = new SortedDictionary <string, string>();

            foreach (KeyValuePair <string, string> pair in resultkv)
            {
                translatedDictionary.Add(pair.Key, pair.Value);
            }



            return(translatedDictionary);
        }
示例#2
0
        /// <summary>
        ///     Initializes a new instance of the TranslateXML class.
        /// </summary>
        /// <param name="Logger">
        ///     The logger.
        /// </param>
        public TranslateXML(ConsoleLogger Logger)
            : base(Logger)
        {
            TranslationServiceFacade.Initialize();
            if (!TranslationServiceFacade.IsTranslationServiceReady())
            {
                this.Logger.WriteLine(LogLevel.Error, "Invalid translation service credentials. Use \"DocumentTranslatorCmd setcredentials\", or use the Document Translator Settings option.");
                return;
            }

            this.xmltotranslate = new Argument(
                "XML",
                true,
                "The XML file in need of translation");

            this.elementsdispositioncsv = new Argument(
                "Elements",
                true,
                "CSV file listing the elements to translate");

            this.fromlanguage = new Argument(
                "from",
                false,
                new[] { "Auto-Detect" },
                AvailableLanguages.GetLanguages().Result.Keys.ToArray(),
                true,
                "The source language. Auto-detect if no language specified.");

            this.tolanguage = new SimpleStringArgument(
                "to",
                true,
                new string[] { },
                AvailableLanguages.GetLanguages().Result.Keys.ToArray(),
                new[] { ',' },
                "The target language code, or comma-separated list of language codes.");

            this.generatecsv = new BooleanArgument(
                "generate",
                false,
                false,
                "Set to true if you want to generate a list of elements.");

            this.Arguments = new ArgumentList(
                new[] { this.xmltotranslate, this.elementsdispositioncsv, this.fromlanguage, this.tolanguage, this.generatecsv },
                Logger);
        }
示例#3
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="TranslateDocuments" /> class.
        /// </summary>
        /// <param name="Logger">
        ///     The logger.
        /// </param>
        public TranslateDocuments(ConsoleLogger Logger)
            : base(Logger)
        {
            try
            {
                _ = TranslationServiceFacade.Initialize();
            }
            catch (CredentialsMissingException ex)
            {
                this.Logger.WriteLine(LogLevel.Error, ex.Message);
            }
            if (!TranslationServiceFacade.IsTranslationServiceReady())
            {
                this.Logger.WriteLine(LogLevel.Error, "Invalid translation service credentials. Use \"DocumentTranslatorCmd setcredentials\"");
                return;
            }

            this.sourceDocuments = new SimpleStringArgument(
                "Documents",
                true,
                new[] { ',' },
                "Document to translate, or list of documents separated by comma, or a wildcard. Wildcard recurses through subfolders.");

            this.sourceLanguage = new Argument(
                "from",
                false,
                new[] { "Auto-Detect" },
                AvailableLanguages.GetLanguages().Result.Keys.ToArray(),
                true,
                "The source language. Auto-detect if no language specified.");

            this.targetLanguages = new SimpleStringArgument(
                "to",
                true,
                new string[] { },
                AvailableLanguages.GetLanguages().Result.Keys.ToArray(),
                new[] { ',' },
                "The target language code, or comma-separated list of language codes.");

            this.Arguments = new ArgumentList(
                new[] { this.sourceDocuments, this.sourceLanguage, this.targetLanguages },
                Logger);
        }
示例#4
0
        public static async Task <string> GetAllLanguages()
        {
            StringWriter writer = new StringWriter();
            Dictionary <string, string> languagelist = new Dictionary <string, string>();

            languagelist = await AvailableLanguages.GetLanguages();

            writer.WriteLine("{0}\t{1}\t{2}", "Language", "Language Code", "Display Name");
            writer.WriteLine("------------------------------------------------------");
            foreach (KeyValuePair <string, string> language in languagelist.ToList())
            {
                Dictionary <string, string> languagesinlanguage = await AvailableLanguages.GetLanguages(language.Key);

                foreach (KeyValuePair <string, string> lang in languagesinlanguage)
                {
                    writer.WriteLine("{0}\t{1}\t{2}", language.Key, lang.Key, lang.Value);
                }
                writer.WriteLine("\n\n");
            }

            return(writer.ToString());
        }
示例#5
0
 /// <summary>
 ///     Populate available source and target languages.
 /// </summary>
 public void PopulateAvailableLanguages()
 {
     this.sourceLanguageList.Clear();
     this.targetLanguageList.Clear();
     if (!TranslationServiceFacade.UseCustomEndpoint)
     {
         this.sourceLanguageList.Add(Properties.Resources.Common_AutoDetect);
     }
     try
     {
         targetLanguageList.AddRange(AvailableLanguages.GetLanguages().Result.Values);
     }
     catch (Exception ex) {
         this.StatusText = String.Format("{0}\n{1}", Properties.Resources.Error_LanguageList, ex.Message);
         this.NotifyPropertyChanged("StatusText");
         return;
     };
     this.targetLanguageList.Sort();
     this.sourceLanguageList.AddRange(this.targetLanguageList);
     this.NotifyPropertyChanged("SourceLanguageList");
     this.NotifyPropertyChanged("TargetLanguageList");
     Debug.WriteLine("DocumentTranslation.cs: targetLanguageList.Count: {0}", targetLanguageList.Count);
 }
示例#6
0
        /// <summary>
        ///     The execute.
        /// </summary>
        /// <returns>
        ///     The <see cref="bool" />.
        /// </returns>
        public override bool Execute()
        {
            int           documentcount = 0;
            List <String> listoffiles   = new List <string>();

            //Expand wildcard, if name specification contains *
            if (this.sourceDocuments.Values.ToArray().Any(file => file.ToString().Contains("*")))
            {
                foreach (string filename in this.sourceDocuments.Values.ToArray())
                {
                    int      lastBackslashPosition = filename.LastIndexOf('\\') + 1;
                    string   path         = filename.Substring(0, lastBackslashPosition);
                    string   filenameOnly = filename.Substring(lastBackslashPosition);
                    String[] filelist     = Directory.GetFiles(path, filenameOnly, SearchOption.AllDirectories);
                    listoffiles.AddRange(filelist);
                }
            }
            else  //no * in the file name
            {
                foreach (var file in this.sourceDocuments.ValueString.Split(','))
                {
                    listoffiles.Add(file);
                }
            }

            try
            {
                var model = new CommentTranslationModel
                {
                    SourceLanguage =
                        this.sourceLanguage.ValueString ?? "Auto-Detect",
                    TargetLanguage = this.targetLanguages.ValueString
                };

                foreach (var file in listoffiles)
                {
                    if (!File.Exists(file))
                    {
                        Logger.WriteLine(LogLevel.Error, String.Format("Specified document {0} does not exist. ", file));
                    }
                    foreach (var language in this.targetLanguages.Values)
                    {
                        try
                        {
                            this.Logger.WriteLine(
                                LogLevel.Msg,
                                string.Format(
                                    "Translating document {0} to language {1}.",
                                    file,
                                    language));
                            model.TargetPath = file;
                            var sourceLanguageExpanded = String.IsNullOrEmpty(this.sourceLanguage.ValueString) ||
                                                         this.sourceLanguage.ValueString.Equals("Auto-Detect")
                                                             ? "Auto-Detect"
                                                             : AvailableLanguages.GetLanguages().Result[this.sourceLanguage.ValueString];
                            string languagename = TranslationServiceFacade.LanguageCodeToLanguageName(language.ToString());

                            DocumentTranslationManager.DoTranslation(
                                file,
                                false,
                                sourceLanguageExpanded,
                                languagename);
                            this.Logger.WriteLine(
                                LogLevel.Msg,
                                string.Format(
                                    "-- Translated document name {0} to language {1}.",
                                    file,
                                    language));
                            documentcount++;
                        }
                        catch (Exception ex)
                        {
                            this.Logger.WriteLine(
                                LogLevel.Error,
                                string.Format(
                                    "Error while processing file: {0} to language {1} with error: {2}",
                                    model.TargetPath,
                                    language,
                                    ex.Message));
                            throw;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                this.Logger.WriteException(ex);
                Console.ReadLine();
                return(false);
            }

            this.Logger.WriteLine(LogLevel.Msg, string.Format("Documents translated successfully: {0}.", documentcount));
            return(true);
        }