/// <summary> /// Creates a SettingsProperty object using the metadata on the given property /// and returns it. /// </summary> private SettingsProperty CreateSetting(PropertyInfo propertyInfo) { // Initialization method - // be careful not to access properties here to prevent stack overflow. object[] attributes = propertyInfo.GetCustomAttributes(false); SettingsProperty settingsProperty = new SettingsProperty(Initializer); bool explicitSerialize = _explicitSerializeOnClass; settingsProperty.Name = propertyInfo.Name; settingsProperty.PropertyType = propertyInfo.PropertyType; for (int i = 0; i < attributes.Length; i++) { Attribute attribute = attributes[i] as Attribute; if (attribute == null) { continue; } if (attribute is DefaultSettingValueAttribute) { settingsProperty.DefaultValue = ((DefaultSettingValueAttribute)attribute).Value; } else if (attribute is ReadOnlyAttribute) { settingsProperty.IsReadOnly = true; } else if (attribute is SettingsProviderAttribute) { string providerTypeName = ((SettingsProviderAttribute)attribute).ProviderTypeName; Type providerType = Type.GetType(providerTypeName); if (providerType == null) { throw new ConfigurationErrorsException(SR.Format(SR.ProviderTypeLoadFailed, providerTypeName)); } SettingsProvider settingsProvider = TypeUtil.CreateInstance(providerType) as SettingsProvider; if (settingsProvider == null) { throw new ConfigurationErrorsException(SR.Format(SR.ProviderInstantiationFailed, providerTypeName)); } settingsProvider.Initialize(null, null); settingsProvider.ApplicationName = ConfigurationManagerInternalFactory.Instance.ExeProductName; // See if we already have a provider of the same name in our collection. If so, // re-use the existing instance, since we cannot have multiple providers of the same name. SettingsProvider existing = _providers[settingsProvider.Name]; if (existing != null) { settingsProvider = existing; } settingsProperty.Provider = settingsProvider; } else if (attribute is SettingsSerializeAsAttribute) { settingsProperty.SerializeAs = ((SettingsSerializeAsAttribute)attribute).SerializeAs; explicitSerialize = true; } else { // This isn't an attribute we care about, so simply pass it on // to the SettingsProvider. // // NOTE: The key is the type. So if an attribute was found at class // level and also property level, the latter overrides the former // for a given setting. This is exactly the behavior we want. settingsProperty.Attributes.Add(attribute.GetType(), attribute); } } if (!explicitSerialize) { // Serialization method was not explicitly attributed. TypeConverter tc = TypeDescriptor.GetConverter(propertyInfo.PropertyType); if (tc.CanConvertTo(typeof(string)) && tc.CanConvertFrom(typeof(string))) { // We can use string settingsProperty.SerializeAs = SettingsSerializeAs.String; } else { // Fallback is Xml settingsProperty.SerializeAs = SettingsSerializeAs.Xml; } } return(settingsProperty); }
internal ConfigurationProperty(PropertyInfo info) { Debug.Assert(info != null, "info != null"); ConfigurationPropertyAttribute propertyAttribute = null; DescriptionAttribute descriptionAttribute = null; // For compatibility we read the component model default value attribute. It is only // used if ConfigurationPropertyAttribute doesn't provide the default value. DefaultValueAttribute defaultValueAttribute = null; TypeConverter typeConverter = null; ConfigurationValidatorBase validator = null; // Look for relevant attributes foreach (Attribute attribute in Attribute.GetCustomAttributes(info)) { if (attribute is TypeConverterAttribute) { typeConverter = TypeUtil.CreateInstance <TypeConverter>(((TypeConverterAttribute)attribute).ConverterTypeName); } else if (attribute is ConfigurationPropertyAttribute) { propertyAttribute = (ConfigurationPropertyAttribute)attribute; } else if (attribute is ConfigurationValidatorAttribute) { if (validator != null) { // We only allow one validator to be specified on a property. // // Consider: introduce a new validator type ( CompositeValidator ) that is a // list of validators and executes them all throw new ConfigurationErrorsException( string.Format(SR.Validator_multiple_validator_attributes, info.Name)); } ConfigurationValidatorAttribute validatorAttribute = (ConfigurationValidatorAttribute)attribute; validatorAttribute.SetDeclaringType(info.DeclaringType); validator = validatorAttribute.ValidatorInstance; } else if (attribute is DescriptionAttribute) { descriptionAttribute = (DescriptionAttribute)attribute; } else if (attribute is DefaultValueAttribute) { defaultValueAttribute = (DefaultValueAttribute)attribute; } } Type propertyType = info.PropertyType; // If the property is a Collection we need to look for the ConfigurationCollectionAttribute for // additional customization. if (typeof(ConfigurationElementCollection).IsAssignableFrom(propertyType)) { // Look for the ConfigurationCollection attribute on the property itself, fall back // on the property type. ConfigurationCollectionAttribute collectionAttribute = Attribute.GetCustomAttribute(info, typeof(ConfigurationCollectionAttribute)) as ConfigurationCollectionAttribute ?? Attribute.GetCustomAttribute(propertyType, typeof(ConfigurationCollectionAttribute)) as ConfigurationCollectionAttribute; if (collectionAttribute != null) { if (collectionAttribute.AddItemName.IndexOf(',') == -1) { AddElementName = collectionAttribute.AddItemName; // string.Contains(char) is .NetCore2.1+ specific } RemoveElementName = collectionAttribute.RemoveItemName; ClearElementName = collectionAttribute.ClearItemsName; } } // This constructor shouldn't be invoked if the reflection info is not for an actual config property Debug.Assert(propertyAttribute != null, "attribProperty != null"); ConstructorInit(propertyAttribute.Name, info.PropertyType, propertyAttribute.Options, validator, typeConverter); // Figure out the default value InitDefaultValueFromTypeInfo(propertyAttribute, defaultValueAttribute); // Get the description if (!string.IsNullOrEmpty(descriptionAttribute?.Description)) { Description = descriptionAttribute.Description; } }
private ProtectedConfigurationProvider CreateAndInitializeProviderWithAssert(Type t, ProviderSettings pn) { ProtectedConfigurationProvider provider = (ProtectedConfigurationProvider)TypeUtil.CreateInstanceWithReflectionPermission(t); NameValueCollection pars = pn.Parameters; NameValueCollection cloneParams = new NameValueCollection(pars.Count); foreach (string key in pars) { cloneParams[key] = pars[key]; } provider.Initialize(pn.Name, cloneParams); return(provider); }
private static IConfigurationManagerHelper CreateConfigurationManagerHelper() { return(TypeUtil.CreateInstance <IConfigurationManagerHelper>(ConfigurationManagerHelperTypeString)); }
private object Deserialize() { object value = null; // Attempt 1: Try creating from SerializedValue if (SerializedValue != null) { bool throwBinaryFormatterDeprecationException = false; try { if (SerializedValue is string) { value = GetObjectFromString(Property.PropertyType, Property.SerializeAs, (string)SerializedValue); } else { if (SettingsProperty.EnableUnsafeBinaryFormatterInPropertyValueSerialization) { using (MemoryStream ms = new MemoryStream((byte[])SerializedValue)) { #pragma warning disable SYSLIB0011 // BinaryFormatter serialization is obsolete and should not be used. value = (new BinaryFormatter()).Deserialize(ms); #pragma warning restore SYSLIB0011 } } else { throwBinaryFormatterDeprecationException = true; } } } catch (Exception exception) { try { if (IsHostedInAspnet()) { object[] args = new object[] { Property, this, exception }; const string webBaseEventTypeName = "System.Web.Management.WebBaseEvent, System.Web"; Type type = Type.GetType(webBaseEventTypeName, true); type.InvokeMember("RaisePropertyDeserializationWebErrorEvent", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.InvokeMethod, null, null, args, CultureInfo.InvariantCulture); } } catch { } } if (throwBinaryFormatterDeprecationException) { throw new NotSupportedException(Obsoletions.BinaryFormatterMessage); } if (value != null && !Property.PropertyType.IsAssignableFrom(value.GetType())) // is it the correct type { value = null; } } // Attempt 2: Try creating from default value if (value == null) { UsingDefaultValue = true; if (Property.DefaultValue == null || Property.DefaultValue.ToString() == "[null]") { if (Property.PropertyType.IsValueType) { return(TypeUtil.CreateInstance(Property.PropertyType)); } else { return(null); } } if (!(Property.DefaultValue is string)) { value = Property.DefaultValue; } else { try { value = GetObjectFromString(Property.PropertyType, Property.SerializeAs, (string)Property.DefaultValue); } catch (Exception e) { throw new ArgumentException(SR.Format(SR.Could_not_create_from_default_value, Property.Name, e.Message)); } } if (value != null && !Property.PropertyType.IsAssignableFrom(value.GetType())) // is it the correct type { throw new ArgumentException(SR.Format(SR.Could_not_create_from_default_value_2, Property.Name)); } } // Attempt 3: Create via the parameterless constructor if (value == null) { if (Property.PropertyType == typeof(string)) { value = string.Empty; } else { try { value = TypeUtil.CreateInstance(Property.PropertyType); } catch { } } } return(value); }
internal ConfigurationProperty(PropertyInfo info) { Debug.Assert(info != null, "info != null"); // Bellow are the attributes we handle ConfigurationPropertyAttribute attribProperty = null; // Compatability attributes // If the approprite data is provided in the ConfigPropAttribute then the one bellow will be ignored DescriptionAttribute attribStdDescription = null; DefaultValueAttribute attribStdDefault = null; TypeConverter typeConverter = null; ConfigurationValidatorBase validator = null; // Find the interesting attributes in the collection foreach (Attribute attribute in Attribute.GetCustomAttributes(info)) { if (attribute is TypeConverterAttribute) { TypeConverterAttribute attribConverter = (TypeConverterAttribute)attribute; typeConverter = TypeUtil.CreateInstance <TypeConverter>(attribConverter.ConverterTypeName); } else { if (attribute is ConfigurationPropertyAttribute) { attribProperty = (ConfigurationPropertyAttribute)attribute; } else { if (attribute is ConfigurationValidatorAttribute) { // There could be more then one validator attribute specified on a property // Currently we consider this an error since it's too late to fix it for whidbey // but the right thing to do is to introduce new validator type ( CompositeValidator ) that is a list of validators and executes // them all if (validator != null) { throw new ConfigurationErrorsException( string.Format(SR.Validator_multiple_validator_attributes, info.Name)); } ConfigurationValidatorAttribute attribValidator = (ConfigurationValidatorAttribute)attribute; attribValidator.SetDeclaringType(info.DeclaringType); validator = attribValidator.ValidatorInstance; } else { if (attribute is DescriptionAttribute) { attribStdDescription = (DescriptionAttribute)attribute; } else { if (attribute is DefaultValueAttribute) { attribStdDefault = (DefaultValueAttribute)attribute; } } } } } } Type propertyType = info.PropertyType; // Collections need some customization when the collection attribute is present if (typeof(ConfigurationElementCollection).IsAssignableFrom(propertyType)) { ConfigurationCollectionAttribute attribCollection = Attribute.GetCustomAttribute(info, typeof(ConfigurationCollectionAttribute)) as ConfigurationCollectionAttribute ?? Attribute.GetCustomAttribute(propertyType, typeof(ConfigurationCollectionAttribute)) as ConfigurationCollectionAttribute; // If none on the property - see if there is an attribute on the collection type itself if (attribCollection != null) { if (attribCollection.AddItemName.IndexOf(',') == -1) { AddElementName = attribCollection.AddItemName; } RemoveElementName = attribCollection.RemoveItemName; ClearElementName = attribCollection.ClearItemsName; } } // This constructor shouldnt be invoked if the reflection info is not for an actual config property Debug.Assert(attribProperty != null, "attribProperty != null"); ConstructorInit(attribProperty.Name, info.PropertyType, attribProperty.Options, validator, typeConverter); // Figure out the default value InitDefaultValueFromTypeInfo(attribProperty, attribStdDefault); // Get the description if (!string.IsNullOrEmpty(attribStdDescription?.Description)) { Description = attribStdDescription.Description; } }
private object Deserialize() { object val = null; // Step 1: Try creating from Serailized value if (SerializedValue != null) { try { if (SerializedValue is string) { val = GetObjectFromString(Property.PropertyType, Property.SerializeAs, (string)SerializedValue); } else { MemoryStream ms = new System.IO.MemoryStream((byte[])SerializedValue); try { val = (new BinaryFormatter()).Deserialize(ms); } finally { ms.Close(); } } } catch (Exception exception) { try { if (IsHostedInAspnet()) { object[] args = new object[] { Property, this, exception }; const string webBaseEventTypeName = "System.Web.Management.WebBaseEvent, System.Web"; Type type = Type.GetType(webBaseEventTypeName, true); type.InvokeMember("RaisePropertyDeserializationWebErrorEvent", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.InvokeMethod, null, null, args, CultureInfo.InvariantCulture); } } catch { } } if (val != null && !Property.PropertyType.IsAssignableFrom(val.GetType())) // is it the correct type { val = null; } } // Step 2: Try creating from default value if (val == null) { UsingDefaultValue = true; if (Property.DefaultValue == null || Property.DefaultValue.ToString() == "[null]") { if (Property.PropertyType.IsValueType) { return(TypeUtil.CreateInstance(Property.PropertyType)); } else { return(null); } } if (!(Property.DefaultValue is string)) { val = Property.DefaultValue; } else { try { val = GetObjectFromString(Property.PropertyType, Property.SerializeAs, (string)Property.DefaultValue); } catch (Exception e) { throw new ArgumentException(string.Format(SR.Could_not_create_from_default_value, Property.Name, e.Message)); } } if (val != null && !Property.PropertyType.IsAssignableFrom(val.GetType())) // is it the correct type { throw new ArgumentException(string.Format(SR.Could_not_create_from_default_value_2, Property.Name)); } } // Step 3: Create a new one by calling the parameterless constructor if (val == null) { if (Property.PropertyType == typeof(string)) { val = ""; } else { try { val = TypeUtil.CreateInstance(Property.PropertyType); } catch { } } } return(val); }
internal ConfigurationProperty(PropertyInfo info) { Debug.Assert(info != null, "info != null"); // Bellow are the attributes we handle TypeConverterAttribute attribConverter = null; ConfigurationPropertyAttribute attribProperty = null; ConfigurationValidatorAttribute attribValidator = null; // Compatability attributes // If the approprite data is provided in the ConfigPropAttribute then the one bellow will be ignored DescriptionAttribute attribStdDescription = null; DefaultValueAttribute attribStdDefault = null; TypeConverter typeConverter = null; ConfigurationValidatorBase validator = null; // Find the interesting attributes in the collection foreach (Attribute attribute in Attribute.GetCustomAttributes(info)) { if (attribute is TypeConverterAttribute) { attribConverter = (TypeConverterAttribute)attribute; typeConverter = (TypeConverter)TypeUtil.CreateInstanceWithReflectionPermission(attribConverter.ConverterTypeName); } else if (attribute is ConfigurationPropertyAttribute) { attribProperty = (ConfigurationPropertyAttribute)attribute; } else if (attribute is ConfigurationValidatorAttribute) { if (validator != null) { throw new ConfigurationErrorsException(SR.GetString(SR.Validator_multiple_validator_attributes, info.Name)); } attribValidator = (ConfigurationValidatorAttribute)attribute; validator = attribValidator.ValidatorInstance; } else if (attribute is DescriptionAttribute) { attribStdDescription = (DescriptionAttribute)attribute; } else if (attribute is DefaultValueAttribute) { attribStdDefault = (DefaultValueAttribute)attribute; } } Type propertyType = info.PropertyType; // Collections need some customization when the collection attribute is present if (typeof(ConfigurationElementCollection).IsAssignableFrom(propertyType)) { ConfigurationCollectionAttribute attribCollection = Attribute.GetCustomAttribute(info, typeof(ConfigurationCollectionAttribute)) as ConfigurationCollectionAttribute; // If none on the property - see if there is an attribute on the collection type itself if (attribCollection == null) { attribCollection = Attribute.GetCustomAttribute(propertyType, typeof(ConfigurationCollectionAttribute)) as ConfigurationCollectionAttribute; } if (attribCollection != null) { if (attribCollection.AddItemName.IndexOf(',') == -1) { _addElementName = attribCollection.AddItemName; } _removeElementName = attribCollection.RemoveItemName; _clearElementName = attribCollection.ClearItemsName; } } // This constructor shouldnt be invoked if the reflection info is not for an actual config property Debug.Assert(attribProperty != null, "attribProperty != null"); ConstructorInit(attribProperty.Name, info.PropertyType, attribProperty.Options, validator, typeConverter); // Figure out the default value InitDefaultValueFromTypeInfo(attribProperty, attribStdDefault); // Get the description if ((attribStdDescription != null) && !string.IsNullOrEmpty(attribStdDescription.Description)) { _description = attribStdDescription.Description; } }
/// <summary> /// Creates a SettingsProperty object using the metadata on the given property /// and returns it. /// /// Implementation note: Initialization method - be careful not to access properties here /// to prevent stack overflow. /// </summary> private SettingsProperty CreateSetting(PropertyInfo propInfo) { object[] attributes = propInfo.GetCustomAttributes(false); SettingsProperty sp = new SettingsProperty(Initializer); bool explicitSerialize = _explicitSerializeOnClass; sp.Name = propInfo.Name; sp.PropertyType = propInfo.PropertyType; for (int i = 0; i < attributes.Length; i++) { Attribute attr = attributes[i] as Attribute; if (attr != null) { if (attr is DefaultSettingValueAttribute) { sp.DefaultValue = ((DefaultSettingValueAttribute)attr).Value; } else if (attr is ReadOnlyAttribute) { sp.IsReadOnly = true; } else if (attr is SettingsProviderAttribute) { string providerTypeName = ((SettingsProviderAttribute)attr).ProviderTypeName; Type providerType = Type.GetType(providerTypeName); if (providerType != null) { SettingsProvider spdr = TypeUtil.CreateInstance(providerType) as SettingsProvider; if (spdr != null) { spdr.Initialize(null, null); spdr.ApplicationName = ConfigurationManagerInternalFactory.Instance.ExeProductName; // See if we already have a provider of the same name in our collection. If so, // re-use the existing instance, since we cannot have multiple providers of the same name. SettingsProvider existing = _providers[spdr.Name]; if (existing != null) { spdr = existing; } sp.Provider = spdr; } else { throw new ConfigurationErrorsException(string.Format(SR.ProviderInstantiationFailed, providerTypeName)); } } else { throw new ConfigurationErrorsException(string.Format(SR.ProviderTypeLoadFailed, providerTypeName)); } } else if (attr is SettingsSerializeAsAttribute) { sp.SerializeAs = ((SettingsSerializeAsAttribute)attr).SerializeAs; explicitSerialize = true; } else { // This isn't an attribute we care about, so simply pass it on // to the SettingsProvider. // NOTE: The key is the type. So if an attribute was found at class // level and also property level, the latter overrides the former // for a given setting. This is exactly the behavior we want. sp.Attributes.Add(attr.GetType(), attr); } } } if (!explicitSerialize) { sp.SerializeAs = GetSerializeAs(propInfo.PropertyType); } return(sp); }