Ejemplo n.º 1
0
        /// <summary>
        /// Translates a local language to another language
        /// </summary>
        /// <param name="sourceLanguage">The language to be translated</param>
        /// <param name="toLanguage">The language to translate to</param>
        /// <param name="translator">The translator to use</param>
        public string[] AddOnlineLanguage(Language sourceLanguage, CultureInfo toLanguage, IOnlineTranslator translator)
        {
            // If the decoder selected is embbeded, throw exception
            if (Decoder is EmbbededLanguageDecoder)
            {
                throw new Exception("This feature is not available using the EmbbededLanguage decoder.");
            }

            // If the source language is not installed, throw exception
            if (!GetInstalledLanguages().Contains(sourceLanguage))
            {
                throw new LanguageNotFoundException($"Language {sourceLanguage.Code} not found.");
            }

            // Get the language file
            if (!File.Exists(sourceLanguage.Location))
            {
                throw new FileNotFoundException("Language file not found.");
            }

            // Get entries
            var entries           = LanguageManager.LoadLanguageEntries(sourceLanguage.Code, Decoder);
            var translatedEntries = new Dictionary <string, string>(); // Create a dictionary to store translated entries
            var translationFailed = new List <string>();               // List to store the keys that could not be translated

            // Foreach entry...
            foreach (var entry in entries)
            {
                // Translate the text
                string translated = translator.TranslateText(entry.Value, sourceLanguage.GetCulture(), toLanguage);

                // Add if failed
                if (string.IsNullOrWhiteSpace(translated))
                {
                    translationFailed.Add(entry.Key);
                }

                // Add to translated entries
                translatedEntries.Add(entry.Key, translated.Replace('"', '\''));
            }

            // Write to a file
            string path = Path.Combine((Decoder as PhysicalFileDecoder).Path, $"{toLanguage.Name}{LANG_FILE_EXTENSION}");

            using (var fs = new FileStream(path, FileMode.Create))
                using (var writer = new StreamWriter(fs))
                {
                    // Write each entry into the file
                    foreach (var entry in translatedEntries)
                    {
                        writer.WriteLine($"{entry.Key}={entry.Value}");
                    }
                }

            // Create a new language
            Language lang = new Language(toLanguage.Name, path);

            // Add it
            LanguageManager.AddLanguage(lang);

            // Return failed translations as array
            return(translationFailed.ToArray());
        }