Exemplo n.º 1
0
        /// <summary>
        ///     Sets the values for properties of
        ///     <see cref="P:Microsoft.AspNetCore.Mvc.ModelBinding.Metadata.DisplayMetadataProviderContext.DisplayMetadata" />.
        /// </summary>
        /// <param name="context">
        ///     The
        ///     <see cref="T:Microsoft.AspNetCore.Mvc.ModelBinding.Metadata.DisplayMetadataProviderContext" />.
        /// </param>
        public void CreateDisplayMetadata(DisplayMetadataProviderContext context)
        {
            var theAttributes = context.Attributes;
            var modelMetadata = context.DisplayMetadata;
            var propertyName  = context.Key.Name;
            var containerType = context.Key.ContainerType;

            if (containerType == null)
            {
                return;
            }

            if (containerType.GetCustomAttribute <LocalizedModelAttribute>() == null)
            {
                return;
            }

            var currentMetaData = modelMetadata.DisplayName?.Invoke();

            modelMetadata.DisplayName = () => !ModelMetadataLocalizationHelper.UseLegacyMode(currentMetaData)
                ? ModelMetadataLocalizationHelper.GetTranslation(containerType, propertyName)
                : ModelMetadataLocalizationHelper.GetTranslation(currentMetaData);

            var displayAttribute = theAttributes.OfType <DisplayAttribute>().FirstOrDefault();

            if (displayAttribute?.Description != null)
            {
                // ReSharper disable once ImplicitlyCapturedClosure
                modelMetadata.Description = () =>
                                            ModelMetadataLocalizationHelper.GetTranslation(containerType, $"{propertyName}-Description");
            }
        }
Exemplo n.º 2
0
        public void UseLegacyMode_DisplayNameHasNotLegacyFormat_ReturnsFalse()
        {
            var displayName = "propertyName";

            var result = ModelMetadataLocalizationHelper.UseLegacyMode(displayName);

            Assert.False(result);
        }
Exemplo n.º 3
0
        public void UseLegacyMode_DisplayNameIsLegacyModeWithLegacyModeEnabled_ReturnsTrue()
        {
            var displayName = "/legacy/path";

            ConfigurationContext.Current.ModelMetadataProviders.EnableLegacyMode = () => true;

            var result = ModelMetadataLocalizationHelper.UseLegacyMode(displayName);

            Assert.True(result);
        }
Exemplo n.º 4
0
        public void UseLegacyMode_EnableLegacyModeIsFalse_ReturnsFalse()
        {
            var displayName = "propertyName";

            ConfigurationContext.Current.ModelMetadataProviders.EnableLegacyMode = () => false;

            var result = ModelMetadataLocalizationHelper.UseLegacyMode(displayName);

            Assert.False(result);
        }
