Developing with the Configuration Application Block


A primary design goal for the Configuration Application Block is to make it simple to save and retrieve configuration data. This design goal is achieved via the ConfigurationManager object that was just discussed. Many applications will only need to leverage two static methods exposed by this object: GetConfiguration and WriteConfiguration.

GetConfiguration is used for reading configuration data in a configuration section, and WriteConfiguration is used for saving data for a configuration section back to the configuration data store. Additional methods exist for handling change events to the underlying configuration data store and clearing the configuration cache to enforce that configuration data is reread from this store.

Occasionally, an application or assembly may need more functionality than the ConfigurationManager provides. For example, an assembly may need to be created that cannot access the configuration data for a configuration section through the ConfigurationManager, like the Database-StorageProvider example shown earlier. The ConfigurationContext exists to handle these more advanced configuration needs.

The following sections detail how you can use the ConfigurationManager and ConfigurationContext objects to address all of these points.

Reading Configuration Data

One of the most common needs for many applications is to read configuration data. Often a developer needs to write code that accesses a specific data store (e.g., a file or database) and reads configuration data from well-defined sections in this store. If the location or type of data store changes, the code in the application may need to be rewritten.

The ConfigurationManager's static GetConfiguration method addresses these issues. Because the knowledge about how and where to get configuration data is handled by the Configuration Application Block, you do not need to write code that is specific to any one physical store. Instead, you can use the GetConfiguration method to retrieve the configuration data for a particular configuration section. The Configuration Application Block does the rest.

Listing 1.13 demonstrates how to call the GetConfiguration method to retrieve configuration data for the TabConfig object that was shown earlier in this chapter.

Listing 1.13. Reading Configuration Data with the ConfigurationManager

