Example #1
0
        /// <inheritdocs />
        public CultureDictionary GetDictionary(CultureInfo culture, bool disableCache = false)
        {
            var cacheKeyPrefix = CacheKeyPrefix + culture.Name;

            if (disableCache)
            {
                _cache.Remove(cacheKeyPrefix);
            }

            var cachedDictionary = _cache.GetOrCreate(cacheKeyPrefix, k => new Lazy <CultureDictionary>(() =>
            {
                var rule = DefaultPluralRule;

                foreach (var provider in _pluralRuleProviders)
                {
                    if (provider.TryGetRule(culture, out rule))
                    {
                        break;
                    }
                }

                var dictionary = new CultureDictionary(culture.Name, rule ?? DefaultPluralRule);
                _translationProvider.LoadTranslations(culture, dictionary);

                return(dictionary);
            }, LazyThreadSafetyMode.ExecutionAndPublication));

            return(cachedDictionary.Value);
        }
Example #2
0
        public string Replace(CultureDictionary cultureDictionary, string text)
        {
            if (cultureDictionary == null)
            {
                throw new ArgumentNullException(nameof(cultureDictionary));
            }

            string ReplaceNuggets(Match match)
            {
                var textExclNugget = match.Groups[1].Value;
                var searchText     = textExclNugget;

                var textExclNuggetPosition = textExclNugget.IndexOf("///", StringComparison.Ordinal);

                if (textExclNuggetPosition >= 0)
                {
                    searchText = textExclNugget.Substring(0, textExclNuggetPosition);
                }

                var translationText = cultureDictionary[searchText];

                return(translationText ?? searchText);
            }

            return(NuggetRegex.Replace(text, ReplaceNuggets));
        }
 public void LoadTranslations(string cultureName, CultureDictionary dictionary)
 {
     foreach (var location in _poFilesLocationProvider.GetLocations(cultureName))
     {
         LoadFileToDictionary(location, dictionary);
     }
 }
        public void IndexerReturnNullIfKeyDoesntExist()
        {
            var dictionary  = new CultureDictionary("cs", _csPluralRule);
            var key         = new CultureDictionaryRecordKey("ball");
            var translation = dictionary[key];

            Assert.Null(translation);
        }
        private void SetupDictionary(string cultureName, IEnumerable <CultureDictionaryRecord> records, PluralizationRuleDelegate pluralRule)
        {
            var dictionary = new CultureDictionary(cultureName, pluralRule);

            dictionary.MergeTranslations(records);

            _localizationManager.Setup(o => o.GetDictionary(It.Is <CultureInfo>(c => c.Name == cultureName))).Returns(dictionary);
        }
Example #6
0
        public void IntexerThrowsPluralFormNotFoundExceptionIfSpecifiedPluralFormDoesntExist()
        {
            var dictionary = new CultureDictionary("cs", _csPluralRule);
            var record     = new CultureDictionaryRecord("ball", null, new[] { "míč", "míče" });

            dictionary.MergeTranslations(new[] { record });

            Assert.Throws <PluralFormNotFoundException>(() => dictionary["ball", 5]);
        }
        public void MergeAddsRecordToEmptyDictionary()
        {
            var dictionary = new CultureDictionary("cs", _csPluralRule);
            var record     = new CultureDictionaryRecord("ball", "míč", "míče", "míčů");

            dictionary.MergeTranslations(new[] { record });

            Assert.Equal(dictionary.Translations[record.Key], record.Translations);
        }
        public void MergeOverwritesTranslationsForSameKeys()
        {
            var dictionary = new CultureDictionary("cs", _csPluralRule);
            var record     = new CultureDictionaryRecord("ball", "míč", "míče", "míčů");
            var record2    = new CultureDictionaryRecord("ball", "balón", "balóny", "balónů");

            dictionary.MergeTranslations(new[] { record });
            dictionary.MergeTranslations(new[] { record2 });

            Assert.Equal(dictionary.Translations[record.Key], record2.Translations);
        }
