Esempio n. 1
0
 private LocalizationResourceTranslationEntity ToTranslationEntity(DiscoveredTranslation translation)
 {
     return(new LocalizationResourceTranslationEntity
     {
         Language = translation.Culture, Translation = translation.Translation, ModificationDate = DateTime.UtcNow
     });
 }
        public ICollection <DiscoveredResource> GetClassLevelResources(Type target, string resourceKeyPrefix)
        {
            var translation = target.Name;

            try
            {
                var category = (Activator.CreateInstance(target) as Category);
                if (!string.IsNullOrEmpty(category?.Name))
                {
                    translation = category.Name;
                }
            }
            catch (Exception) { }


            return(new List <DiscoveredResource>
            {
                new DiscoveredResource(null,
                                       $"/categories/category[@name=\"{target.Name}\"]/description",
                                       DiscoveredTranslation.FromSingle(translation),
                                       target.Name,
                                       target,
                                       typeof(string),
                                       true)
            });
        }
Esempio n. 3
0
        public static ICollection <DiscoveredTranslation> GetAllTranslations(MemberInfo mi, string resourceKey, string defaultTranslation)
        {
            var translations           = DiscoveredTranslation.FromSingle(defaultTranslation);
            var additionalTranslations = mi.GetCustomAttributes <TranslationForCultureAttribute>();

            if (additionalTranslations != null && additionalTranslations.Any())
            {
                if (additionalTranslations.GroupBy(t => t.Culture).Any(g => g.Count() > 1))
                {
                    throw new DuplicateResourceTranslationsException($"Duplicate translations for the same culture for following resource: `{resourceKey}`");
                }

                additionalTranslations.ForEach(t =>
                {
                    var existingTranslation = translations.FirstOrDefault(_ => _.Culture == t.Culture);
                    if (existingTranslation != null)
                    {
                        existingTranslation.Translation = t.Translation;
                    }
                    else
                    {
                        translations.Add(new DiscoveredTranslation(t.Translation, t.Culture));
                    }
                });
            }

            return(translations);
        }
Esempio n. 4
0
        public IEnumerable <DiscoveredResource> GetDiscoveredResources(
            Type target,
            object instance,
            MemberInfo mi,
            string translation,
            string resourceKey,
            string resourceKeyPrefix,
            bool typeKeyPrefixSpecified,
            bool isHidden,
            string typeOldName,
            string typeOldNamespace,
            Type declaringType,
            Type returnType,
            bool isSimpleType)
        {
            // try to fetch also [Display()] attribute to generate new "...-Description" resource => usually used for help text labels
            var displayAttribute = mi.GetCustomAttribute <DisplayAttribute>();

            if (displayAttribute?.Description == null)
            {
                yield break;
            }
            var propertyName    = $"{mi.Name}-Description";
            var oldResourceKeys = OldResourceKeyBuilder.GenerateOldResourceKey(target, propertyName, mi,
                                                                               resourceKeyPrefix, typeOldName, typeOldNamespace);

            var translations = new List <DiscoveredTranslation>();

            translations.AddRange(DiscoveredTranslation.FromSingle(displayAttribute.Description));
            var validationTranslations = mi.GetCustomAttributes <DisplayTranslationForCultureAttribute>();

            foreach (var validationTranslationAttribute in validationTranslations)
            {
                var validationAttributeName = displayAttribute.GetType().Name;
                if (validationAttributeName.EndsWith("Attribute"))
                {
                    validationAttributeName =
                        validationAttributeName.Substring(0,
                                                          validationAttributeName.LastIndexOf("Attribute", StringComparison.Ordinal));
                }
                translations.Add(new DiscoveredTranslation(validationTranslationAttribute.Translation,
                                                           validationTranslationAttribute.Culture));
            }

            yield return(new DiscoveredResource(mi,
                                                $"{resourceKey}",
                                                translations,
                                                propertyName,
                                                declaringType,
                                                returnType,
                                                isSimpleType)
            {
                TypeName = target.Name,
                TypeNamespace = target.Namespace,
                TypeOldName = oldResourceKeys.Item2,
                TypeOldNamespace = typeOldNamespace,
                OldResourceKey = oldResourceKeys.Item1
            });
        }
        public IEnumerable <DiscoveredResource> GetDiscoveredResources(
            Type target,
            object instance,
            MemberInfo mi,
            string translation,
            string resourceKey,
            string resourceKeyPrefix,
            bool typeKeyPrefixSpecified,
            bool isHidden,
            string typeOldName,
            string typeOldNamespace,
            Type declaringType,
            Type returnType,
            bool isSimpleType)
        {
            var keyAttributes        = mi.GetCustomAttributes <ResourceKeyAttribute>().ToList();
            var validationAttributes = mi.GetCustomAttributes <ValidationAttribute>().ToList();

            if (keyAttributes.Count > 1 && validationAttributes.Any())
            {
                throw new InvalidOperationException("Model with data annotation attributes cannot have more than one `[ResourceKey]` attribute.");
            }

            foreach (var validationAttribute in validationAttributes)
            {
                if (validationAttribute.GetType() == typeof(DataTypeAttribute))
                {
                    continue;
                }

                if (keyAttributes.Any())
                {
                    resourceKey = keyAttributes.First().Key;
                }

                var validationResourceKey = ResourceKeyBuilder.BuildResourceKey(resourceKey, validationAttribute);
                var propertyName          = validationResourceKey.Split('.').Last();

                var oldResourceKeys = OldResourceKeyBuilder.GenerateOldResourceKey(target, propertyName, mi, resourceKeyPrefix, typeOldName, typeOldNamespace);

                yield return(new DiscoveredResource(mi,
                                                    validationResourceKey,
                                                    DiscoveredTranslation.FromSingle(string.IsNullOrEmpty(validationAttribute.ErrorMessage)
                                                                                         ? propertyName
                                                                                         : validationAttribute.ErrorMessage),
                                                    propertyName,
                                                    declaringType,
                                                    returnType,
                                                    isSimpleType)
                {
                    TypeName = target.Name,
                    TypeNamespace = target.Namespace,
                    TypeOldName = oldResourceKeys.Item2,
                    TypeOldNamespace = typeOldNamespace,
                    OldResourceKey = oldResourceKeys.Item1
                });
            }
        }
