private void Init(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord) { // Get the type of the factory Type type = TypeUtil.GetType(configRecord.Host, factoryRecord.FactoryTypeName, true); // If the type is a ConfigurationSection, that's the type. if (typeof(ConfigurationSection).IsAssignableFrom(type)) { _sectionCtor = TypeUtil.GetConstructor(type, typeof(ConfigurationSection), true); } else { // Note: in v1, IConfigurationSectionHandler is in effect a factory that has a Create method // that creates the real section object. // throws if type does not implement IConfigurationSectionHandler TypeUtil.VerifyAssignableType(typeof(IConfigurationSectionHandler), type, true); // Create an instance of the handler _sectionHandler = (IConfigurationSectionHandler)TypeUtil.CreateInstance(type); } }
/// <summary> /// We delegate this to the ClientConfigurationHost. The only thing we need to do here is to /// build a configPath from the ConfigurationUserLevel we get passed in. /// </summary> public override void InitForConfiguration(ref string locationSubPath, out string configPath, out string locationConfigPath, IInternalConfigRoot configRoot, params object[] hostInitConfigurationParams) { ConfigurationUserLevel userLevel = (ConfigurationUserLevel)hostInitConfigurationParams[0]; string desiredConfigPath = null; Host = TypeUtil.CreateInstance <IInternalConfigHost>(ClientConfigurationHostTypeName); switch (userLevel) { case ConfigurationUserLevel.None: desiredConfigPath = ClientHost.GetExeConfigPath(); break; case ConfigurationUserLevel.PerUserRoaming: desiredConfigPath = ClientHost.GetRoamingUserConfigPath(); break; case ConfigurationUserLevel.PerUserRoamingAndLocal: desiredConfigPath = ClientHost.GetLocalUserConfigPath(); break; default: throw new ArgumentException(SR.UnknownUserLevel); } Host.InitForConfiguration(ref locationSubPath, out configPath, out locationConfigPath, configRoot, null, null, desiredConfigPath); }
internal Configuration(string locationSubPath, Type typeConfigHost, params object[] hostInitConfigurationParams) { _typeConfigHost = typeConfigHost; _hostInitConfigurationParams = hostInitConfigurationParams; IInternalConfigHost configHost = (IInternalConfigHost)TypeUtil.CreateInstance(typeConfigHost); // Wrap the host with the UpdateConfigHost to support SaveAs. UpdateConfigHost updateConfigHost = new UpdateConfigHost(configHost); // Now wrap in ImplicitMachineConfigHost so we can stub in a simple machine.config if needed. IInternalConfigHost implicitMachineConfigHost = new ImplicitMachineConfigHost(updateConfigHost); InternalConfigRoot configRoot = new InternalConfigRoot(this, updateConfigHost); ((IInternalConfigRoot)configRoot).Init(implicitMachineConfigHost, isDesignTime: true); // Set the configuration paths for this Configuration. // // We do this in a separate step so that the WebConfigurationHost // can use this object's _configRoot to get the <sites> section, // which is used in it's MapPath implementation. string configPath, locationConfigPath; implicitMachineConfigHost.InitForConfiguration( ref locationSubPath, out configPath, out locationConfigPath, configRoot, hostInitConfigurationParams); if (!string.IsNullOrEmpty(locationSubPath) && !implicitMachineConfigHost.SupportsLocation) { throw ExceptionUtil.UnexpectedError("Configuration::ctor"); } if (string.IsNullOrEmpty(locationSubPath) != string.IsNullOrEmpty(locationConfigPath)) { throw ExceptionUtil.UnexpectedError("Configuration::ctor"); } // Get the configuration record for this config file. _configRecord = (MgmtConfigurationRecord)configRoot.GetConfigRecord(configPath); // Create another MgmtConfigurationRecord for the location that is a child of the above record. // Note that this does not match the resolution hiearchy that is used at runtime. if (!string.IsNullOrEmpty(locationSubPath)) { _configRecord = MgmtConfigurationRecord.Create( configRoot, _configRecord, locationConfigPath, locationSubPath); } // Throw if the config record we created contains global errors. _configRecord.ThrowIfInitErrors(); }
private ProtectedConfigurationProvider CreateAndInitializeProviderWithAssert(Type t, ProviderSettings pn) { ProtectedConfigurationProvider provider = (ProtectedConfigurationProvider)TypeUtil.CreateInstance(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); }
public ConfigurationProperty(string name, Type type) { object defaultValue = null; ConstructorInit(name, type, ConfigurationPropertyOptions.None, null, null); if (type == typeof(string)) { defaultValue = string.Empty; } else if (type.IsValueType) { defaultValue = TypeUtil.CreateInstance(type); } SetDefaultValue(defaultValue); }
private void InitDefaultValueFromTypeInfo(ConfigurationPropertyAttribute attribProperty, DefaultValueAttribute attribStdDefault) { object defaultValue = attribProperty.DefaultValue; // If there is no default value there - try the other attribute ( the clr standard one ) if (((defaultValue == null) || (defaultValue == ConfigurationElement.s_nullPropertyValue)) && (attribStdDefault != null)) { defaultValue = attribStdDefault.Value; } // If there was a default value in the prop attribute - check if we need to convert it from string if (defaultValue is string && (Type != typeof(string))) { // Use the converter to parse this property default value try { defaultValue = Converter.ConvertFromInvariantString((string)defaultValue); } catch (Exception ex) { throw new ConfigurationErrorsException(string.Format(SR.Default_value_conversion_error_from_string, Name, ex.Message)); } } if ((defaultValue == null) || (defaultValue == ConfigurationElement.s_nullPropertyValue)) { if (Type == typeof(string)) { defaultValue = string.Empty; } else { if (Type.IsValueType) { defaultValue = TypeUtil.CreateInstance(Type); } } } SetDefaultValue(defaultValue); }
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); }
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"); 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( SR.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; } }
/// <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); }
/// <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); }
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)) { value = (new BinaryFormatter()).Deserialize(ms); } } 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); }
private static IConfigurationManagerHelper CreateConfigurationManagerHelper() { return(TypeUtil.CreateInstance <IConfigurationManagerHelper>(ConfigurationManagerHelperTypeString)); }
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; } }