Example #9
0
        public PortableObjectStringLocalizer(CultureInfo culture, string context, ILocalizationManager localizationManager, ILogger logger)
        {
            Context = context;
            _localizationManager = localizationManager;
            _logger     = logger;
            _dictionary = localizationManager.GetDictionary(culture);

            if (culture.Parent != null)
            {
                _parentCultureDictionary = localizationManager.GetDictionary(culture.Parent);
            }
        }
 private void LoadFileToDictionary(string path, CultureDictionary dictionary)
 {
     if (File.Exists(path))
     {
         using (var stream = File.OpenRead(path))
         {
             using (var reader = new StreamReader(stream))
             {
                 dictionary.MergeTranslations(_parser.Parse(reader));
             }
         }
     }
 }
 private void LoadFileToDictionary(IFileInfo fileInfo, CultureDictionary dictionary)
 {
     if (fileInfo.Exists && !fileInfo.IsDirectory)
     {
         using (var stream = fileInfo.CreateReadStream())
         {
             using (var reader = new StreamReader(stream))
             {
                 dictionary.MergeTranslations(_parser.Parse(reader));
             }
         }
     }
 }
        public void IndexerThrowsPluralFormNotFoundExceptionIfSpecifiedPluralFormDoesntExist()
        {
            // Arrange
            var dictionary = new CultureDictionary("cs", _csPluralRule);
            var record     = new CultureDictionaryRecord("ball", "míč", "míče");

            dictionary.MergeTranslations(new[] { record });

            Assert.Throws <PluralFormNotFoundException>(() =>
            {
                var key = new CultureDictionaryRecordKey("ball");

                return(dictionary[key, 5]);
            });
        }
Example #13
0
        public void IndexerThrowsPluralFormNotFoundExceptionIfSpecifiedPluralFormDoesntExist()
        {
            // Arrange
            var dictionary = new CultureDictionary("cs", _csPluralRule);
            var record     = new CultureDictionaryRecord("ball", "míč", "míče");

            dictionary.MergeTranslations(new[] { record });

            // Act & Assert
            var exception = Assert.Throws <PluralFormNotFoundException>(() => dictionary["ball", 5]);

            Assert.Equal("ball", exception.Form.Key);
            Assert.Equal(_csPluralRule(5), exception.Form.Form);
            Assert.Equal("cs", exception.Form.Culture.Name);
        }
Example #14
0
        private void BuildJsonRecursive(XElement currentComplexType, Dictionary <string, ElementMetadata> allElements,
                                        string parentTrail, CultureDictionary allTexts)
        {
            // Process attributes
            AddAttributeElements(currentComplexType, allElements, parentTrail);

            // Iterate over children
            var sequenceElements = GetSequenceElementsFromComplexType(currentComplexType);

            if (sequenceElements.Any())
            {
                var propertyNamesUsed = new List <string>();
                foreach (var childElement in sequenceElements)
                {
                    ProcessChildElement(currentComplexType, childElement, allElements, parentTrail, propertyNamesUsed,
                                        allTexts);
                }
            }
        }
        public void EnumerateCultureDictionary()
        {
            // Arrange
            var dictionary = new CultureDictionary("ar", _arPluralRule);

            dictionary.MergeTranslations(new List <CultureDictionaryRecord>
            {
                new CultureDictionaryRecord("Hello", "مرحبا"),
                new CultureDictionaryRecord("Bye", "مع السلامة")
            });

            // Act & Assert
            Assert.NotEmpty(dictionary);

            foreach (var record in dictionary)
            {
                Assert.Single(record.Translations);
            }

            Assert.Equal(2, dictionary.Count());
        }
