Alois Kraus

blog

  Home  |   Contact  |   Syndication    |   Login
  133 Posts | 8 Stories | 368 Comments | 162 Trackbacks

News



Article Categories

Archives

Post Categories

Image Galleries

Programming

Microsoft Enterprise Library for .NET 2.0: Configuration

The long awaited successor of the Enterprise Library for .NET 2.0 has been released by Microsoft at MSDN. From the configuration perspective the main changes are:

  • Configuration Application Block was replaced by the .NET 2.0 System.Configuration classes.
  • Usage of ConfigurationSection and ConfigurationElement for ser/deserialization.
  • Only the Logging Application Block registers to receive file change notifications.
  • Object Builder from the CAB (Composite UI Application Block) is used for Configuration Factories.
  • Instrumentation can now be configured and is turned off by default.

Configuration of Enterprise Library Application Blocks

Possible configuration scenarios are:

  • All configuration data is in App.config (default).
  • App.config references another config file which contains all configuration data.
  • No App.config but another config file which is located by other means.
  • No config file at all. You can new up the objects directly without the help of ObjectBuilder

If you first want to get your hands dirty with the new System.Configuration mechansim of .NET 2.0 you can find more infos here. This article describes how to read/write your App.Config and store complex object graphs (e.g. type safe collections) inside your App.config ....
All scenarios except the last one (later post) are described in this article. When you configure your application blocks the default store is the System Configuration Source. With this strategy your App/Web.Config is searched for your configuration settings. You can retrieve configuration values from other config files via the File Configuration Source. Below is an example shown how to refer from your App.Config file to another XML config file which contains common EntLib Application Block settings.

<configuration>

    <configSections>

        <section name="enterpriseLibrary.ConfigurationSource" type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ConfigurationSourceSection, Microsoft.Practices.EnterpriseLibrary.Common, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null" />

    </configSections>

    <enterpriseLibrary.ConfigurationSource selectedSource="System Configuration Source">

        <sources>

            <add name="File Configuration Source" type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.FileConfigurationSource, Microsoft.Practices.EnterpriseLibrary.Common, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"

                filePath="c:\Shared.config" />

            <add name="System Configuration Source" type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.SystemConfigurationSource, Microsoft.Practices.EnterpriseLibrary.Common, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null" />

        </sources>

    </enterpriseLibrary.ConfigurationSource>

</configuration>

Sample base config to share config setting across several App.Connfig files

Enterprise Library´s famous graphical configuration tool GUI is very similar to its predecessor. Normally you only need to recreate your configuration files with the new config tool and you are done. In your App.Config a config section is created which uses the FileConfigurationSource that refers to the real config file for your application.

How does the System.Configuration mechanism work?

The goal is to allow the de/serialization of strongly typed objects to and from XML using a human readable format. Every App.Config file begins with a <configuration> tag followed by a <configSections> tag. In this section the XML node name and its type responsible for ser/deserialization is stored. The picture below illustrates this.

Serilization of config settings into a class

When you call a Configuration.GetSection("loggingConfiguration") the LoggingSettings type is from the specified assembly loaded. A ConfigurationSection object can contain in its properties standard types like bool, string, ... which are de/serialized as attributes in the sectione.g. Formatters, Name, TracingEnabled (green rectangles) . Complex types must derive from ConfigurationElement which are de/serialized as a new XML nodes (e.g. yellow node TraceListeners collection). The configuration subsystem takes care of the de/serialization of this compact xml representation of your configuration settings. After all types have been reconstructed you can cast the returned ConfigurationSection object to its original type LoggingConfiguration and use it. Since the Configuration system uses caching the returned objects are read only. You have to create a new configuration object if you want to store a changed configuration section. 


Retrieval of Config Settings with no App/Web.config