[C#] object configInfo = ConfigurationManager.GetConfiguration("TabConfig"); if (configInfo is TabConfig)      appConfig = configInfo as TabConfig; [Visual Basic] Dim configInfo As Object = _      ConfigurationManager.GetConfiguration("TabConfig") If TypeOf configInfo Is TabConfig Then      appConfig = IIf(TypeOf configInfo Is TabConfig, _            CType(configInfo, TabConfig), CType(Nothing, TabConfig)) End If

Note that the return value from the GetConfiguration method must be cast to the appropriate runtime type. Also note that no code is written that is specific to accessing data from a file, database, or registry. You don't need to know where the configuration data is being stored. Not only does this ease the development effort, but it also allows the application to be more flexible to any changes that may occur to the underlying configuration store.

Writing Configuration Data

The ConfigurationManager provides a complementary method to GetConfiguration with the WriteConfiguration method. WriteConfiguration is used to write configuration data back into the physical configuration data store.

The sample application described at the beginning of this chapter lets users change different characteristics of the tabs (e.g., background color and tab label) that exist in the application. When the application is closed, this configuration data is automatically written back to the physical data store by way of the ConfigurationManager's WriteConfiguration method. Listing 1.14 shows the code for this. The configTabs variable is an instance of the object that represents the configuration data. To write the configuration data back to the configuration data store, the WriteConfiguration method is called with the name of the configuration section and the object that represents the configuration data for that section.

Listing 1.14. Saving Configuration Data with the ConfigurationManager

[C#] private void frmConfiglnfo_Closing(                      object sender,                      System.ComponentModel.CancelEventArgs e) {      ConfigurationManager.WriteConfiguration("TabConfig",configTabs); } [Visual Basic] Private Sub frmConfiglnfo_Closing( _                     ByVal sender As Object, _                     ByVal e As System.ComponentModel.CancelEventArgs)     ConfigurationManager.WriteConfiguration("TabConfig",configTabs) End Sub

Detecting Change Notification

When a StorageProvider detects that configuration data has changed in the physical data store, it fires a ConfigurationChanged event. The ConfigurationBuilder receives this event and clears that section from its cache so that it is reread the next time it is requested.

Sometimes it may be valuable for other parts of an application to also be aware when a change has been made to the configuration data in the physical configuration data store. For example, the sample application used throughout this chapter displays a dialog to end users notifying them that a change to the underlying configuration data store has changed and asks if it should immediately account for this change. To accomplish this, an application can handle the OnConfigurationChanged event notification. Listing 1.15 shows how this is accomplished in the sample application.

Listing 1.15. Detecting Configuration Changes

[C#] ConfigurationManager.ConfigurationChanged += new            ConfigurationChangedEventHandler(OnConfigurationChanged); ... private void OnConfigurationChanged(object sender,                      ConfigurationChangedEventArgs e) {     if (e.SectionName.Equals(tabConfigSectionName) && !(this.isClosing))     {           DialogResult dialogResult =                MessageBox.Show(                     SR.ConfigurationChangedMessage,                     SR.ConfigurationChangedCaption,                     MessageBoxButtons.YesNo);           if (dialogResult == DialogResult.Yes)           {                configurationChanged = true;           }      } } [Visual Basic] Private ConfigurationManager.ConfigurationChanged += New _           ConfigurationChangedEventHandler(OnConfigurationChanged) ... Private Sub OnConfigurationChanged(ByVal sender As Object, _                ByVal e As ConfigurationChangedEventArgs)      If e.SectionName.Equals(tabConfigSectionName) AndAlso _           Not(Me.isClosing) Then           Dim dialogResult As DialogResult = _                MessageBox.Show(_                     SR.ConfigurationChangedMessage, _                     SR.ConfigurationChangedCaption, _                     MessageBoxButtons.YesNo)           If dialogResult = DialogResult.Yes Then                configurationChanged = True           End If      End If End Sub

Clearing Cached Configuration Data

The configuration data for each configuration section that gets loaded by the Configuration Application Block is cached. The Configuration Application Block will use the configuration data from its cache first and will only go out to the physical data store if the configuration does not exist in cache. When a change occurs in the underlying data store, the cache is cleared.

There may be instances where it is desirable to specifically clear the cache so the Configuration Application Block will read the configuration data from the physical data store. You can use the ConfigurationManager's ClearSingletonSectionCache method to do this. If the Clear-SingletonSectionCache method is called with no parameters, all configuration sections will be cleared from the cache; if it is called with a section name, only that section's data will be cleared from the cache. Listing 1.16 shows how to clear the configuration data for the TabConfig configuration section from the cache.

Listing 1.16. Clearing the Cache of Configuration Data

[C#] ConfigurationManager.ClearSingletonSectionCache(tabConfigSectionName); [Visual Basic] ConfigurationManager.ClearSingletonSectionCache(tabConfigSectionName)

Accessing Configuration Data Through ConfigurationContext

Under special circumstances, the ConfigurationManager might not provide all the capabilities that are needed to accomplish a task. You can use the ConfigurationContext when you need more control over configuration data. For example, sometimes it is not desirable to obtain the metaconfiguration data for an application or assembly from an application domain configuration file. The ConfigurationContext supports using a file other than the application domain configuration file for reading and writing metaconfiguration.

Listing 1.17 illustrates how to create a ConfigurationContext from a file other than the application domain configuration file. The one caveat is that the file has to follow the same schema as the application domain configuration file.

Listing 1.17. Accessing Data Using the ConfigurationContext

[C#] ConfigurationContext context =       ConfigurationManager.CreateContext("differentfile.config"); [Visual Basic] Dim context As ConfigurationContext =       ConfigurationManager.CreateContext("differentfile.config")

Another special circumstance is when the configuration data needs to be retrieved and/or created in an application or process without the benefit of a backing store, as in the DatabaseStorageProvider example described earlier in this chapter. When the DatabaseStorageProvider is being configured with the Enterprise Library Configuration Tool (I'll show how this is possible in the next chapter), it is not actually running in an application. Yet it still needs to dynamically build the DatabaseInstance.

Because all application blocks have a provider factory class that accepts a ConfigurationContext in its constructor, this factory can be fed the ConfigurationContext to retrieve specific configuration information for that block. The DatabaseStorageProvider uses the DatabaseProviderFactory and a ConfigurationContext to obtain the configuration data from the Data Access Application Block. Listing 1.18 shows where this occurs in the code for the DatabaseStorageProvider.

Listing 1.18. The DatabaseStorageProvider's Use of the ConfigurationContext

 [C#] Database db; try {      db = DatabaseFactory.CreateDatabase(DatabaseInstance); } // When the Config Console is used to modify this information, // the database factory has to be used dynamically to build the // dbInstance catch (ConfigurationException configEx) {     ConfigurationContext ctx =      runtimeConfigurationView.ConfigurationContext;     try     {          DatabaseProviderFactory factory =           new DatabaseProviderFactory(ctx);      db = factory.CreateDatabase(DatabaseInstance);     } ... [Visual Basic] Dim db As Database Try      db = DatabaseFactory.CreateDatabase(DatabaseInstance) ' When the Config Console is used to modify this information, ' the database factory has to be used dynamically to build the ' dbInstance Catch configEx As ConfigurationException      Dim ctx As ConfigurationContext = _            runtimeConfigurationView.ConfigurationContext      Try            Dim factory As DatabaseProviderFactory = _                 New DatabaseProviderFactory(ctx)            db = factory.CreateDatabase(DatabaseInstance)      End Try End Try ...

By using the ConfigurationManager for most applications and the ConfigurationContext for atypical scenarios, the Configuration Application Block can help you accomplish most of the configuration scenarios that exist for enterprise applications and services.




Fenster Effective Use of Microsoft Enterprise Library(c) Building Blocks for Creating Enterprise Applications and Services 2006
Effective Use of Microsoft Enterprise Library: Building Blocks for Creating Enterprise Applications and Services
ISBN: 0321334213
EAN: 2147483647
Year: 2004
Pages: 103
Authors: Len Fenster

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net