Example #16
0
        /// <summary>
        ///     Parses Seres XSD into JSON
        /// </summary>
        /// <exception cref="Exception">
        ///     Throws Exception if XSD does not have root element or complexType
        /// </exception>
        /// <param name="org">The current organization</param>
        /// <param name="service">The current service</param>
        /// <param name="xsd">
        ///     Seres XSD
        /// </param>
        /// <param name="secondaryXsds">
        ///     Any secondary XSD refers from the main XSD
        /// </param>
        /// <returns>
        ///     ServiceMetadata object representing the XSD
        /// </returns>
        public ServiceMetadata ParseXsdToServiceMetadata(
            string org,
            string service,
            XDocument xsd,
            Dictionary <string, XDocument> secondaryXsds)
        {
            var serviceMetadata = new ServiceMetadata
            {
                Elements       = new Dictionary <string, ElementMetadata>(),
                RepositoryName = service,
                Org            = org,
            };

            this.xsd           = xsd;
            this.secondaryXsds = secondaryXsds;

            if (secondaryXsds != null)
            {
                var imports = xsd.Root.Elements(XDocName.Import);
                foreach (var import in imports)
                {
                    var schemaLocation = import.AttributeValue("schemaLocation");
                    secondaryXsdsByNamespace.Add(
                        import.GetPrefixOfNamespace(XNamespace.Get(import.AttributeValue("namespace"))),
                        secondaryXsds["\"" + schemaLocation + "\""]);
                }
            }

            var rootElement = xsd.Root.Element(XDocName.Element);

            if (rootElement == null)
            {
                throw new Exception("XSD missing root element...");
            }

            var      rootName        = rootElement.AttributeValue("name");
            var      rootTypeName    = rootElement.AttributeValue("type");
            XElement rootComplexType = null;

            if (string.IsNullOrEmpty(rootTypeName))
            {
                rootElement = xsd.Root.Element(XDocName.Element);
                if (rootElement == null)
                {
                    throw new Exception("XSD without root is a bad idea...");
                }

                rootComplexType = rootElement.Element(XDocName.ComplexType);
                if (rootComplexType == null)
                {
                    throw new Exception("XSD missing root complexType...");
                }
            }
            else
            {
                rootComplexType = GetComplexTypeByNameAttribute(rootTypeName);
            }

            var rootMetadata = new ElementMetadata
            {
                ID       = rootName,
                Name     = rootName,
                XPath    = "/" + rootName,
                Type     = ElementType.Group,
                TypeName = SanitizeName(!string.IsNullOrEmpty(rootTypeName) ? rootTypeName : rootName),
            };

            if (rootElement == null)
            {
                throw new Exception("XSD missing root complex type element...");
            }

            var existingTexts = _repository.GetServiceTexts(org, service);

            if (existingTexts == null)
            {
                existingTexts = new Dictionary <string, Dictionary <string, string> >();
            }

            var allTexts = new CultureDictionary();

            _complexTypes = new HashSet <string>();

            // Build metadata recursively
            BuildJsonRecursive(rootComplexType, serviceMetadata.Elements, "/" + rootName, allTexts);

            foreach (var cultureString in allTexts)
            {
                if (!existingTexts.ContainsKey(cultureString.Key))
                {
                    existingTexts.Add(cultureString.Key, new Dictionary <string, string>());
                }

                foreach (var localizedString in cultureString.Value)
                {
                    if (!existingTexts[cultureString.Key].ContainsKey(localizedString.Key))
                    {
                        existingTexts[cultureString.Key].Add(localizedString.Key, localizedString.Value);
                    }
                }
            }

            _repository.SaveServiceTexts(org, service, existingTexts);

            serviceMetadata.Elements.Add(rootName, rootMetadata);

            return(serviceMetadata);
        }
        private CultureDictionary LoadCulture(string moduleName, CultureInfo culture)
        {
            string key = string.Format("Dictionary.Culture:{0}.Module{1}", culture.Name, moduleName);

            CultureDictionary cachedObject = this.cacheProvider.Get<CultureDictionary>(key);

            if (cachedObject == null)
            {
                cachedObject = new CultureDictionary
                                   {
                                       Culture = culture,
                                       Translations = this.LoadTranslations(moduleName, culture)
                                   };
                this.cacheProvider.Put(key, cachedObject, TimeSpan.FromDays(1));
            }

            return cachedObject;
        }
