public TranslationDictionary Load(string type, CultureInfo ci)
        {
            var key = $"{type}.{ci.Name}";
            var localPath = $"{_path}/{key}.json";
            var dictionary = new TranslationDictionary();
            if (!_fileSystem.Exists(localPath))
            {
                return dictionary;
            }
            try
            {
                var fileContent = _fileSystem.ReadAllText(localPath);
                try
                {
                    dictionary = JsonConvert.DeserializeObject<TranslationDictionary>(fileContent) ?? dictionary;
                }
                catch (Exception)
                {
                    _fileSystem.Move(localPath, localPath + new Guid() + ".err");
                    return new TranslationDictionary();

                }
                lock (_sync)
                {
                    TranslationDictionary dummy;
                    TranslationDictionaries.TryRemove(key, out dummy);
                    TranslationDictionaries.TryAdd(key, dictionary);
                }
                return dictionary;
            }
            catch (IOException)
            {
            }
            return new TranslationDictionary();
        }
        public void op_Add_Translation()
        {
            var obj = new TranslationDictionary<int>
                          {
                              new Translation<int>(123, "en")
                          };

            Assert.Equal(1, obj.Count);
        }
        public void op_Contains_Translation()
        {
            var item = new Translation<int>(123, "en");
            var obj = new TranslationDictionary<int>
                          {
                              item
                          };

            Assert.True(obj.Contains(item));
        }
Beispiel #4
0
        public async Task ChangeCultureAsync(string locale)
        {
            currentLocale = locale;
            var newdict = await FetchLanguageMethod(locale);

            newdict.OnAdd += TranslationAdded;
            if (_translations != null)
            {
                _translations.OnAdd -= TranslationAdded;
            }
            _translations = newdict;
            propertyChanged(nameof(Translations));
        }
        private void ValueMeter_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                this.SetRanges();

                this.Value = 0;
            }
            catch (Exception err)
            {
                MessageDisplay.Show(TranslationDictionary.Translate(err.InnerExceptionMessage()));
            }
        }
        private void ViSoDataGridPager_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                this.uxSearhLabel.Visibility = this.ShowSearch ? Visibility.Visible : Visibility.Collapsed;

                this.uxSearchTextBox.Visibility = this.ShowSearch ? Visibility.Visible : Visibility.Collapsed;
            }
            catch (Exception err)
            {
                MessageDisplay.Show(TranslationDictionary.Translate(err.InnerExceptionMessage()));
            }
        }
        private void RightButton_Clicked(object sender, RoutedEventArgs e)
        {
            try
            {
                this.pageIndex++;

                this.uxPageNumbers.SelectedIndex = this.pageIndex;
            }
            catch (Exception err)
            {
                MessageDisplay.Show(TranslationDictionary.Translate(err.InnerExceptionMessage()));
            }
        }