Exemplo n.º 5
0
        public void UseLegacyMode_DisplayNameIsNull_ReturnsFalse()
        {
            var result = ModelMetadataLocalizationHelper.UseLegacyMode(null);

            Assert.False(result);
        }
        /// <summary>   Validates the model value. </summary>
        /// <exception cref="ArgumentNullException">
        ///     Thrown when one or more required arguments are
        ///     null.
        /// </exception>
        /// <exception cref="ArgumentException">
        ///     Thrown when one or more arguments have
        ///     unsupported or illegal values.
        /// </exception>
        /// <param name="validationContext">
        ///     The
        ///     <see cref="T:Microsoft.AspNetCore.Mvc.ModelBinding.Validation.ModelValidationContext" />.
        /// </param>
        /// <returns>
        ///     A list of
        ///     <see cref="T:Microsoft.AspNetCore.Mvc.ModelBinding.Validation.ModelValidationResult" />
        ///     indicating the results of validating the model value.
        /// </returns>
        public IEnumerable <ModelValidationResult> Validate(ModelValidationContext validationContext)
        {
            if (validationContext == null)
            {
                throw new ArgumentNullException(nameof(validationContext));
            }

            if (validationContext.ModelMetadata == null)
            {
                throw new ArgumentException($"{nameof(validationContext.ModelMetadata)} is null",
                                            nameof(validationContext));
            }

            if (validationContext.MetadataProvider == null)
            {
                throw new ArgumentException($"{nameof(validationContext.MetadataProvider)} in null",
                                            nameof(validationContext));
            }

            var metadata   = validationContext.ModelMetadata;
            var memberName = metadata.PropertyName;
            var container  = validationContext.Container;

            var context = new ValidationContext(
                container ?? validationContext.Model ?? EmptyValidationContextInstance,
                validationContext.ActionContext?.HttpContext?.RequestServices,
                null)
            {
                DisplayName = metadata.GetDisplayName(),
                MemberName  = memberName
            };

            var result = _attribute.GetValidationResult(validationContext.Model, context);

            if (result == ValidationResult.Success)
            {
                return(Enumerable.Empty <ModelValidationResult>());
            }
            var resourceKey =
                ResourceKeyBuilder.BuildResourceKey(metadata.ContainerType, metadata.PropertyName, _attribute);
            var translation  = ModelMetadataLocalizationHelper.GetTranslation(resourceKey);
            var errorMessage = !string.IsNullOrEmpty(translation) ? translation : result?.ErrorMessage;

            var validationResults = new List <ModelValidationResult>();

            if (result?.MemberNames != null)
            {
                validationResults.AddRange(result.MemberNames.Select(resultMemberName =>
                                                                     string.Equals(resultMemberName, memberName, StringComparison.Ordinal)
                            ? null
                            : resultMemberName)
                                           .Select(newMemberName => new ModelValidationResult(newMemberName, errorMessage)));
            }

            if (validationResults.Count == 0)
            {
                validationResults.Add(new ModelValidationResult(null, errorMessage));
            }

            return(validationResults);
        }
        internal static IEnumerable <DiscoveredResource> GetAllProperties(Type type, string keyPrefix = null, bool contextAwareScanning = true)
        {
            var resourceKeyPrefix      = type.FullName;
            var typeKeyPrefixSpecified = false;
            var properties             = new List <DiscoveredResource>();

            if (contextAwareScanning)
            {
                // this is model scanning - try to fetch resource key prefix attribute if set there
                var modelAttribute = type.GetCustomAttribute <LocalizedResourceAttribute>();
                if (!string.IsNullOrEmpty(modelAttribute?.KeyPrefix))
                {
                    resourceKeyPrefix      = modelAttribute.KeyPrefix;
                    typeKeyPrefixSpecified = true;
                }
                else
                {
                    resourceKeyPrefix = string.IsNullOrEmpty(keyPrefix) ? type.FullName : keyPrefix;
                }
            }
            else
            {
                // this is model scanning - try to fetch resource key prefix attribute if set there
                var modelAttribute = type.GetCustomAttribute <LocalizedModelAttribute>();
                if (!string.IsNullOrEmpty(modelAttribute?.KeyPrefix))
                {
                    resourceKeyPrefix      = modelAttribute.KeyPrefix;
                    typeKeyPrefixSpecified = true;
                }

                var resourceAttributesOnModelClass = type.GetCustomAttributes <ResourceKeyAttribute>().ToList();
                if (resourceAttributesOnModelClass.Any())
                {
                    foreach (var resourceKeyAttribute in resourceAttributesOnModelClass)
                    {
                        properties.Add(new DiscoveredResource(null,
                                                              ResourceKeyBuilder.BuildResourceKey(resourceKeyPrefix, resourceKeyAttribute.Key, separator: string.Empty),
                                                              resourceKeyAttribute.Value,
                                                              type,
                                                              typeof(string),
                                                              true));
                    }
                }
            }

            if (type.BaseType == typeof(Enum))
            {
                properties.AddRange(type.GetMembers(BindingFlags.Public | BindingFlags.Static)
                                    .Select(mi => new DiscoveredResource(mi,
                                                                         ResourceKeyBuilder.BuildResourceKey(resourceKeyPrefix, mi),
                                                                         mi.Name,
                                                                         type,
                                                                         Enum.GetUnderlyingType(type),
                                                                         Enum.GetUnderlyingType(type).IsSimpleType())).ToList());
            }
            else
            {
                properties.AddRange(type.GetProperties(BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Static)
                                    .Where(pi => pi.GetCustomAttribute <IgnoreAttribute>() == null)
                                    .SelectMany(pi => DiscoverResourcesFromProperty(pi, resourceKeyPrefix, typeKeyPrefixSpecified)).ToList());
            }

            // first we can filter out all simple and/or complex included properties from the type as starting list of discovered resources
            var results = new List <DiscoveredResource>(properties.Where(t => t.IsSimpleType || t.Info == null || t.Info.GetCustomAttribute <IncludeAttribute>() != null));

            foreach (var property in properties)
            {
                var pi = property.Info;
                var deeperModelType = property.ReturnType;

                if (!property.IsSimpleType)
                {
                    // if this is not a simple type - we need to scan deeper only if deeper model has attribute annotation
                    if (contextAwareScanning || deeperModelType.GetCustomAttribute <LocalizedModelAttribute>() != null)
                    {
                        results.AddRange(GetAllProperties(property.DeclaringType, property.Key, contextAwareScanning));
                    }
                }

                if (pi == null)
                {
                    continue;
                }

                var validationAttributes = pi.GetCustomAttributes <ValidationAttribute>();
                foreach (var validationAttribute in validationAttributes)
                {
                    var resourceKey   = ModelMetadataLocalizationHelper.BuildResourceKey(property.Key, validationAttribute);
                    var resourceValue = resourceKey.Split('.').Last();
                    results.Add(new DiscoveredResource(pi,
                                                       resourceKey,
                                                       string.IsNullOrEmpty(validationAttribute.ErrorMessage) ? resourceValue : validationAttribute.ErrorMessage,
                                                       property.DeclaringType,
                                                       property.ReturnType,
                                                       property.ReturnType.IsSimpleType()));
                }
            }

            return(results);
        }