Esempio n. 6
0
        public IEnumerable <DiscoveredResource> GetDiscoveredResources(
            Type target,
            object instance,
            MemberInfo mi,
            string translation,
            string resourceKey,
            string resourceKeyPrefix,
            bool typeKeyPrefixSpecified,
            bool isHidden,
            string typeOldName,
            string typeOldNamespace,
            Type declaringType,
            Type returnType,
            bool isSimpleType)
        {
            // scan custom registered attributes (if any)
            foreach (var descriptor in ConfigurationContext.Current.CustomAttributes.ToList())
            {
                var customAttributes = mi.GetCustomAttributes(descriptor.CustomAttribute);
                foreach (var customAttribute in customAttributes)
                {
                    var customAttributeKey = ResourceKeyBuilder.BuildResourceKey(resourceKey, customAttribute);
                    var propertyName       = customAttributeKey.Split('.').Last();
                    var oldResourceKeys    = OldResourceKeyBuilder.GenerateOldResourceKey(target,
                                                                                          propertyName,
                                                                                          mi,
                                                                                          resourceKeyPrefix,
                                                                                          typeOldName,
                                                                                          typeOldNamespace);
                    var foreignTranslation = string.Empty;
                    if (descriptor.GenerateTranslation)
                    {
                        var z1 = customAttribute.GetType().ToString();
                        var z2 = customAttribute.ToString();

                        foreignTranslation = !z1.Equals(z2) ? z2 : propertyName;
                    }

                    yield return(new DiscoveredResource(mi,
                                                        customAttributeKey,
                                                        DiscoveredTranslation.FromSingle(foreignTranslation),
                                                        propertyName,
                                                        declaringType,
                                                        returnType,
                                                        isSimpleType)
                    {
                        TypeName = target.Name,
                        TypeNamespace = target.Namespace,
                        TypeOldName = oldResourceKeys.Item2,
                        TypeOldNamespace = typeOldNamespace,
                        OldResourceKey = oldResourceKeys.Item1
                    });
                }
            }
        }