Beispiel #8
0
        public override void OnGUI(Rect rect, SerializedProperty property, GUIContent label)
        {
            // Grab every field
            SerializedProperty key        = property.FindPropertyRelative("key");
            SerializedProperty dictionary = property.FindPropertyRelative("dictionary");

            using (EditorGUI.PropertyScope scope = new EditorGUI.PropertyScope(rect, label, property))
            {
                // Calculate height
                float previewHeight = rect.height;
                rect.height    = EditorGUIUtility.singleLineHeight;
                previewHeight -= rect.height;
                Width          = rect.width;

                // Draw label of object
                property.isExpanded = EditorGUI.Foldout(rect, property.isExpanded, scope.content);
                if (property.isExpanded == true)
                {
                    // Indent
                    using (EditorGUI.IndentLevelScope indent = new EditorGUI.IndentLevelScope())
                    {
                        // Draw the properties regularly
                        rect = DrawFields(rect, key, dictionary);
                    }
                }
            }

            if (property.isExpanded == true)
            {
                // Indent
                using (EditorGUI.IndentLevelScope indent = new EditorGUI.IndentLevelScope())
                {
                    // Update status
                    TranslationDictionary translationDictionary = dictionary.objectReferenceValue as TranslationDictionary;
                    string translationKey = key.stringValue;
                    Status status         = UpdateMessageStatus(translationDictionary, translationKey);

                    // Draw preview
                    rect = DrawPreviewLabel(rect, status);

                    // Draw HelpBox
                    rect = DrawHelpBox(rect);

                    // Draw preview
                    rect = DrawTextPreview(rect, status, translationKey, translationDictionary);

                    // Show button to add a new translation key
                    rect = DrawButton(rect, status, translationDictionary, translationKey, dictionary);
                }
            }
        }
        private void SearchText_Changed(object sender, TextChangedEventArgs e)
        {
            try
            {
                if (this.uxSearchTextBox.Text.IsNullEmptyOrWhiteSpace())
                {
                    this.ItemsSource.Clear();

                    this.itemsSource.AddRange(this.holdList.ToArray());

                    this.holdList.Clear();

                    this.searchList.Clear();

                    this.SelectedPageChange?.Invoke(this, this.ItemsSource[this.pageIndex]);

                    this.uxSearchTextBox.Focus();

                    return;
                }

                if (this.holdList.Count == 0)
                {
                    this.holdList.AddRange(this.ItemsSource.Items);
                }

                string searchText = this.uxSearchTextBox.Text;

                ConcurrentBag <object> searchBag = new ConcurrentBag <object>();

                Parallel.ForEach(this.holdList, row =>
                {
                    if (row.ContainsValue(searchText, DataComparisonEnum.Contains))
                    {
                        searchBag.Add(row);
                    }
                });

                this.searchList.Clear();

                this.searchList.AddRange(searchBag);

                this.lastSearched = DateTime.Now;

                this.ChangeItemSource();
            }
            catch (Exception err)
            {
                MessageBox.Show(TranslationDictionary.Translate(err.InnerExceptionMessage()));
            }
        }
Beispiel #10
0
        public TranslationJob_POST(TranslationDictionary requests, Action <TranslationDictionary, string> OnTranslationReady)
        {
            _requests           = requests;
            _OnTranslationReady = OnTranslationReady;

            var data = GoogleTranslation.ConvertTranslationRequest(requests, false);

            WWWForm form = new WWWForm();

            form.AddField("action", "Translate");
            form.AddField("list", data[0]);

            www = new WWW(LocalizationManager.GetWebServiceURL(), form);
        }
        private int ExistsTranslationItem(TranslationDictionary dict, string word)
        {
            int i = 0;

            foreach (var item in dict.Translations)
            {
                if (item.Word.Text.Equals(word))
                {
                    return(i);
                }
                i++;
            }
            return(-1);
        }
Beispiel #12
0
        public override void PrintProperties(int level = 0)
        {
            base.PrintProperties(level);
            var tabs = new String('\t', level);

            if (TranslationDictionary.TryGetValue(Content.GetType(), out string name))
            {
                Console.Out.WriteLine(tabs + "Содержание: " + name);
            }
            else
            {
                Console.Out.WriteLine(tabs + "Содержание: " + Content.GetType().Name);
            }
        }
Beispiel #13
0
        /// <summary>
        /// Builds a string containing translation keys.
        /// </summary>
        /// <returns>One translation key per line, with name and value separated by a colon</returns>
        public string GetDictionary()
        {
            StringBuilder sb = new StringBuilder();

            foreach (var pair in TranslationDictionary)
            {
                sb.Append($"{pair.Key}: {pair.Value}");
                if (!pair.Equals(TranslationDictionary.Last()))
                {
                    sb.Append(Environment.NewLine);
                }
            }
            return(sb.ToString());
        }
Beispiel #14
0
 /// <summary>
 /// Sets translation keys from an array of lines.
 /// </summary>
 /// <param name="lines">The lines containing the colon-separated name and value of the translation keys</param>
 public void SetDictionary(string[] lines)
 {
     TranslationDictionary.Clear();
     foreach (var line in lines)
     {
         if (line.Contains(':'))
         {
             var split = line.Split(new[] { ':' }, 2);
             var key   = split[0];
             var val   = split[1].TrimStart();
             TranslationDictionary[key] = val;
         }
     }
 }