So much for the eye candy with nice GUI and automatic config file generation. An alternative approach without any App/Web.config is possible. This way you don't need to specify the path and file name in n App.config files. Good candiates for common settings are the Exception Handling and Logging Block. The bad news is that to change the configuration Source of this two block you need to replace the static facades by your own ones. Once done you can create your own FileConfigurationSource and point to your global config file. This way you have encapsulated the location and name of a global config file at one central storage location.

LogWriter writer = null;

FileConfigurationSource source = new FileConfigurationSource(@"C:\Shared.config");

factory = new LogWriterFactory(source);

writer = factory.Create();

But wait you don´t need to stop here. Why not get your configuration from somewhere else? The Application Block´s retrieve their configuration via the interface IConfigurationSource. One of the Enterprise Library samples show´s you how to implement a SqlConfigurationSource. Now we can get e.g. the logging settings from a totally different storage location.

SqlConfigurationSource source = new SqlConfigurationSource(

                                                                “Connection String“,

                                                                “EntLib_GetStoredProcName“,

                                                                “Entlib_SetStoredProcName“,

                                                                “Entlib_RefreshStoredProcName“,

                                                          “Entlib_RemoveStorecProcName“);

factory = new LogWriterFactory(source);

writer = factory.Create();

 

 

No Configuration Block anymore

With .NET 2.0 many new features have been introduced, especially the System.Configuration namespace has been significantly enhanced. The ConfigurationMigration Quick Start Sample of the Enterprise Library shows you how to read and write configuration values with no help of the Enterprise Library at all. Reading a ConfigurationSection is easy but writing is a bit more tricky. The reason behind this is that when you call ConfigurationManager.GetSection a read only ConfigurationSection is returned. To save a changed configuration section you actually have to remove the section and then add it again.

                using System.Configuration;

 

                               // Open App.Config file 

                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

                config.Sections.Remove("EditorSettings");

                config.Sections.Add("EditorSettings", configData);

                // Write the new configuration data to the XML file

                config.Save();

So when do I need the Enterprise Library?

If you want more than the default System.Configuration System supports. This are

  • Register for changes in configuration settings.
  • Read/Write Configuration Settings from SQL Server.
  • Read/Write arbitrary configuration files.
  • Store objects with full type and version info inside Strongly Typed Collections (PolymorphicConfigurationElementCollection).
  • Switch from one config file to another one by changing your App.config file

To retrieve your configuration values from the currently configured repository you can use the following code snippet:

            // Create SystemConfigurationSource if SystemConfigurationSource is selected

            // or a FileConfigurationSource if another config file is referenced in my App.config file

            IConfigurationSource selectedConfig = ConfigurationSourceFactory.Create();

 

            // Get Configuration from wherever even SQL Server configuration source is possible

            // via this generic interface

            ThreedConfigData conf = selectedConfig.GetSection("ThreedConfiguration") as ThreedConfigData;



More info about strongly the strongly typed collection class PolymorphicConfigurationElementCollection can be found here.

You can link with System.Configuration config files together. But it is complicated to read and write arbitrary config files with this mechanism. Luckily the new Enterprise Library helps you out. The code below does exactly the same than the one above: Store some data in an config file.

                using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;

 

             

                const string CFG_FILE = @"C:\mySettings.config";

                FileConfigurationSource source = new FileConfigurationSource(CFG_FILE);

                source.Save(CFG_FILE, "MySection", configData);

As you can see configuration has become easier and more flexible with the new Enterprise Library. The work at the Patterns & Practices group shows what can be achieved when quality is the goal number one. Have a look at the new features and the library itself. It is definitely worth it.

Fans of the "old" Enterprise Library can look for configuration tips from from Scott Densmore.

Thats all for today and about time to go to bed (3.26 am GMT+1).

posted on Monday, December 12, 2005 12:44 AM

Feedback

# re: Microsoft Enterprise Library for .NET 2.0: Configuration 12/15/2005 5:50 PM Marcus
Thanks for the article.