Example #18
0
        private void BuildJsonRecursive(
            XElement currentComplexType,
            Dictionary <string, ElementMetadata> allElements,
            string parentTrail,
            CultureDictionary allTexts)
        {
            var typeName = currentComplexType.AttributeValue("name");

            if (!string.IsNullOrEmpty(typeName))
            {
                if (_complexTypes.Contains(typeName))
                {
                    return;
                }
                else
                {
                    _complexTypes.Add(typeName);
                }
            }

            // Process attributes
            AddAttributeElements(currentComplexType, allElements, parentTrail);

            // Iterate over children
            var sequenceElements = GetSequenceElementsFromComplexType(currentComplexType);

            if (sequenceElements.Any())
            {
                foreach (var childElement in sequenceElements)
                {
                    if (childElement.Name.Equals(XDocName.Choice))
                    {
                        // expand choice
                        var choiceElements = ExtractAllElementDeclarationsInTree(childElement);

                        foreach (var element in choiceElements)
                        {
                            string minOccurs = element.AttributeValue("minOccurs");
                            if (string.IsNullOrEmpty(minOccurs))
                            {
                                element.AddAttribute("minOccurs", "0");
                            }
                            else
                            {
                                element.Attribute("minOccurs").Value = "0";
                            }

                            ProcessChildElement(
                                currentComplexType,
                                element,
                                allElements,
                                parentTrail,
                                allTexts);
                        }
                    }
                    else
                    {
                        ProcessChildElement(
                            currentComplexType,
                            childElement,
                            allElements,
                            parentTrail,
                            allTexts);
                    }
                }
            }
        }