Beispiel #15
0
        private void InitializeDictionaryData()
        {
            foreach (string chapter in this.BookChapterCount)
            {
                this.bookChapterCount.Add(this.GetBookKey(chapter), this.GetChapterCount(chapter));
            }

            foreach (string verse in this.ChapterVerseCount)
            {
                this.chapterVerseCount.Add(this.GetChapterKey(verse), this.GetVerseCount(verse));
            }

            int xOffset = 1;

            for (int x = 0; x < this.OldTestamentBookNames.Length; ++x)
            {
                string bookKey = this.BuildBookKey((x + xOffset), TestamentEnum.O);

                this.keyToBookIndex.Add(bookKey, this.OldTestamentBookNames[x]);

                BookModel book = new BookModel
                {
                    BookKey  = bookKey,
                    BookName = TranslationDictionary.Translate(this.keyToBookIndex[bookKey])
                };

                this.LoadBookChapters(book);

                this.bookModels.Add(bookKey, book);
            }

            xOffset = 40;

            for (int x = 0; x < this.NewTestamentBookNames.Length; ++x)
            {
                string bookKey = this.BuildBookKey((x + xOffset), TestamentEnum.N);

                keyToBookIndex.Add(this.BuildBookKey((x + xOffset), TestamentEnum.N), this.NewTestamentBookNames[x]);

                BookModel book = new BookModel
                {
                    BookKey  = bookKey,
                    BookName = TranslationDictionary.Translate(this.keyToBookIndex[bookKey])
                };

                this.LoadBookChapters(book);

                this.bookModels.Add(bookKey, book);
            }
        }
        public void op_GetEnumerator()
        {
            var obj = new TranslationDictionary<int>
                          {
                              new Translation<int>(123, "en")
                          };

            foreach (var item in obj)
            {
                Assert.IsType<Translation<int>>(item);
                Assert.Equal(new Language("en"), item.Language);
                Assert.Equal(123, item.Value);
            }
        }
Beispiel #17
0
        public static TranslationDictionary CreateTranslationDictionary()
        {
            // Setup asset
            TranslationDictionary newAsset = CreateInstance <TranslationDictionary>();

            // Setup path to file
            string folderName  = AssetHelpers.GetSelectedFolder();
            string pathOfAsset = Path.Combine(folderName, DefaultFileName);

            pathOfAsset = AssetDatabase.GenerateUniqueAssetPath(pathOfAsset);

            // Create the asset, and prompt the user to rename it
            ProjectWindowUtil.CreateAsset(newAsset, pathOfAsset);
            return(newAsset);
        }
Beispiel #18
0
        public TranslatorService()
        {
            string XMLFileName = "TranslationDataBaseResources.xml";

            if (File.Exists(XMLFileName))
            {
                MyTranslationDictionary = TranslationDictionary.LoadNewDictionary(XMLFileName);
            }
            else
            {
                DummyTranslationXMLGenerator mygen = new DummyTranslationXMLGenerator();
                mygen.GenerateDummyData(XMLFileName);
                MyTranslationDictionary = TranslationDictionary.LoadNewDictionary(XMLFileName);
            }
        }
        private void PageSize_Changed(object sender, SelectionChangedEventArgs e)
        {
            e.Handled = true;

            try
            {
                this.ItemsSource.PageSize = this.uxPageSize.SelectedValue.ToInt32();

                this.ItemsSource.Refresh();
            }
            catch (Exception err)
            {
                MessageBox.Show(TranslationDictionary.Translate(err.InnerExceptionMessage()));
            }
        }