Esempio n. 7
0
        private static void AddTranslationScript(
            LocalizationResource existingResource,
            StringBuilder buffer,
            DiscoveredTranslation resource)
        {
            var existingTranslation = existingResource.Translations.FirstOrDefault(t => t.Language == resource.Culture);

            if (existingTranslation == null)
            {
                buffer.Append($@"
        INSERT INTO [dbo].[LocalizationResourceTranslations] (ResourceId, [Language], [Value], [ModificationDate]) VALUES ({existingResource.Id}, '{resource.Culture}', N'{resource.Translation.Replace("'", "''")}', GETUTCDATE())");
            }
            else if (existingTranslation.Value == null || !existingTranslation.Value.Equals(resource.Translation))
            {
                buffer.Append($@"
        UPDATE [dbo].[LocalizationResourceTranslations] SET [Value] = N'{resource.Translation.Replace("'", "''")}' WHERE ResourceId={existingResource.Id} and [Language]='{resource.Culture}'");
            }
        }
Esempio n. 8
0
        private static void AddTranslationScript(
            LocalizationResource existingResource,
            StringBuilder buffer,
            DiscoveredTranslation resource)
        {
            var existingTranslation = existingResource.Translations.FirstOrDefault(t => t.Language == resource.Culture);

            if (existingTranslation == null)
            {
                buffer.AppendLine(
                    $@"INSERT INTO public.""LocalizationResourceTranslations"" (""ResourceId"", ""Language"", ""Value"", ""ModificationDate"") VALUES ({existingResource.Id}, '{resource.Culture}', N'{resource.Translation.Replace("'", "''")}',  CAST(NOW() at time zone 'utc' AS timestamp));");
            }
            else if (!existingTranslation.Value.Equals(resource.Translation))
            {
                buffer.AppendLine(
                    $@"UPDATE public.""LocalizationResourceTranslations"" SET ""Value"" = N'{resource.Translation.Replace("'", "''")}' WHERE ResourceId={existingResource.Id} and ""Language""='{resource.Culture}';");
            }
        }
        public IEnumerable <DiscoveredResource> GetDiscoveredResources(
            Type target,
            object instance,
            MemberInfo mi,
            string translation,
            string resourceKey,
            string resourceKeyPrefix,
            bool typeKeyPrefixSpecified,
            bool isHidden,
            string typeOldName,
            string typeOldNamespace,
            Type declaringType,
            Type returnType,
            bool isSimpleType)
        {
            // try to fetch also [Display()] attribute to generate new "...-Description" resource => usually used for help text labels
            var displayAttribute = mi.GetCustomAttribute <DisplayAttribute>();

            if (displayAttribute?.Description != null)
            {
                var propertyName    = $"{mi.Name}-Description";
                var oldResourceKeys = OldResourceKeyBuilder.GenerateOldResourceKey(target, propertyName, mi, resourceKeyPrefix, typeOldName, typeOldNamespace);
                yield return(new DiscoveredResource(mi,
                                                    $"{resourceKey}-Description",
                                                    DiscoveredTranslation.FromSingle(displayAttribute.Description),
                                                    propertyName,
                                                    declaringType,
                                                    returnType,
                                                    isSimpleType)
                {
                    TypeName = target.Name,
                    TypeNamespace = target.Namespace,
                    TypeOldName = oldResourceKeys.Item2,
                    TypeOldNamespace = typeOldNamespace,
                    OldResourceKey = oldResourceKeys.Item1
                });
            }
        }
Esempio n. 10
0
        /// <summary>
        ///     Gets all translations.
        /// </summary>
        /// <param name="mi">The member info type to get resources from.</param>
        /// <param name="resourceKey">The resource key.</param>
        /// <param name="defaultTranslation">The default translation.</param>
        /// <returns>List of discovered resources</returns>
        /// <exception cref="DuplicateResourceTranslationsException">
        ///     Duplicate translations for the same culture for following
        ///     resource: `{resourceKey}`
        /// </exception>
        public static ICollection <DiscoveredTranslation> GetAllTranslations(MemberInfo mi, string resourceKey, string defaultTranslation)
        {
            var translations           = DiscoveredTranslation.FromSingle(defaultTranslation);
            var additionalTranslations = mi.GetCustomAttributes <TranslationForCultureAttribute>().ToList();

            if (!additionalTranslations.Any())
            {
                return(translations);
            }

            if (additionalTranslations.GroupBy(t => t.Culture).Any(g => g.Count() > 1))
            {
                throw new DuplicateResourceTranslationsException(
                          $"Duplicate translations for the same culture for following resource: `{resourceKey}`");
            }

            additionalTranslations.ForEach(t =>
            {
                // check if specified culture in attribute is actual culture
                if (!TryGetCultureInfo(t.Culture, out _))
                {
                    throw new ArgumentException($"Culture `{t.Culture}` for resource `{resourceKey}` is not supported.");
                }

                var existingTranslation = translations.FirstOrDefault(_ => _.Culture == t.Culture);
                if (existingTranslation != null)
                {
                    existingTranslation.Translation = t.Translation;
                }
                else
                {
                    translations.Add(new DiscoveredTranslation(t.Translation, t.Culture));
                }
            });

            return(translations);
        }
        public IEnumerable <DiscoveredResource> GetDiscoveredResources(Type target,
                                                                       object instance,
                                                                       MemberInfo mi,
                                                                       string translation,
                                                                       string resourceKey,
                                                                       string resourceKeyPrefix,
                                                                       bool typeKeyPrefixSpecified,
                                                                       bool isHidden,
                                                                       string typeOldName,
                                                                       string typeOldNamespace,
                                                                       Type declaringType,
                                                                       Type returnType,
                                                                       bool isSimpleType)
        {
            // check if there are [ResourceKey] attributes
            var keyAttributes = mi.GetCustomAttributes <ResourceKeyAttribute>().ToList();

            foreach (var resourceKeyAttribute in keyAttributes)
            {
                yield return new DiscoveredResource(mi,
                                                    ResourceKeyBuilder.BuildResourceKey(typeKeyPrefixSpecified ? resourceKeyPrefix : null,
                                                                                        resourceKeyAttribute.Key, string.Empty),
                                                    DiscoveredTranslation.FromSingle(string.IsNullOrEmpty(resourceKeyAttribute.Value)
                        ? translation
                        : resourceKeyAttribute.Value),
                                                    null,
                                                    declaringType,
                                                    returnType,
                                                    true)
                       {
                           FromResourceKeyAttribute = true
                       }
            }
            ;
        }
    }
Esempio n. 12
0
        private static void AddTranslationScript(LocalizationResource existingResource, StringBuilder buffer, DiscoveredTranslation resource)
        {
            var existingTranslation = existingResource.Translations.FirstOrDefault(t => t.Language == resource.Culture);

            if (existingTranslation == null)
            {
                buffer.Append($@"
        insert into localizationresourcetranslations (resourceid, [language], [value]) values ({existingResource.Id}, '{resource.Culture}', N'{resource.Translation.Replace("'", "''")}')
        ");
            }
            else if (!existingTranslation.Value.Equals(resource.Translation))
            {
                buffer.Append($@"
        update localizationresourcetranslations set [value] = N'{resource.Translation.Replace("'", "''")}' where resourceid={existingResource.Id} and [language]='{resource.Culture}'
        ");
            }
        }
Esempio n. 13
0
        public IEnumerable <DiscoveredResource> GetDiscoveredResources(
            Type target,
            object instance,
            MemberInfo mi,
            string translation,
            string resourceKey,
            string resourceKeyPrefix,
            bool typeKeyPrefixSpecified,
            bool isHidden,
            string typeOldName,
            string typeOldNamespace,
            Type declaringType,
            Type returnType,
            bool isSimpleType)
        {
            // check if there are [ResourceKey] attributes
            var keyAttributes = mi.GetCustomAttributes <ResourceKeyAttribute>().ToList();

            if (keyAttributes.Any())
            {
                yield break;
            }

            // check if there are [UseResource] attributes
            var useAttribute = mi.GetCustomAttribute <UseResourceAttribute>();

            if (useAttribute != null)
            {
                yield break;
            }

            var isResourceHidden = isHidden || mi.GetCustomAttribute <HiddenAttribute>() != null;
            var translations     = DiscoveredTranslation.FromSingle(translation);

            var additionalTranslationsAttributes = mi.GetCustomAttributes <TranslationForCultureAttribute>().ToArray();

            if (additionalTranslationsAttributes != null && additionalTranslationsAttributes.Any())
            {
                translations.AddRange(additionalTranslationsAttributes.Select(a =>
                                                                              new DiscoveredTranslation(a.Translation, a.Culture)));
            }

            var oldResourceKeys = OldResourceKeyBuilder.GenerateOldResourceKey(target, mi.Name, mi, resourceKeyPrefix,
                                                                               typeOldName, typeOldNamespace);

            yield return(new DiscoveredResource(mi,
                                                resourceKey,
                                                translations,
                                                mi.Name,
                                                declaringType,
                                                returnType,
                                                isSimpleType,
                                                isResourceHidden)
            {
                TypeName = target.Name,
                TypeNamespace = target.Namespace,
                TypeOldName = oldResourceKeys.Item2,
                TypeOldNamespace = typeOldNamespace,
                OldResourceKey = oldResourceKeys.Item1
            });
        }