Exemple #1
0
        private void InitDefaultValueFromTypeInfo(
            ConfigurationPropertyAttribute configurationProperty,
            DefaultValueAttribute defaultValueAttribute)
        {
            object defaultValue = configurationProperty.DefaultValue;

            // If the ConfigurationPropertyAttribute has no default try the DefaultValueAttribute
            if (ConfigurationElement.IsNullOrNullProperty(defaultValue))
            {
                defaultValue = defaultValueAttribute?.Value;
            }

            // Convert the default value from string if necessary
            if (defaultValue is string && (Type != typeof(string)))
            {
                try
                {
                    defaultValue = Converter.ConvertFromInvariantString((string)defaultValue);
                }
                catch (Exception ex)
                {
                    throw new ConfigurationErrorsException(SR.Format(SR.Default_value_conversion_error_from_string,
                                                                     Name, ex.Message));
                }
            }

            // If we still have no default, use string Empty for string or the default for value types
            if (ConfigurationElement.IsNullOrNullProperty(defaultValue))
            {
                if (Type == typeof(string))
                {
                    defaultValue = string.Empty;
                }
                else if (Type.IsValueType)
                {
                    defaultValue = TypeUtil.CreateInstance(Type);
                }
            }

            SetDefaultValue(defaultValue);
        }
Exemple #2
0
        private void SetDefaultValue(object value)
        {
            // Validate the default value if any. This should make errors from invalid defaults easier to catch
            if (ConfigurationElement.IsNullOrNullProperty(value))
            {
                return;
            }

            if (!Type.IsInstanceOfType(value))
            {
                if (!Converter.CanConvertFrom(value.GetType()))
                {
                    throw new ConfigurationErrorsException(SR.Format(SR.Default_value_wrong_type, Name));
                }

                value = Converter.ConvertFrom(value);
            }

            Validate(value);
            DefaultValue = value;
        }