Beispiel #20
0
        public TranslationJob_POST(TranslationDictionary requests, GoogleTranslation.fnOnTranslationReady OnTranslationReady)
        {
            _requests           = requests;
            _OnTranslationReady = OnTranslationReady;

            var data = GoogleTranslation.ConvertTranslationRequest(requests, false);

            WWWForm form = new WWWForm();

            form.AddField("action", "Translate");
            form.AddField("list", data[0]);

            www = UnityWebRequest.Post(LocalizationManager.GetWebServiceURL(), form);
            I2Utils.SendWebRequest(www);
        }
        private void DictionaryViewer_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                if (!base.WasFirstLoaded && this.dictionaryModel.GetDictionaries.Length == 0)
                {
                    MessageDisplay.Show(TranslationDictionary.Translate("No dictionaries were installed. From the Online Menu select Downloads and select a Dictionary to install."));
                }

                base.WasFirstLoaded = true;
            }
            catch (Exception err)
            {
                ErrorLog.ShowError(err);
            }
        }
        public static string RebuildTranslation(string text, TranslationDictionary dict, string LanguageCodeTo)
        {
            if (!text.Contains("[i2s_"))
            {
                return(RebuildTranslation_Plural(text, dict, LanguageCodeTo));
            }

            var variants = SpecializationManager.GetSpecializations(text);
            var results  = new Dictionary <string, string>();

            foreach (var kvp in variants)
            {
                results[kvp.Key] = RebuildTranslation_Plural(kvp.Value, dict, LanguageCodeTo);
            }
            return(SpecializationManager.SetSpecializedText(results));
        }
        public void SaveTest()
        {
            // Arrange
            var type = "HomeController";
            var key = $"{type}.{CultureInfo.CurrentUICulture.Name}";
            var hostingEnvironmentTest = TestHostingEnvironment();
            var fileSystem = TestFileSytem();
            var cache = new JsonLocalizationCache(hostingEnvironmentTest, fileSystem.Object);

            //act
            var dict = new TranslationDictionary();
            dict["specific"] = new Translation() { str = "Culture specific", Added = new DateTime(1) };

            cache.Save(new KeyValuePair<string, TranslationDictionary>(key, dict));
            //assert
            fileSystem.Verify(m => m.WriteAllText(It.IsAny<string>(), It.IsAny<string>()), Times.Once());
        }
 public Localization()
 {
     Name         = "Unknown";
     Author       = "Unknown";
     General      = new TranslationDictionary();
     Options      = new TranslationDictionary();
     Character    = new TranslationDictionary();
     Dialogue     = new TranslationDictionary();
     Vendor       = new TranslationDictionary();
     Quest        = new TranslationDictionary();
     Condition    = new TranslationDictionary();
     Reward       = new TranslationDictionary();
     VendorItem   = new TranslationDictionary();
     Mistakes     = new TranslationDictionary();
     Notification = new TranslationDictionary();
     Interface    = new TranslationDictionary();
 }
Beispiel #25
0
        public TranslationDictionary CreateDictionary()
        {
            var dict = new TranslationDictionary();

            foreach (Translation translation in this)
            {
                if (!dict.ContainsKey(translation.Van))
                {
                    dict.Add(translation.Van, translation);
                }
                else
                {
                }
            }

            return(dict);
        }
Beispiel #26
0
        //private void LoadTranslationsDictionary(int languageId)
        //{
        //    List<TranslationMappingModel> translationMapping = BiblesData.Database
        //        .GetTranslationMapping(languageId);

        //    List<DataItemModel> translationItems = new List<DataItemModel>();

        //    foreach(TranslationMappingModel mapping in translationMapping)
        //    {
        //        translationItems.Add(new DataItemModel
        //        {
        //            ItemKey = mapping.EnglishLanguage.UnzipFile().ParseToString(),
        //            DisplayValue = mapping.OtherLanguage.UnzipFile().ParseToString()
        //        });
        //    }

        //    TranslationDictionary.LoadTransaltionFile(translationItems);
        //}

        private void SetMenuTranslation(MenuItem item)
        {
            item.Header = TranslationDictionary.Translate(item.Header.ParseToString());

            if (item.Items != null)
            {
                foreach (object child in item.Items)
                {
                    if (child.GetType() != typeof(MenuItem))
                    {
                        continue;
                    }

                    this.SetMenuTranslation((MenuItem)child);
                }
            }
        }
        private void Colour_Clicked(object sender, System.Windows.RoutedEventArgs e)
        {
            try
            {
                ActionButton button = (ActionButton)sender;

                this.SelectedColour = button.Background;

                this.DialogResult = true;

                this.Close();
            }
            catch (Exception err)
            {
                MessageDisplay.Show(TranslationDictionary.Translate(err.InnerExceptionMessage()));
            }
        }