Example #19
0
        private void ProcessChildElement(
            XElement currentComplexType,
            XElement childElement,
            Dictionary <string, ElementMetadata> allElements,
            string parentTrail,
            CultureDictionary allTexts,
            string parentName = null)
        {
            var elementMetadata = new ElementMetadata();

            var currentElement   = childElement;
            var actualElement    = currentElement;
            var currentIsComplex = false;
            var skipRecursive    = false;
            var typeName         = string.Empty;

            if (!string.IsNullOrEmpty(childElement.AttributeValue("ref")))
            {
                // Load the referenced element
                var reference = childElement.AttributeValue("ref");
                if (reference.Split(':').Count() == 2)
                {
                    var name = reference.Split(':')[0];
                    var type = reference.Split(':')[1];

                    typeName       = type;
                    currentElement = GetXElementByNameAttribute(type, secondaryXsdsByNamespace[name]);
                    actualElement  = currentElement;
                }
                else
                {
                    typeName       = reference;
                    currentElement = GetXElementByNameAttribute(reference);
                    actualElement  = currentElement;
                }
            }

            if (!string.IsNullOrEmpty(currentElement.AttributeValue("type")) &&
                !currentElement.AttributeValue("type").Contains(":"))
            {
                // Load the type definition
                actualElement = GetComplexTypeByNameAttribute(currentElement.AttributeValue("type"));
                if (actualElement == null)
                {
                    actualElement = GetSimpleTypeByNameAttribute(currentElement.AttributeValue("type"));
                }
                else
                {
                    currentIsComplex = true;
                }

                typeName = currentElement.AttributeValue("type");
            }
            else
            {
                if (currentElement.Element(XDocName.SimpleType) != null)
                {
                    // Get the direct child simple type
                    typeName         = currentElement.AttributeValue("name");
                    actualElement    = currentElement.Element(XDocName.SimpleType);
                    currentIsComplex = false;
                }
                else
                {
                    if (currentElement.Element(XDocName.ComplexType) != null)
                    {
                        // Get the direct child complex type
                        typeName      = currentElement.AttributeValue("name");
                        actualElement = currentElement.Element(XDocName.ComplexType);

                        if (actualElement.Element(XDocName.SimpleContent) != null)
                        {
                            var    simpleContent = actualElement.Element(XDocName.SimpleContent);
                            string xtraTypeName  = SanitizeName(typeName);

                            ProcessSimpleContent(
                                actualElement,
                                simpleContent,
                                allElements,
                                $"{parentTrail}/{xtraTypeName}",
                                typeName.Split('.')[0]);

                            AddAttributeElements(currentElement, allElements, $"{parentTrail}/{xtraTypeName}");
                            currentIsComplex = true;
                            skipRecursive    = true;
                        }
                        else
                        {
                            currentIsComplex = true;
                        }
                    }
                }
            }

            if (childElement.Name.Equals(XDocName.Any))
            {
                typeName = "Any";
            }

            elementMetadata.XName = typeName;
            var    classShortRefName = SanitizeName(typeName);
            string newTrail          = $"{parentTrail}/{typeName}";

            var elementName = classShortRefName;

            if (!string.IsNullOrEmpty(currentElement.AttributeValue("name")))
            {
                elementName           = SanitizeName(currentElement.AttributeValue("name"));
                elementMetadata.XName = currentElement.AttributeValue("name");

                newTrail = $"{parentTrail}/{elementName}";
            }

            elementMetadata.Name            = elementName;
            elementMetadata.TypeName        = classShortRefName;
            elementMetadata.XPath           = newTrail;
            elementMetadata.ID              = newTrail.Replace("/", ".").Substring(1);
            elementMetadata.ParentElement   = parentTrail.Replace("/", ".").Substring(1);
            elementMetadata.DataBindingName = GetDataBindingName(elementMetadata.ID);

            var currentElementAnnotations = GetAnnotationsForElement(currentElement, elementMetadata.ID);
            var childElementAnnotations   = GetAnnotationsForElement(childElement, elementMetadata.ID);
            var actualElementAnnotations  = GetAnnotationsForElement(actualElement, elementMetadata.ID);

            foreach (var resource in childElementAnnotations)
            {
                if (!currentElementAnnotations.ContainsKey(resource.Key))
                {
                    currentElementAnnotations.Add(resource.Key, resource.Value);
                }
            }

            foreach (var resource in actualElementAnnotations)
            {
                if (!currentElementAnnotations.ContainsKey(resource.Key))
                {
                    currentElementAnnotations.Add(resource.Key, resource.Value);
                }
            }

            if (allElements.ContainsKey(elementMetadata.ID + ".Value"))
            {
                var newElementAnnotations = new CultureDictionary();
                foreach (var resourceText in currentElementAnnotations)
                {
                    var oldIdParts = resourceText.Key.Split('.').ToList();
                    oldIdParts.Insert(oldIdParts.Count - 1, "Value");
                    var newKey = string.Join(".", oldIdParts.ToArray());

                    newElementAnnotations.Add(newKey, resourceText.Value);
                }

                currentElementAnnotations = newElementAnnotations;
            }

            string orid = GetOrid(elementMetadata.XName);

            foreach (var cultureString in currentElementAnnotations)
            {
                var newKey = ShortenKeyID(cultureString, orid);

                if (!allTexts.ContainsKey(cultureString.Key))
                {
                    allTexts.Add(newKey, cultureString.Value);
                }

                if (cultureString.Key.Split('.').Last().EndsWith(TextCategoryType.Label.ToString()))
                {
                    elementMetadata.Texts.Add(TextCategoryType.Label.ToString(), newKey);
                }
                else
                {
                    if (cultureString.Key.Split('.').Last().EndsWith(TextCategoryType.Help.ToString()))
                    {
                        elementMetadata.Texts.Add(TextCategoryType.Help.ToString(), newKey);
                    }
                    else
                    {
                        if (cultureString.Key.Split('.').Last().EndsWith(TextCategoryType.Error.ToString()))
                        {
                            elementMetadata.Texts.Add(TextCategoryType.Error.ToString(), newKey);
                        }
                        else
                        {
                            if (cultureString.Key.Split('.').Last().EndsWith(TextCategoryType.PlaceHolder.ToString()))
                            {
                                elementMetadata.Texts.Add(TextCategoryType.PlaceHolder.ToString(), newKey);
                            }
                        }
                    }
                }
            }

            if (allElements.ContainsKey(elementMetadata.ID + ".Value"))
            {
                allElements[elementMetadata.ID + ".Value"].Texts = elementMetadata.Texts;
                elementMetadata.Texts = new Dictionary <string, string>();
            }

            WriteRestrictions(elementMetadata, actualElement, childElement);

            string errorTextKey = null;

            if (currentElementAnnotations.Count(a => a.Key.Split('.').Last() == TextCategoryType.Error.ToString()) > 0)
            {
                errorTextKey =
                    currentElementAnnotations.FirstOrDefault(
                        a => a.Key.Split('.').Last() == TextCategoryType.Error.ToString()).Key;
            }

            if (errorTextKey != null)
            {
                foreach (var restriction in elementMetadata.Restrictions.Values)
                {
                    restriction.ErrortText = errorTextKey;
                }
            }

            if (!currentIsComplex)
            {
                elementMetadata.Type = ElementType.Field;
            }
            else
            {
                elementMetadata.Type = ElementType.Group;

                elementMetadata.DataBindingName = null;

                if (!skipRecursive)
                {
                    BuildJsonRecursive(actualElement, allElements, newTrail, allTexts);
                }
            }

            if (string.IsNullOrEmpty(elementMetadata.TypeName))
            {
                elementMetadata.TypeName = null;
            }

            if (allElements.ContainsKey(elementMetadata.ID))
            {
                elementMetadata.ID += _randomGen.Next();
            }

            allElements.Add(elementMetadata.ID, elementMetadata);
            AddSchemaReferenceInformation(currentComplexType, elementMetadata);
        }
