All applications require configuration files; we use them to customize behavior and to set parameters unknown at compile time, or those that may change over time (such as the database connection string, the address of the mail server, etc.).
.NET supplies the class ConfigurationManager, or WebConfigurationManager for Web applications, to recover the configuration parameters recorded in the CONFIG file. This class is not included in the .NET Micro Framework.
However, we can create a smaller version of the ConfigurationManager. The .NET Micro Framework can read the appSettings section of the standard .NET configuration file, since they are simple XML files.
The most important method of the class is Load, which takes a Stream input object containing the configuration file, and reads it with an XmlReader, in search of the appSettings tag. When it finds it, it processes all elements with name ADD, and for each, extracts the values of the key attributes, saving them in theHashtable appSettings. We then call the GetAppSettings function, which returns the value corresponding to the specified key; it is also an overload that returns a default value if the key does not exist.
Let’s take an example. We create a new .NET Gadgeteer application and connect the SD Card module to an F socket of the FEZ Spider. We need an SD card that contains, in the root directory of the store, the following configuration file in .NET standard format, with the name Application.config:
Finally, in the Program.cs file, we read the file from the memory card and pass it to theConfigurationManager:
The event sdCard_SDCardMounted is generated when the memory card is inserted into the module. We read the Application.config file with the OpenRead method and pass it to the ConfigurationManager.Loadmethod. At this point, we recover some example values through calls to GetAppSetting and we print them in the Debug output window of Visual Studio. Notice that in the third case we require the value of key username, than is not present in the configuration file, and therefore comes back with the default value, that is anonymous.
The ConfigurationManager class is easily extensible. To support new sections of the configuration file, add branches to the switch of the Load method.
This application is available for download.
Reference:
No comments:
Post a Comment