Beispiel #28
0
        public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
        {
            float height = EditorGUIUtility.singleLineHeight;

            if (property.isExpanded == true)
            {
                // Grab every field
                SerializedProperty key        = property.FindPropertyRelative("key");
                SerializedProperty dictionary = property.FindPropertyRelative("dictionary");

                // Allocate key field
                height += EditorHelpers.GetHeight(2);

                // Update status
                TranslationDictionary translationDictionary = dictionary.objectReferenceValue as TranslationDictionary;
                string translationKey = key.stringValue;
                Status status         = UpdateMessageStatus(translationDictionary, translationKey);

                // Check status
                if (string.IsNullOrEmpty(Message) == false)
                {
                    // Allocate help box
                    height += EditorHelpers.VerticalMargin;
                    height += EditorHelpers.GetHelpBoxHeight(Message, Width);
                }

                // Check button
                if (IsButtonDrawn(status) == true)
                {
                    // Allocate button
                    height += EditorHelpers.VerticalMargin;
                    height += ButtonHeight;
                }

                // Check preview
                if (IsTextPreviewDrawn(status) == true)
                {
                    // Allocate preview
                    height += EditorHelpers.VerticalSpace;
                    height += EditorGUIUtility.singleLineHeight;
                    height += TextPreview.CalculateHeight(null, !translationDictionary.IsAllTranslationsSerialized);
                }
            }
            return(height);
        }
        private void LoadTranslationsDictionary(int languageId)
        {
            List <TranslationMappingModel> translationMapping = BiblesData.Database
                                                                .GetTranslationMapping(languageId);

            List <DataItemModel> translationItems = new List <DataItemModel>();

            foreach (TranslationMappingModel mapping in translationMapping)
            {
                translationItems.Add(new DataItemModel
                {
                    ItemKey      = mapping.EnglishLanguage.UnzipFile().ParseToString(),
                    DisplayValue = mapping.OtherLanguage.UnzipFile().ParseToString()
                });
            }

            TranslationDictionary.LoadTransaltionFile(translationItems);
        }