Is there a way to break out just portions of the entlib configuration into multiple files using the GUI?

For example, I want to move the connection and database settings into a data.config file and all the logging settings into logging.config.

All I can figure out is how to move the whole thing to just one file.

Thanks again.

# re: Microsoft Enterprise Library for .NET 2.0: Configuration 12/15/2005 6:10 PM Alois Kraus
Hi Marcus,

you can create two config files with the Entlib Config tool and use then the FileConfigurationSource to load the respecitve settings. Then you only need to feed the right configuration source object desired Application Block and you are done.

Yours,

Alois Kraus

# re: Microsoft Enterprise Library for .NET 2.0: Configuration 12/15/2005 9:02 PM Marcus
Are you saying I have to do it with VB/C# code somewhere or can it be done within the .config files? If the later, please elaborate with examples.

Thanks!

# re: Microsoft Enterprise Library for .NET 2.0: Configuration 12/15/2005 9:50 PM Alois Kraus
Hi Marcus,
ahh you wanted to go the easy way. Here it is:

1. Create New App.Config.
2. Add File Configuration Source with file
LoggingSettings.config
3. Add File Configuration Source with file
DBSettings.config
4. Close App.Config
5. Open LoggingSettings.Config
6. Add Logging Application Block and configure it
7. Close LoggingSettings.Config
8. Open DBSettings.Config
9. Add DB ApplicationBlock and configure it
10. It should work this way graphically ;-)

I think it should also be possible to use this App.config link file as input for a FileConfigurationSource and use it like an external config file.

Yours,

Alois


# re: Microsoft Enterprise Library for .NET 2.0: Configuration 1/14/2006 9:30 PM Frank
Thank you so much !!!

# re: Microsoft Enterprise Library for .NET 2.0: Configuration 1/25/2006 5:06 PM Richard
Alois,
Can you show me how to link a custom config file to app.config? I'd like to serialize the config section in that file into a custom value object class.

Thanks!

# re: Microsoft Enterprise Library for .NET 2.0: Configuration 1/26/2006 8:16 PM Alois Kraus
Hi Richard,

you can store in your app.config inside the AppSettings sections your config file name. To retrieve it you can use string filename = ConfigurationManager.AppSettings["FileName"];
and then use the Enterprise Library File Configuration Source to do the rest.

FileConfigurationSource source = new FileConfigurationSource(filename);

object deserialized = source.GetSection("mySection");
source.Save(filename,newsection,"mySection");

Hope this helps a bit.

Yours,

Alois Kraus



# re: Microsoft Enterprise Library for .NET 2.0: Configuration 2/2/2006 4:54 PM Richard
Alois,
Thanks for your reply. Sorry that I didn't explain my problem clearly. Actually I'd like the link happen automatically without any code.
With the old Enterprise Libray, you may specify SectionHandler within <section>, for example:
<section name="enterpriselibrary.configurationSettings" type="System.Configuration.IgnoreSectionHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />

Then in that section, you specify the storageProvider and dataTransformer to automatically load the config when App.conig is loaded:
<configurationSection name="EditorSettings" encrypt="false">
<storageProvider xsi:type="XmlFileStorageProviderData" name="XML File Storage Provider" path="../../../EditorSettings.config" />
<dataTransformer xsi:type="XmlSerializerTransformerData" name="Xml Serializer Transformer">
<includeTypes />
</dataTransformer>
</configurationSection>

Now I can't find the sectionHandler, storageProvider, or Transformer classes in the new Enterprise Library. According to the document, most the functionalities are now within .Net 2.0 but I can't figure out how.

Thank you for your time.



# re: Microsoft Enterprise Library for .NET 2.0: Configuration 2/2/2006 5:16 PM Alois Kraus
Hi Richard,

to use the EditorSettings from wherever you would like you can use the

IConfigurationSource currentConfig = ConfigurationSourceFactory.Create() method.
xxxx = currentConfig.GetSection("EditorSettings");


