The .config files centralize and standardize how per application or per library configuration data are stored. The format can be a little dense to get through, and I always tend to leak this information from my brain. I only need to know when I start a new project.
I have had to relearn configuration data yet again, so I figured I should commit it to the electrons so I do not forget again.
Use the tests with external file dependencies post as a starting point. The tests have to be written this way because the System.Configuration API does not support accepting input from a stream.
Step 1: Create a minimal configuration. In this case, I have two configuration values. The maximum number of tasks, and the period.
namespace My.Library { public class MyConfiguration : ConfigurationSection { [ConfigurationProperty("maxTasks", IsRequired = true)] public int MaxTasks { get { return (int)this["maxTasks"]; } set { this["maxTasks"] = value; } } [ConfigurationProperty("period", IsRequired = false, DefaultValue = "00:00:15")] public TimeSpan Period { get { return (TimeSpan)this["period"]; } set { this["period"] = value; } } } }
Step 2: Create an example configuration file to use for testing.
<configuration> <configSections> <section name="myConfig" type="My.Library.MyConfiguration, Library" /> </configSections> <myConfig maxTasks="1" period="00:00:01" /> </configuration>
NOTE: When defining the configuration section (<section />) at a minimum the type attribute must include the full name of the type (My.Library.MyConfiguration). The value after the comma is the assembly name (minus .exe/.dll) containing the type. Additional information can be specified such as the version, and public key token, i.e. strong name of the assembly.
Step 3: Write a test to validate the configuration file.
[Fact] public void MyConfiguration_OverrideAllValues() { string fileName = Assembly.GetExecutingAssembly().LoadFileAssemblyResource( "My.Tests.examples.example1.config"); try { ConfigurationFileMap fileMap = new ConfigurationFileMap(fileName); Configuration configuration = ConfigurationManager.OpenMappedMachineConfiguration( fileMap); MyConfiguration mine = (MyConfiguration)configuration.GetSection( "myConfig"); Assert.Equal(1, mine.MaxTasks); Assert.Equal(TimeSpan.FromSeconds(1), mine.Period); } finally { File.Delete(fileName); } }
This test validates the configuration data loaded matches the data in the seed file, example1.config. There are two other tests that should be written.
- Validate that period correctly defaults to 15 seconds.
- Validate that MaxTasks is a required parameter.