Beispiel #30
0
        public static List <string> ConvertTranslationRequest(TranslationDictionary requests, bool encodeGET)
        {
            List <string> results = new List <string>();
            var           sb      = new StringBuilder();

            foreach (var kvp in requests)
            {
                var request = kvp.Value;
                if (sb.Length > 0)
                {
                    sb.Append("<I2Loc>");
                }

                sb.Append(GoogleLanguages.GetGoogleLanguageCode(request.LanguageCode));
                sb.Append(":");
                for (int i = 0; i < request.TargetLanguagesCode.Length; ++i)
                {
                    if (i != 0)
                    {
                        sb.Append(",");
                    }
                    sb.Append(GoogleLanguages.GetGoogleLanguageCode(request.TargetLanguagesCode[i]));
                }
                sb.Append("=");

                var text = (TitleCase(request.Text) == request.Text) ? request.Text.ToLowerInvariant() : request.Text;

                if (!encodeGET)
                {
                    sb.Append(text);
                }
                else
                {
                    sb.Append(Uri.EscapeDataString(text));
                    if (sb.Length > 4000)
                    {
                        results.Add(sb.ToString());
                        sb.Length = 0;
                    }
                }
            }
            results.Add(sb.ToString());
            return(results);
        }
        public static string ParseTranslationResult(string html, TranslationDictionary requests)
        {
            //Debug.Log(html);
            // Handle google restricting the webservice to run
            if (html.StartsWith("<!DOCTYPE html>") || html.StartsWith("<HTML>"))
            {
                if (html.Contains("The script completed but did not return anything"))
                {
                    return("The current Google WebService is not supported.\nPlease, delete the WebService from the Google Drive and Install the latest version.");
                }
                else
                if (html.Contains("Service invoked too many times in a short time"))
                {
                    return(""); // ignore and try again
                }
                else
                {
                    return("There was a problem contacting the WebService. Please try again later\n" + html);
                }
            }

            string[] texts    = html.Split(new string[] { "<I2Loc>" }, StringSplitOptions.None);
            string[] splitter = new string[] { "<i2>" };
            int      i        = 0;

            var Keys = requests.Keys.ToArray();

            foreach (var text in Keys)
            {
                var temp = requests[text];
                temp.Results = texts[i++].Split(splitter, StringSplitOptions.None);

                // Google has problem translating this "This Is An Example"  but not this "this is an example"
                if (TitleCase(text) == text)
                {
                    for (int j = 0; j < temp.Results.Length; ++j)
                    {
                        temp.Results[j] = TitleCase(temp.Results[j]);
                    }
                }
                requests[text] = temp;
            }
            return(null);
        }
        private void OnDelete_Clicked(object sender, System.Windows.RoutedEventArgs e)
        {
            if (this.uxLinkTree.SelectedItem == null)
            {
                MessageDisplay.Show("Please select a Link");

                return;
            }

            try
            {
                string verseKey = ((TreeViewItemTool)this.uxLinkTree.SelectedItem).Tag.ParseToString();

                if (!this.modelsLinksDictionary.ContainsKey(verseKey))
                {
                    MessageDisplay.Show("Cannot delete topmost parent item.");

                    return;
                }

                string message = $"{TranslationDictionary.Translate("Are you sure you would like to delete?")} {GlobalStaticData.Intance.GetKeyDescription(verseKey)}";

                if (MessageDisplay.Show(message, "Warning", MessageBoxButton.YesNo) != MessageBoxResult.Yes)
                {
                    return;
                }

                ModelsLink deleteItem = this.modelsLinksDictionary[verseKey];

                BiblesData.Database.DeleteLink(deleteItem.LinkKeyId);

                this.modelsLinksDictionary.Remove(verseKey);

                TreeViewItemTool deleteTreeItemParent = ((TreeViewItemTool)this.uxLinkTree.SelectedItem).Parent.To <TreeViewItemTool>();

                deleteTreeItemParent.Items.Remove(this.uxLinkTree.SelectedItem);

                this.deletedLinksList.Add(verseKey);
            }
            catch (Exception err)
            {
                ErrorLog.ShowError(err);
            }
        }
        public static void WriteFile(string filePath, TranslationDictionary data)
        {
            SupportedLanguages languages = data.SupportedLanguages;

            using (StreamWriter writer = new StreamWriter(filePath, false, Encoding.UTF8))
            {
                // Write the key column
                writer.Write(KeyColumnName);

                // Go through all the languages
                for (int index = 0; index < languages.Count; ++index)
                {
                    // Write the divider
                    writer.Write(Divider);

                    // Write the language
                    WriteString(writer, languages[index]);
                }

                // Go through all the translations
                foreach (KeyValuePair <string, TranslationDictionary.LanguageTextMap> translation in data.AllTranslations)
                {
                    // Delimit the header
                    writer.Write(Newline);

                    // Write the key value
                    WriteString(writer, translation.Key);

                    // Go through all the languages
                    for (int index = 0; index < languages.Count; ++index)
                    {
                        if (translation.Value.SupportedLanguages.Contains(index) == true)
                        {
                            // Write the divider
                            writer.Write(Divider);

                            // Write the text
                            WriteString(writer, translation.Value[index]);
                        }
                    }
                }
            }
        }
        public void TranslateTest()
        {
            TranslationDictionary myTransDict = new TranslationDictionary();

            myTransDict.Languages = new Language[] {
                new Language("german", new Word[] {
                    new Word("hallo", "hello"),
                    new Word("der", "the"),
                    new Word("sein", "to be")
                }),
                new Language("chinese", new Word[] {
                    new Word("nihau", "hello"),
                    new Word("li", "the"),
                    new Word("lihe", "to be")
                })
            };
            Assert.AreEqual("hallo", myTransDict.Translate("nihau", "german"));
            Assert.AreEqual("li", myTransDict.Translate("der", "chinese"));
        }
        public async Task <TranslationDictionary> ReadKindleMateExportedDictionaryAsync(string kindleMateFile)
        {
            var dict = new TranslationDictionary
            {
                Translations = new List <TranslationItem>()
            };
            var             content         = File.ReadAllLines(kindleMateFile);
            bool            isWord          = true;
            var             word            = "";
            int             emptyLineNum    = 0;
            TranslationItem translationItem = new TranslationItem();

            foreach (var line in content)
            {
                if (string.IsNullOrWhiteSpace(line))
                {
                    isWord = true;
                    emptyLineNum++;
                    word = "";
                    if (emptyLineNum % 2 == 0)
                    {
                        var index = ExistsTranslationItem(dict, translationItem.Word.Text);
                        if (index == -1)
                        {
                            dict.Translations.Add(translationItem);
                        }
                        else
                        {
                            if (dict.Translations[index].Sentence.Text != translationItem.Sentence.Text)
                            {
                                dict.Translations[index].Sentence.Text += translationItem.Sentence.Text;
                            }
                        }

                        isWord = true;
                    }
                    continue;
                }
                if (isWord)
                {
                    var startWord = line.IndexOf("(") + 1;
                    var endWord   = line.IndexOf(")");
                    word            = line[startWord..endWord];
        public void ctor_SerializationInfo_StreamingContext()
        {
            var expected = new TranslationDictionary<int>
                               {
                                   new Translation<int>(123, "en")
                               };
            TranslationDictionary<int> actual;

            using (Stream stream = new MemoryStream())
            {
                var formatter = new BinaryFormatter();
                var obj = new TranslationDictionary<int>
                              {
                                  new Translation<int>(123, "en")
                              };
                formatter.Serialize(stream, obj);
                stream.Position = 0;
                actual = (TranslationDictionary<int>)formatter.Deserialize(stream);
            }

            Assert.Equal(expected, actual);
        }
 private IJsonLocalizationCache MockCache()
 {
     var cu = CultureInfo.CurrentUICulture;
     var mockJCache = new Mock<IJsonLocalizationCache>();
     var dicts = new TranslationDictionaries();
     var dictCultureSpecific = new TranslationDictionary(
         new Dictionary<string, Translation>
         {
             {"specific", new Translation {str = "Culture specific", Added = DateTime.Now}},
             {"StringOptions", new Translation {str = "{0}{{1|2}}{{a few words|more words|many words}}", Added = DateTime.Now}}
         });
     var dictCultureNeutral = new TranslationDictionary(
         new Dictionary<string, Translation>
         {
             {"neutral", new Translation {str = "Culture neutral", Added = DateTime.Now}}
         });
     var dictCultureInvariant = new TranslationDictionary(
         new Dictionary<string, Translation>
         {
             {"Invariant", new Translation {str = "Culture Invariant", Added = DateTime.Now}}
         });
     mockJCache.Setup(m => m.TranslationDictionaries).Returns(dicts);
     mockJCache.Setup(m => m.Load("HomeController", CultureInfo.CurrentUICulture)).Returns(dictCultureSpecific);
     mockJCache.Setup(m => m.Load("HomeController", CultureInfo.CurrentUICulture.Parent)).Returns(dictCultureNeutral);
     mockJCache.Setup(m => m.Load("HomeController", CultureInfo.CurrentUICulture.Parent.Parent)).Returns(dictCultureInvariant);
     return mockJCache.Object;
 }
        public CultureInfo AddMissingTranslation(string name, CultureInfo culture)
        {
            if (_defaultCulture == CultureType.Neutral && !culture.IsNeutralCulture)
            {
                culture = culture.Parent;
            }
            var key = $"{_type}.{culture.Name}";
            var dict = new TranslationDictionary();

            dict = _cache.TranslationDictionaries.GetOrAdd(key, dict);
            var trans = new Translation { str = _translater.TryTranslateWord(name, new CultureInfo("en-US"), culture) };
            dict.GetOrAdd(name, _ =>
            {
                _cache.Dirty = true;
                return trans;
            });
            return culture;
        }
        public void op_Remove_KeyStringPair()
        {
            var item = new Translation<int>(123, "en");
            var obj = new TranslationDictionary<int>
                          {
                              item
                          };

            Assert.True(obj.Remove(item));
            Assert.Equal(0, obj.Count);
        }
        public void prop_Current_whenFullTranslation()
        {
            var culture = Thread.CurrentThread.CurrentUICulture;
            try
            {
                const string language = "fr-FR";

                Thread.CurrentThread.CurrentUICulture = new CultureInfo(language);

                const int expected = 123;
                var obj = new TranslationDictionary<int>
                              {
                                  new Translation<int>(456, "fr"),
                                  new Translation<int>(expected, language)
                              };

                var actual = obj.Current;

                Assert.Equal(expected, actual);
            }
            finally
            {
                Thread.CurrentThread.CurrentUICulture = culture;
            }
        }
        public void prop_Current_whenInvariantTranslation()
        {
            var culture = Thread.CurrentThread.CurrentUICulture;
            try
            {
                Thread.CurrentThread.CurrentUICulture = new CultureInfo("fr-FR");

                const int expected = 123;
                var obj = new TranslationDictionary<int>
                              {
                                  new Translation<int>(expected, string.Empty),
                                  new Translation<int>(456, "fr-CA")
                              };

                var actual = obj.Current;

                Assert.Equal(expected, actual);
            }
            finally
            {
                Thread.CurrentThread.CurrentUICulture = culture;
            }
        }
 public string DictionaryToJsonOrderByKey(TranslationDictionary dict)
 {
     return "{" + string.Join(",", dict.OrderBy(d => d.Key).Select(d => string.Format(_jsonDictoronaryEntry, d.Key, d.Value.str, d.Value.Added))) + "}";
 }