Example #20
0
        private CultureDictionary GetAnnotationsForElement(XElement currentElement, string currentId)
        {
            var elements = new CultureDictionary();

            if (currentElement.Element(XDocName.Annotation) != null)
            {
                var annotationElement     = currentElement.Element(XDocName.Annotation);
                var documentationElements = annotationElement.Elements(XDocName.Documentation).ToList();
                if (documentationElements != null)
                {
                    foreach (var documentationElement in documentationElements)
                    {
                        var textElement = documentationElement.Element(XDocName.Tekst);
                        if (textElement != null)
                        {
                            var language = textElement.AttributeValue(XDocName.Lang);
                            var textType = textElement.AttributeValue(XDocName.TextType);
                            var text     = textElement.Value;

                            var key = currentId + ".TODO";

                            if (textType == "LEDE")
                            {
                                key = currentId + "." + TextCategoryType.Label;
                            }
                            else
                            {
                                if ((textType == "HJELP") || (textType == "DEF"))
                                {
                                    key = currentId + "." + TextCategoryType.Help;
                                }
                                else
                                {
                                    if (textType == "FEIL")
                                    {
                                        key = currentId + "." + TextCategoryType.Error;
                                    }
                                    else
                                    {
                                        if (textType == "HINT")
                                        {
                                            key = currentId + "." + TextCategoryType.PlaceHolder;
                                        }
                                    }
                                }
                            }

                            CultureString cultureString;
                            if (!elements.ContainsKey(key))
                            {
                                cultureString = new CultureString();
                                elements.Add(key, cultureString);
                            }
                            else
                            {
                                cultureString = elements[key];
                            }

                            if (language == "NOB")
                            {
                                cultureString.Add("nb-NO", text);
                            }
                            else
                            {
                                if (language == "NON")
                                {
                                    cultureString.Add("nn-NO", text);
                                }
                                else
                                {
                                    if (language == "EN")
                                    {
                                        cultureString.Add("en", text);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return(elements);
        }
Example #21
0
        /// <inheritdocs />
        public void LoadTranslations([JetBrains.Annotations.NotNull] CultureInfo cultureInfo, [JetBrains.Annotations.NotNull] CultureDictionary dictionary)
        {
            if (cultureInfo == null)
            {
                throw new ArgumentNullException(nameof(cultureInfo));
            }
            if (dictionary == null)
            {
                throw new ArgumentNullException(nameof(dictionary));
            }

            var fileInfos   = new List <IFileInfo>();
            var cultureName = cultureInfo.Name;

            fileInfos.AddRange(_poFilesLocationProvider.GetLocations(cultureName));

            foreach (var fileInfo in fileInfos.Where(fileInfo => !fileInfo.IsDirectory))
            {
                if (fileInfo.Exists)
                {
                    using var stream = fileInfo.CreateReadStream();
                    using var reader = new StreamReader(stream);
                    dictionary.MergeTranslations(_parser.Parse(reader));

                    _logger?.LogDebug($"Translations for culture found: {cultureName}. Translations available: {dictionary.Translations.Count}. Path: {fileInfo.PhysicalPath}.");
                    break;
                }

                _logger?.LogWarning($"Translation for culture was not found: {cultureName}. Path: {fileInfo.PhysicalPath}.");
            }
        }