This returns the currently selected configurationsource which you can use from now on. Please refer to the first picture what I mean with selected configuration source.

Yours,

Alois Kraus


# re: Microsoft Enterprise Library for .NET 2.0: Configuration 2/4/2006 10:00 PM Richard
Alois,
Yes, it worked! Thank you very much!

# re: Microsoft Enterprise Library for .NET 2.0: Configuration 2/7/2006 9:23 PM Alois Kraus
Hi Tom,

is the sample App.config of the other article http://geekswithblogs.net/akraus1/articles/64871.aspx insufficient? I am glad to hear about what can/should be improved.

# re: Microsoft Enterprise Library for .NET 2.0: Configuration 2/7/2006 10:56 PM Mick
I have a similar question to Tom. In EntLib 1.1, I have been using the EntLib ConfigurationManager and custom classes to strongly type config settings in an alternative config file e.g. Dim mySettings As ApplicationData = DirectCast(ConfigurationManager.GetConfiguration("MySettings"), ApplicationData)

I would like to continue storing some application settings in an alternative config. In EntLib 2.0, I specify in my app.config a FileSource (NOT the selected source as this seems to be needed by the data config) - how do I use this source setting to select this alternative config and strongly type the settings in it??

# re: Microsoft Enterprise Library for .NET 2.0: Configuration 2/22/2006 5:43 AM Tran Ngoc Van
SqlConfigurationSource is all I need, except it does not accept ConnectionStrings section, due to ConnectionStrings is not derived from SerializableSection :(

# re: Microsoft Enterprise Library for .NET 2.0: Configuration 2/22/2006 5:45 AM Tran Ngoc Van
Is there anyway to put the ConnectionStrings section to SqlConfigurationSource?

# re: Microsoft Enterprise Library for .NET 2.0: Configuration 2/22/2006 9:40 PM Alois Kraus
Hi Tran,

try the following App.Config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="test" type="System.Configuration.ConnectionStringsSection,System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
</configSections>
<test>
<add name="ConnStr1" connectionString="LocalSqlServer: data source=127.0.0.1;Integrated Security=SSPI;Initial Catalog=aspnetdb"
providerName="System.Data.SqlClient" />
<add name="ConnStr2" connectionString="LocalSqlServer: data source=128.0.0.1;Integrated Security=SSPI;Initial Catalog=aspnetdb"
providerName="System.Data.SqlClient" />
</test>
</configuration>
With this code it works fine for me:

static void Main(string[] args)
{
ConnectionStringsSection section = ConfigurationManager.GetSection("test") as ConnectionStringsSection;
foreach (ConnectionStringSettings set in section.ConnectionStrings)
{
Console.WriteLine("Server: " + set.ConnectionString);

}
}


# re: Microsoft Enterprise Library for .NET 2.0: Configuration 2/23/2006 8:35 PM Zia
How would you read the following custom section using the ConfigurationManager? I get an error saying CData or text elements are not allowed. If I change my data to reside in attributes of the CustomSectionName, it works fine.

<CustomSectionName>
<FirstName>John</FirstName>
<LastName>Doe</LastName>
</CustomSectionName>



# re: Microsoft Enterprise Library: Configuration 3/9/2006 6:06 AM Dhirendra
Hi,
Please tell me, How to read all nodes EditorSettions.config file if file contians more than one node (EditorFontData).

As GetConfiguration only returns first node.

Please reply.

Thanks in Advance
Dhirendra

# re: Microsoft Enterprise Library for .NET 2.0: Configuration 3/9/2006 4:38 PM Alois Kraus
Hi Dhirendra,

you can have more than one EditorFontData element in your App.Config but you need to put it into a collection which is derived from ConfigurationElementCollection. Subsequent calls to GetSection will not work since it does not contain any state.

Yours,
Alois Kraus


# re: Microsoft Enterprise Library for .NET 2.0: Configuration 3/16/2006 2:25 PM James
Hi Alois Kraus,
I want to save configuration setting in SQL server and use these setting for other application block,but I don't know how to use those store procedure.Which content of the value do I need to insert? Do you have any sample code or document for this issue?Your reply will be appreciate.

James

# re: Microsoft Enterprise Library for .NET 2.0: Configuration 4/18/2006 6:57 PM Ed
How does this work with the Composite UI App Block (CAB)? I successfully used this approach with the ExceptionHandlingWithLoggingQuickStart provided with EntLib 2.0, but when I tried it with the BankTeller QuickStart from the CAB QuickStar, it fails.

# re: Microsoft Enterprise Library for .NET 2.0: Configuration 4/18/2006 8:53 PM Alois Kraus
Hi Ed,

I would ask this question in the right forum:
http://www.gotdotnet.com/codegallery/messageboard/home.aspx?id=295a464a-6072-4e25-94e2-91be63527327&mbid=98d6b0f4-da31-4314-a885-79824ba842ba
To help you successfully you should provide some additional information what did go wrong (Exception stack ...). A forum is a much better way to answer your question/s

Yours,
Alois Kraus

# re: Microsoft Enterprise Library for .NET 2.0: Configuration 6/7/2006 1:51 PM Moi
With the old Enterprise Libray, you may specify SectionHandler within <section>, for example:
<section name="enterpriselibrary.configurationSettings" type="System.Configuration.IgnoreSectionHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />

Then in that section, you specify the storageProvider and dataTransformer to automatically load the config when App.conig is loaded:
<configurationSection name="EditorSettings" encrypt="false">
<storageProvider xsi:type="XmlFileStorageProviderData" name="XML File Storage Provider" path="../../../EditorSettings.config" />
<dataTransformer xsi:type="XmlSerializerTransformerData" name="Xml Serializer Transformer">
<includeTypes />
</dataTransformer>
</configurationSection>

Now I can't find the sectionHandler, storageProvider, or Transformer classes in the new Enterprise Library. According to the document, most the functionalities are now within .Net 2.0 but I can't figure out how.

Please insert a detailled example

# re: Microsoft Enterprise Library for .NET 2.0: Configuration 6/10/2006 1:20 AM brad
Can you encrypt sections of a shared config file, and have them decrypted properly with FileConfigurationSource ? I have some shared database connections that have username/passwords in the connection strings that I'd like to hide (non SQL server), but all of the examples using encryption seem to assume ASP.Net configuration files.

# re: Microsoft Enterprise Library for .NET 2.0: Configuration 7/21/2006 6:56 PM Vadim Farberov
Hi Alois,

I would like to split configuration into 2 parts, shared configuration and application configuration, where application configuration will be in app.config, and the shared configuration could be in either database using SqlConfigurationSource or a shared network file using FileConfigurationSource. I would like the application confiuguration settings to override the shared configuration settings.

For example, for the Logging Application Block, all the applications may share the same Category Sources, Formatters and TraceListeners, but have different Filters. Or in another example, shared configuration may define 5 trace listeners, but application configuration add one more and replace settings on an existing one. In other word, overriding can be done not on the block level, but lower, on the particular setting level.

How would you recommend to better implement that?

Thank you very much

# re: Microsoft Enterprise Library for .NET 2.0: Configuration 7/23/2006 4:37 PM Alois Kraus
Hi Vadim,
you are asking for configuration inheritance which is explicitely not supported by the Enterprise Library configuration concept. Sorry I have no solution for this problem yet but the new
Manageability Extension to Entlib (http://blogs.msdn.com/tomholl/archive/2006/07/20/EntLibManageabilityExtensions.aspx) do look promising to enable you to do something similar with Active Directory Group Policies and WMI.

Yours,
Alois Kraus


# re: Microsoft Enterprise Library for .NET 2.0: Configuration 7/25/2006 12:27 PM Vadim Farberov
Hi Alois,

I have looked at the article, but Active Directory and WMI seem to be overkill for me.

I plan to go a different route:

* Have a shared master config file, and a application config file with the override/added settings.
* Merge them on startup, creating the real application config file. If it is called app.config I may even use the EntLib facade classes.
* To track the changes I may track the changes in both source files, and merge again if any of them changes.

Do you see any problemn with this solution?

Thank you,

Vadim


# re: Microsoft Enterprise Library for .NET 2.0: Configuration 7/27/2006 6:19 AM anuo
how to store the configuratio settings into database? & use them in the file

# Donde esta el Application Block de Configuracion en Enterprise Library 2.0 ??? 8/16/2006 2:57 AM ElBruno
Esta pregunta me la han hecho varias veces, desde el lanzamiento de Enterprise Library 2.0 , y la respuesta

# ¿Donde esta el Application Block de Configuracion en Enterprise Library 2.0? 9/30/2006 5:02 AM El Bruno
Esta pregunta me la han hecho varias veces, desde el lanzamiento de Enterprise Library 2.0 , y la respuesta

# re: Microsoft Enterprise Library for .NET 2.0: Configuration 2/20/2007 5:56 AM Ank
Hi Alois,
I am a newcomer to the field of programming. I am trying to develop a Web Service using Enterprise Library 2.0.

I have another config file other than web.config, in which i need to acces the data.
If the config file is like : ExtraDetails.Config
---------------------------
<?xml version="1.0" encoding="utf-8">
<RootNode>
<Node1>
<Value>data-1</Value>
<Value>data-2</Value>
</Node1>
<Node2>data-3</Node2>
</RootNode>
---------------------------

In the Enterprise Library I have added a Config block. A system Config source and File Config source (pointing to this XML file). The Config block default source is system config source.

I have created a class of the xml file (read somewhere that I would need to use serialization in here).

Now I want to know in the web method of the Web service how do I access the values of ExtraDetails.Config. After accessing the values I would further use them.

I did try using ConfigManager, but wasnt able to use it.

Please let me know the approach to proceed.

Thanks



# re: Microsoft Enterprise Library for .NET 2.0: Configuration 9/21/2007 8:51 AM Mayra
My problem is: I have several projects within my solution. Each project have an AppConfig file, I need integrate the configuration values of all AppConfig files in an main AppConfig, How can I integrate all configuration values in the AppConfig file from a project that is the start up project?

# re: Microsoft Enterprise Library for .NET 2.0: Configuration 10/25/2007 10:50 PM Patrice Marengo
Hello Alois,

In my Web.Config file, I have under the tag <formatters> 2 template as shown:

<formatters>
<add template="Timestamp: {timestamp}&#xA;Message: {message}&#xA;" type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null" name="Text Formatter1"/>

<add template="Timestamp: {timestamp}&#xA;Message: {message}&#xA;Priority: {priority&#xA;"type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null" name="Text Formatter2"/>

</formatters>

Questions:
1. How can I read the formatters in a C# application?
2. How can I detect one from the other?

Thanks
Patrice

# re: Microsoft Enterprise Library for .NET 2.0: Configuration 1/8/2008 7:28 AM Aman
Can someone tell me how to encrypt a config file...

# re: Microsoft Enterprise Library for .NET 2.0: Configuration 5/15/2008 5:27 AM Isuka
Can we combine app.config files of multiple projects into a root config file using Enterprise library manager?Please help.

# re: Microsoft Enterprise Library for .NET 2.0: Configuration 8/19/2009 6:42 AM Qutaibahs
In case of standalone cash this solution works but when you go to enterprise level it gradually drops performance . This drawback can be overcome by using third party integrations including NCache which is freely available and can be tested for the performance and scalability.

Post A Comment
Title:
Name:
Email:
Comment:
Verification: