Trying to handle (internally) KeyValueConfigurationCollection
exceptions when a value from it indexer doesn't exists, I have an error.
public class ConfigCore
{
public static Configuration config
{
get
{
ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
configFileMap.ExeConfigFilename = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "App.config");
return ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
}
}
public static SettingsManager Settings
{
get
{
//config is an instance of System.Configuration.Configuration and works well.
return (SettingsManager) config.AppSettings.Settings;
}
}
internal static KeyValueConfigurationCollection Setts
{
get
{
return config.AppSettings.Settings;
}
}
public static void CreateSettingEntry(string key, string value)
{
try
{
Setts.Add(key, value);
}
catch (Exception ex)
{
Console.WriteLine("Error ocurred trying to add value to Config. Message: {0}", ex.ToString());
}
}
}
public class SettingsManager : KeyValueConfigurationCollection
{
public KeyValueConfigurationElement this[string key]
{
get
{
if (ConfigCore.Setts[key] == null)
ConfigCore.CreateSettingEntry(key, "");
return ConfigCore.Setts[key];
}
}
}
I want to avoid that a user does the following thing using my API:
if(ConfigCore.Settings["key"] == null)
ConfigCore.CreateSettingEntry("key", "");
ConfigCore.Settings["key"].Value = "value";
And by this reason I have created an internal indexer to search for this cases and call automatically the method that creates the entry before setting it.
But for some reason, an exception occurs saying that KeyValueConfigurationCollection
cannot be casted into SettingsManager
, why if SettingsManager is a inherited class of KeyValueConfigurationCollection
, what I'm forgetting?
Thanks in advance!
I have been working on this issue just today.