Category Archives: ConfigurationSectionHandler

Cinchoo – Consume JSON format configuration values

1. Introduction

Cinchoo is an application framework for .NET. One of the main functionality it provides to users is the application configuration management. Application configuration is information that an application reads and/or writes at run-time from the source.

Please visit jump start article [Cinchoo – Simplified Configuration Manager] for more information about Cinchoo configuration manager.

In this section, I’m going to show you how to consume JSON data as configuration values using the Cinchoo configuration framework. It gives an opportunity to use industry standard message format as configuration source.

Let’s start this exercise using the below values defined in test.json file. This file can be places in any folder. You must specify the absolute path of this file while defining configuration object. Please note, if the file is not present, it will be created automatically the very first time the application starts.

Listing 1.1 Sample JSON file (test.json)

{"name":"Mark","address":"10 River Road, 08837","RunDate":"8\/16\/2015 6:16:36 PM"}

2. How to use

  • Open VS.NET 2010 or higher
  • Create a sample VS.NET (.NET Framework 4) Console Application project.
  • Download the latest Cinchoo.Core.Configuration.JSON via nuget. (Nuget Command: Install-Package Cinchoo.Core.Configuration.JSON)
  • Use the Cinchoo.Core.Configuration namespace
  • Define a configuration object ‘ApplicationSettings‘ as below.

Listing 2.1 Defining Configuration Object

[ChoJSONConfigurationSection("appSettings", ConfigFilePath = "test.json")]
public class ApplicationSettings : ChoConfigurableObject
{
    [ChoPropertyInfo("name", DefaultValue = "Mark")]
    [ChoNotNullOrWhiteSpaceValidator]
    public string Name
    {
        get;
        set;
    }

    [ChoPropertyInfo("address", DefaultValue = "10 River Road, 08837")]
    public string Address;

    [ChoPropertyInfo("Date", DefaultValue = "%%NOW^MM/dd/yyyy HH:mm:ss%%")]
    public DateTime RunDate;

    protected override void OnAfterConfigurationObjectLoaded()
    {
        Console.WriteLine(ToString());
    }
}

The code above illustrates about defining configuration object. First thing defines a configuration object (ex. ApplicationSettings) class from ChoConfigurableObject, it indicates that this object is a configuration object. And it must be decorated with ChoJSONConfigurationSectionAttribute to complete the definition. This attribute enables the configuration object to read and write configuration values from ‘test.json’ file.

Define three members Name, Address and RunDate as public fields or properties with get and set in it. Decorate them with ChoPropertyInfo attribute to indicate that they are configuration members. In this sample, Name property is given name as property name with defaultvalue as ‘Mark‘. It means that this member will be defaulted to default value when the value is missing in the configuration file. Respectively declare other members for each appSettings key. It is a very simple and clear way of specifying configuration members using attributes.

Once you have class declared as above, it is now ready to consume ‘test.json’ values as simple as creating object out of it. Any changes made to this object and/or in the test.json file will be exchanged automatically. The sample code is as below:

Listing 2.2 Main method

static void Main(string[] args)
{
    ApplicationSettings applicationSettings = new ApplicationSettings();
    Console.WriteLine(applicationSettings.Name);
    ChoConsole.PauseLine();
}

We start by creating a new instance of ApplicationSettings object. That’s all. All the heavy lifting of loading appSettings values to the object is done by the Cinchoo framework under the hood.

Just compile and run the above sample, it will output as below:

Listing 2.3 Output of Test1.exe

-- Cinchoo.Core.Configuration.JSON.Test.AppSettings State --
        Name: Mark
        Address: 10 River Road, 08837
        RubDate: 8/17/2015 10:02:08 PM

Press ENTER key to continue...

Now let’s see how the application picks up the changes made to the test.json file reflected in the output. Open test.json file, edit the name from ‘Mark‘ to ‘Tom‘ and save the file.

Listing 2.4 Output of Test1.exe when changing the values in the App.Config file

-- Cinchoo.Core.Configuration.JSON.Test.AppSettings State --
        Name: Mark
        Address: 10 River Road, 08837
        RubDate: 8/17/2015 10:02:08 PM

Press ENTER key to continue...
-- ChoStandardAppSettingsConfig.Test.ApplicationSettings State --
        Name: Tom
        Address: 10 River Road, 08837
        RubDate: 8/17/2015 10:02:08 PM

That’s all. A sample project is attached. Download and try for yourself.

Advertisements

Cinchoo – Using AppSettings as configuration Source

Download Sample – 4.4 KB

1. Introduction

Cinchoo is an application framework for .NET. One of the main functionality it provides to users is the application configuration management. Application configuration is information that an application reads and/or writes at run-time from the source.

Please visit jump start article [Cinchoo – Simplified Configuration Manager] for more information about Cinchoo configuration manager.

In this section, I’ll show you with sample reading/writing AppSettings using the Cinchoo configuration framework. It gives the opportunity loading and using application settings values in your .NET applications.

Let’s start this exercise using the below appSettings values (FYI, this section is not mandatory to present in App.Config when using Cinchoo framework. It will be created automatically very first time the application starts.)

Listing 1.1 Sample AppSettings values in App.Config

<?xml version="1.0"?>
<configuration>
<appSettings>
    <add key="name" value="Mark" />
    <add key="address" value="21 River Road, New York, NY 10010" />
    <add key="invoiceAmount" value="11.2120001" />
</appSettings>
</configuration>

Usually you can consume these values using .NET API as follows

Listing 1.2 Consume appSettings using .NET API

class Program
{
    static void Main(string[] args)
    {
        string name = ConfigurationManager.AppSettings["name"];
        string address = ConfigurationManager.AppSettings["address"];
        double invoiceAmount = Convert.ToDouble(ConfigurationManager.AppSettings["invoiceAmount"]);
    }
}

Accessing appSettings using the above approach lacks below features

  1. Automatic type conversion
  2. Change notification of values in the source
  3. Auto saving of changes values back to source
  4. Type-safe mechanism
  5. Defining and using Default values
  6. Auto creation of key-values if missing

Cinchoo offers the above features out of the box. Just by simply declaring a class with appropriate members, should be sufficient to consume the appSettings values. Read further on how to do it.

2. How to use

  • Download latest Cinchoo binary here. (Nuget Command: Install-Package Cinchoo)
  • Open VS.NET 2010 or higher
  • Create a sample VS.NET (.NET Framework 4) Console Application project.
  • Add reference to Cinchoo.Core.dll
  • Use the Cinchoo.Core.Configuration namespace
  • Define a configuration object ‘ApplicationSettings‘ as below.

Listing 2.1 Defining Configuration Object

[ChoStandardAppSettingsConfigurationSection]
public class ApplicationSettings : ChoConfigurableObject
{
    [ChoPropertyInfo("name", DefaultValue="Mark")]
    public string Name;

    [ChoPropertyInfo("address", DefaultValue = "21 River Road, New York, NY 10010")]
    public string Address;

    [ChoPropertyInfo("invoiceAmount", DefaultValue = "11.21201")]
    public double InvoiceAmount;

    protected override void OnAfterConfigurationObjectLoaded()
    {
        Console.WriteLine(ToString());
    }
}

The code above illustrates about defining configuration object. First thing define a configuration object (ex. ApplicationSettings) class from ChoConfigurableObject, it indicates that this object is a configuration object. And it must be decorated with ChoStandardAppSettingsConfigurationSectionAttribute to complete the definition. This attribute enables the configuration object to read and write configuration values under ‘appSettings’ section in App.Config file.

Define three members Name, Address and InvoiceAmount as public fields or properties with get and set in it. Decorate them with ChoPropertyInfo attribute to indicate that they are configuration members. In this sample, Name property is given name as property name with defaultvalue as ‘Mark’. It means that this member will be defaulted to default value when the value is missing in the configuration file. Respectively declare other members for each appSettings key. It is very simple and clear way of specifying configuration members using attributes.

Once you have class declared as above, it is now ready consume appSettings values as simple as creating object out of it. Any changes made to this object and/or in the app.Config file will be exchanged automatically. The sample code as below

Listing 2.2 Main method

static void Main(string[] args)
{
    ApplicationSettings applicationSettings = new ApplicationSettings();
    ChoConsole.PauseLine();
}

We start by creating new instance of ApplicationSettings object, That all. All the heavy lifting of loading appSettings values to the object done by the Cinchoo framework under the hood.

Just compile and running the above sample, it will output as below

Listing 2.3 Output of Test1.exe

-- ChoStandardAppSettingsConfig.Test.ApplicationSettings State --
        Name: Mark
        Address: 21 River Road, New York, NY 10010
        InvoiceAmount: 11.21201

Press ENTER key to continue...

Now let’s see how the application picks up the changes made to the [AppExeName].Config file reflected in the output. Open [AppExeName].config file, edit the name from ‘Mark’ to ‘Tom’ and save the file.

Listing 2.4 Output of Test1.exe when changing the values in the config file

-- ChoStandardAppSettingsConfig.Test.ApplicationSettings State --
        Name: Mark
        Address: 21 River Road, New York, NY 10010
        InvoiceAmount: 11.21201

Press ENTER key to continue...
-- ChoStandardAppSettingsConfig.Test.ApplicationSettings State --
        Name: Tom
        Address: 21 River Road, New York, NY 10010
        InvoiceAmount: 11.21201

2. Advanced Settings

2.1 Override ConfigurationManager

Cinchoo automatically instantiates and uses appropriate ConfigurationManager depending on the type of the application. Your application works seamlessly out of the box to read and write appSettings. Rarely, you may want to override this behaviour to take control of using different ConfigurationManager. You can do so as below:

Listing 2.1.1 Overriding ConfigurationManager
class Program
{
    static void Main(string[] args)
    {
        ChoApplication.AfterConfigurationManagerInitialized += 
            ChoApplication_AfterConfigurationManagerInitialized;
    }

    static void ChoApplication_AfterConfigurationManagerInitialized(object sender, EventArgs e)
    {
        //Instantiate and assign to ChoConfigurationManager.ApplicationConfiguration member
       ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoaming);
    }
}

2.2 External AppSettings file

Many of you are aware that you can specify external file containing application settings. Cinchoo framework works with this external file as well. Any filepath specified as appSettings external filepath will be automatically created if not present, watch for any changes and save the changes to them, etc. The filepath can be either relative or absolute path. The path specified is relative to the main executable location. For a Windows Forms application, this would be the binary folder (such as /bin/debug), not the location of the application configuration file. For Web Forms applications, the path is relative to the application root, where the web.config file is located. Note that the runtime ignores the attribute if the specified file cannot be found.

Listing 2.2.1 Sample AppSettings section with file attribute
<configuration>
    <appSettings file="appSettings.xml">
    </appSettings>
</configuration>

That’s all. A sample project is attached. Download and try for yourself.

Cinchoo – Configuration Framework, Part 31

Disable logging

Cinchoo is an application framework for .NET. One of the main functionality it provides to users is application configuration management. Application configuration is the information that an application reads and/or writes at run-time from the source.

Please visit jump start article [Cinchoo – Simplified Configuration Manager] for more information about Cinchoo configuration manager.

In this section, I’ll show to disable logging of Cinchoo framework produces. Open a app.config file from your project. Add the below section

<configuration>
 <system.diagnostics>
   <switches>
     <add name="ChoSwitch" value="0" />
   </switches>
 </system.diagnostics>
</configuration>

ChoSwitch is a TraceSwitch, you can assign different levels to it to specify the types of trace or debug messages the application outputs. Setting the value to “0” will disable all the logging of the framework.

Other possible values can be assigned to control the output of the logs

  • 0 – Off
  • 1 – Error
  • 2 – Warning
  • 3 – Info
  • 4 – Verbose

Cinchoo – Configuration Framework, Part 30

Consume configuration values from any database.

Download Sample (Zip)

Cinchoo is an application framework for .NET. One of the main functionality it provides to users is application configuration management. Application configuration is the information that an application reads and/or writes at run-time from the source.

Please visit jump start article [Cinchoo – Simplified Configuration Manager] for more information about Cinchoo configuration manager.

In this section, I’ll detail about new configuration section handler, DbGenericeKeyValueConfigurationSection. It is generic database configuration section handler to read and store configuration data in any database. It eliminates creating new configuration section handler for each targeted database. All you need ADO.NET driver for the corresponding database to work with this handler. This section handler sufficient enough to interact with any database to read/store configuration data. Only downside of this handler is that all the values are converted to string before storing in the database.

Here are steps to work with this section handler

  • Define a table similar to the below schema. The table name can be given anything. This configuration handler needs a table with 2 columns. First column (KEY) holds the configuration parameter names. Must be VARCHAR(50), where length must be minimum of 50. Second column (VALUE) holds the configuration parameter values. It can be size of any. By default, this handler looks for KEY, VALUE as columns. The names of these columns can be given any. In this case, it must be passed as parameter to the configuration object. Will discuss this later about passing these parameters to the configuration object.
CREATE TABLE TEST_CONFIG
(
    [KEY] VARCHAR (50) NOT NULL,
    VALUE VARCHAR (100),
    PRIMARY KEY ([KEY])
)
  • Define configuration object targeted for Sqlite database as below
[ChoDbGenericKeyValueConfigurationSection("dbApplicationSettings",
@"CONNECTION_STRING='Data Source=.\SqliteTest.db;Version=3;Pooling=True;Max Pool Size=100;';
 TABLE_NAME=TEST_CONFIG;PROVIDER_ASSEMBLY_FILE_PATH=C:\Program Files\System.Data.SQLite\2010\bin\System.Data.SQLite.dll;PROVIDER_NAMESPACE=System.Data.SQLite;
 LAST_UPDATE_DATETIME_KEY_NAME=''", Silent = true)]
public class DbApplicationSettings : ChoConfigurableObject
{
 [ChoPropertyInfo("name", DefaultValue = "Mark")]
 public string Name;

 [ChoPropertyInfo("address", DefaultValue = "10 River Road, Edison NJ 08820")]
 public string Address;

 protected override void OnAfterConfigurationObjectLoaded()
 {
 Console.WriteLine(this.ToString());
 }
}

This configuration object must be decorated with ChoDbGenericKeyValueConfigurationSectionAttribute.

First parameter is the configElementPath, a xpath to the configuration section in the [appName].exe.xml file.

Second parameter is the configObjectAdapterParams, parameter list in key-value pairs format separated by ‘;’ character. (PS. If any value contains ‘;’ character, the whole value must be surrounded by single quote in order to escape it.) Below are the list of applicable parameters needed by this section handler

  1. CONNECTION_STRING (string) – Required. ADO.NET connection string to the database.
  2. TABLE_NAME (string) – Required. Configuration table name.
  3. PROVIDER_ASSEMBLY_FILE_PATH (string) – Optional. Only specify if the ADO.NET assembly is not referenced in the project. File path to the ADO.NET assembly if not in GAC. Otherwise, fully qualified assembly name.
  4. PROVIDER_NAMESPACE (string) – Required. Namespace of the ADO.NET provider (Ex. for Sqlite, it is System.Data.Sqlite)
  5. KEY_COLUMN_NAME (string) – Optional. Default is ‘KEY’. If you have different key column name, please specify it here.
  6. VALUE_COLUMN_NAME (string) – Optional. Default is ‘VALUE’. If you have different value column name, please specify it here.
  7. LAST_UPDATE_DATETIME_KEY_NAME (string) – Optional. Default is Empty string. In such case, this provider checks the configuration values for any changes in the underlying table. If you specify a valid key name, it must carry the value as timestamp. To notify the values changes by touching this value to last updated time stamp.
  8. PARAM_PREFIX_CHAR (char) – Optional. Default is ‘@’.
  9. TRUNCATE_VALUE_DATA (bool) – Optional. Default is True.  It will truncate the value if it is over the Value column size.

The above two parameters can be hard-coded in the code and also be modifiable through configuration. Here is how you can modify them through configuration. Open the [AppName].exe.xml file under Config folder

<?xml version="1.0" encoding="utf-8"?>
<configuration>
 <configSections>
 <section name="dbApplicationSettings" type="Cinchoo.Core.Configuration.ChoDictionarySectionHandler, Cinchoo.Core" />
 </configSections>
 <dbApplicationSettings cinchoo:configObjectAdapterType="Cinchoo.Core.Configuration.ChoDbGenericKeyValueConfigStorage, Cinchoo.Core" xmlns:cinchoo="http://schemas.cinchoo.com/cinchoo/01/framework">
 <cinchoo:configObjectAdapterParams xmlns:cinchoo="http://schemas.cinchoo.com/cinchoo/01/framework"><![CDATA[CONNECTION_STRING='Data Source=.\SqliteTest.db;Version=3;Pooling=True;Max Pool Size=100;';
 TABLE_NAME=TEST_CONFIG;PROVIDER_ASSEMBLY_FILE_PATH=C:\Program Files\System.Data.SQLite\2010\bin\System.Data.SQLite.dll;PROVIDER_NAMESPACE=System.Data.SQLite;
 LAST_UPDATE_DATETIME_KEY_NAME='']]></cinchoo:configObjectAdapterParams>
 </dbApplicationSettings>
</configuration>

Now lets try to create and consume the above configuration object. Below code shows how to consume and modify the object members

static void Main(string[] args)
{
    DbApplicationSettings DbApplicationSettings = new DbApplicationSettings();

    ChoConsole.PauseLine();
}

Compile and run this sample to see the output stored in the database.

That’s it folks, it is as easy as to store and consume Configuration values in any databases.

Cinchoo – Using a SQL Server database as a configuration source, Part 2

Download Sample

Cinchoo is an application framework for .NET. One of the main functionality it provides to users is application configuration management. Application configuration is information that an application reads and/or writes at run-time from the source.

Please visit jump start article [Cinchoo – Simplified Configuration Manager] for more information about Cinchoo configuration manager.

In this section, I’m going to detail you about using SQLServer database as configuration source for your applications. More commonly all the .NET application configuration are kept in files as XML format. It has the limitation, such as maintaining them for each application separately, potential disk corruption by many applications due to access etc. This may not fit in enterprise world.  In a enterprise application development, there may be requirement to centralize these configuration parameters in database to better serve, manage and control them. Cinchoo framework opens the possibility of extending the configuration source to various medium. A SQL Server database is one of the mediums to store the application configurations.

This section handler handles the reading and writing of configuration values from Microsoft SqlServer database, a RDBMS from Microsoft designed for enterprise environment. A common widely used database in desktop environment.

This section handler allows multiple applications to store and consume centrally located configuration values.

Part 1 of this series explains about how to use this section handler out of the box without any customization. It meets most of your scenarios to consume the configuration values from SQLServer.

Rarely you have underlying table with different schema or have to consume only part of the table values with custom filter, standard configuration handler may not accommodate it. In this case, you will have to do some customization on top of this framework to achieve the expected results.

A real world scenario will be, you wanted to maintain different set of configuration values for each machine / environment. This can be done with the below steps.

Step 1. Define a table

For a configuration table defined as below,

CREATE TABLE TEST_CONFIG
(
 [KEY] VARCHAR (50) NOT NULL,
 VALUE VARCHAR (100),
 MACHINE VARCHAR (100) NOT NULL,
 PRIMARY KEY ([KEY], MACHINE)
)

The above table structured to hold configuration values for each machine separately.

Step 2. Create Custom SQL generator class

This class is used to override the default SQLs used by the SQLConfiguration section handler for SELECT, INSERT or UPDATE the configuration values to the underlying table. This class must be derived from IChoDbGenericSqlGenerator interface.

public class ChoCustomSqlGenerator : IChoDbGenericSqlGenerator
{
 public void Override(System.Data.IDbCommand selectCmd, System.Data.IDbCommand insertCmd, System.Data.IDbCommand updateCmd)
 {
 string machineName = Environment.MachineName;
 string selectSql = selectCmd.CommandText;
 string insertSql = insertCmd.CommandText;
 string updateSql = updateCmd.CommandText;

 selectSql = "{0} WHERE MACHINE = '{1}'".FormatString(selectSql, machineName);
 insertSql = "{0}, '{1}')".FormatString(insertSql.Substring(0, insertSql.Length - 1), machineName).Replace(") VALUES (", ", MACHINE) VALUES (");
 updateSql = "{0} AND MACHINE = '{1}'".FormatString(updateSql, machineName);

 selectCmd.CommandText = selectSql;
 insertCmd.CommandText = insertSql;
 updateCmd.CommandText = updateSql;
 }
}

Override the interface as above. In above, in the Override method, it rewrite the sqls for SELECT, INSERT or UPDATE operations to include the machine part of the queries.

Step 3. Define new attribute class

Define a new attribute class  (ChoCustomSqlServerConfigurationSectionAttribute) as below to put together all the default values. This attribute class must be derived from ChoDbGenericKeyValueConfigurationSectionAttribute. Exposed number of constructor overloads to different purpose as below. Most important thing to note here is the third constructor overload, where it shows how to inject the ChoCustomSqlGenerator class to it. This completes the definition of new section sqlserver custom section handler to use according to your requirement.

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public class ChoCustomSqlServerConfigurationSectionAttribute : ChoDbGenericKeyValueConfigurationSectionAttribute
{
 public ChoCustomSqlServerConfigurationSectionAttribute(string configElementPath, string serverName, string databaseName, string tableName)
 : this(configElementPath, @"Server={0};Database={1};Trusted_Connection=True;".FormatString(serverName, databaseName), tableName)
 {
 }
 public ChoCustomSqlServerConfigurationSectionAttribute(string configElementPath, string serverName, string databaseName, string userName, string password, string tableName)
 : this(configElementPath, @"Server={0};Database={1};User Id={2};Password={3};".FormatString(serverName, databaseName, userName, password), tableName)
 {
 }
 public ChoCustomSqlServerConfigurationSectionAttribute(string configElementPath, string connectionStringOrName, string tableName)
 : base(configElementPath, @"CONNECTION_STRING='{0}';TABLE_NAME={1};PROVIDER_NAMESPACE=System.Data.SqlClient;SQL_GENERATOR_TYPE='{2}'".FormatString(connectionStringOrName, tableName,
 typeof(ChoCustomSqlGenerator).AssemblyQualifiedName))
 {
 }
}

Step 4. Define your setting class

Now we are ready to use this new section handler and consume the values from SQLServer. In below, let’s define a AppSetting class and decorated with ChoCustomSqlServerConfigurationSectionAttribute. Add few data members to it.

 [ChoCustomSqlServerConfigurationSection("appSettings", @"Data Source=(localdb)\v11.0;Initial Catalog=TestDb;Integrated Security=True", "APP_SETTINGS")]
 public class AppSettings : ChoConfigurableObject
 {
 [ChoPropertyInfo("name")]
 public string Name;

 [ChoPropertyInfo("address", DefaultValue = "100, Madison Avenue, New York, NY 10010")]
 public string Address;

 protected override void OnAfterConfigurationObjectLoaded()
 {
 Console.WriteLine(ToString());
 }
 }

That’s all, the above settings class is ready to used.

Step 5. Consume configuration values

Let’s create a sample application, define an object of AppSettings and access its members to consume the values from SQLServer. See below a sample code

class Program
{
 static void Main(string[] args)
 {
 AppSettings x = new AppSettings();
 Console.WriteLine(x.ToString());

 Console.ReadLine();

 x.Name = "xxx";
 Console.ReadLine();

 }
}

Finally, this article paved a way to consume values from SQLServer table with custom schema. Sample code is attached, download and try it.

 

 

 

Cinchoo – Using SQLServer database as configuration source

Cinchoo is an application framework for .NET. One of the main functionality it provides to users is application configuration management. Application configuration is information that an application reads and/or writes at run-time from the source.

Please visit jump start article [Cinchoo – Simplified Configuration Manager] for more information about Cinchoo configuration manager.

In this section, I’m going to detail you about using SQLServer database as configuration source for your applications. More commonly all the .NET application configuration are kept in files as XML format. It has the limitation, such as maintaining them for each application separately, potential disk corruption by many applications due to access etc. This may not fit in enterprise world.  In a enterprise application development, there may be requirement to centralize these configuration parameters in database to better serve, manage and control them. Cinchoo framework opens the possibility of extending the configuration source to various medium. A SQL Server database is one of the mediums to store the application configurations.

This section handler handles the reading and writing of configuration values from Microsoft SqlServer database, a RDBMS from Microsoft designed for enterprise environment. A common widely used database in desktop environment.

This section handler allows multiple applications to store and consume centrally located configuration values.

First and foremost, you must create a configuration table in the targeted database as per the below schema.

Listing 1 Configuration table

CREATE TABLE APP_SETTINGS
(
    [KEY] VARCHAR (50) NOT NULL,
    VALUE VARCHAR (100),
    PRIMARY KEY ([KEY])
)

The table allows to keep key-value pairs for each configuration members.

The below example illustrates how to define and use this section to consume the configuration values. Declare ChoSqlServerConfigurationSectionAttribute to the class to use this section handler.

Listing 2 Defining Configuration Object

[ChoSqlServerConfigurationSection("appSettings", 
@"Server=SNYC12345400\XYZKND01;Database=TestDb;Trusted_Connection=True;", "APP_SETTINGS")]
public class AppSettings : ChoConfigurableObject
{
    [ChoPropertyInfo("name")]
    public string Name;

    [ChoPropertyInfo("address", DefaultValue = "100, Madison Avenue, New York, NY 10010")]
    public string Address;
}

The code above illustrates how the sqlserver configuration section is specified toconfiguration object. In here, we specified configSectionName, database connection string and table name. TableName is optional. If not specified, framework will try to look for tablename in the name of configuration section object name (AppSettings).

Once you instantiate an object, you are ready to consume the configuration values. The file below shows the layout of the configuration file produced when using this section handler.

Listing 3 HelloWorld.xml

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="appSettings" type="Cinchoo.Core.Configuration.ChoDictionarySectionHandler, 
    Cinchoo.Core" />
  </configSections>
  <appSettings cinchoo:configObjectAdapterType=
    "Cinchoo.Core.Configuration.ChoDbGenericKeyValueConfigStorage, Cinchoo.Core" 
    xmlns:cinchoo="http://schemas.cinchoo.com/cinchoo/01/framework">
    <cinchoo:configObjectAdapterParams 
    xmlns:cinchoo="http://schemas.cinchoo.com/cinchoo/01/framework">
    <![CDATA[CONNECTION_STRING='Server=WNPCTDVZKN01\MSZKND01;Database=School;
    Trusted_Connection=True;';TABLE_NAME=APP_SETTINGS;PROVIDER_NAMESPACE=System.Data.SqlClient]]>
    </cinchoo:configObjectAdapterParams>
  </appSettings>
</configuration>

Number of ChoSqlServerConfigurationSectionAttribute overloads available to meet different requirements. Most of them are self explanatory. One important overload mentioned below now accepts .NET ConnectionString name as parameter.

Listing 4 ChoSqlServerConfigurationSectionAttribute Overload

public ChoSqlServerConfigurationSectionAttribute
    (string configElementPath, string connectionStringOrName, string tableName);

For example, if your application is already using database using .NET ConnectionString, you might see the below entries in the application configuration file.

Listing 5 App.Config file

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
    </configSections>
    <connectionStrings>
        <add name="TESTDB"
            connectionString="Server=SNYC12345400\XYZKND01;Database=TestDb;
        Trusted_Connection=True;" providerName ="System.Data.SqlClient"/>
    </connectionStrings>
</configuration>

This configuration section leverages this feature by accepting .NET ConnectionStringname via parameter to eliminate the duplication of maintaining database connectionstring in multiple places.

The code below illustrates how to use the above connection string name in configuration object.

Listing 6 Configuration Object using ConnectionStringName

[ChoSqlServerConfigurationSection("appSettings", @"TESTDB", "APP_SETTINGS")]
public class AppSettings : ChoConfigurableObject
{
    [ChoPropertyInfo("name")]
    public string Name;

    [ChoPropertyInfo("address", DefaultValue = "100, Madison Avenue, New York, NY 10010")]
    public string Address;
}

Cinchoo framework automatically discovers the connection string from system ConnectionStrings section seamlessly and uses them for consuming configuration values.

Cinchoo – Configuration framework, part 26

Using ChoFireBirdADODictionaryConfigStorage

UPDATE:

This article is outdated. Please visit the below codeproject article for more updated information on this storage plug-ins

Cinchoo – Using FireBird database as configuration source

Using FireBird database as configuration store using Cinchoo framework made easy with this storage plug-in. Using ChoFireBirdADODictionaryConfigStorage, you can read and store application configuration information easily. It is based on ChoDictionaryAdapterConfigurationSection pattern and uses ADO.NET as the database access medium. You can take this one as an example and implement various plug-ins targeting various other databases. Here is how you can use this storage

  • Download and install FireBird Db from here.
  • Create a table using the below Sql. I designed this table in such a way you can use them for multiple applications. Thats why I set the ‘AppName’ as primary key.
CREATE TABLE application_settings
(
 Path varchar(255) DEFAULT NULL,
 OS varchar(50) DEFAULT NULL,
 SingleInstanceApp int DEFAULT NULL,
 LastUpdateTimeStamp timestamp NOT NULL,
 AppName varchar(255) NOT NULL,
 PRIMARY KEY (AppName)
);
  • Create a VS project and add reference to ChoFireBirdADODictionaryConfigStorage.dll
  • Define the configuration section object decorated with ChoDictionaryAdapterConfigurationSectionAttribute as below.
[ChoDictionaryAdapterConfigurationSection("fireBirdDictionarySectionHandlerTest/applicationSettings",
    typeof(ChoFireBirdADODictionaryConfigObjectAdapter),
    "CONNECTION_STRING='User=SYSDBA;Password=masterkey;Database=C:\Users\raj\AppData\Local\Temp\Sample.fdb;DataSource=localhost';
    TABLE_NAME=APPLICATION_SETTINGS;LAST_UPDATE_DATETIME_COLUMN_NAME=LastUpdateTimeStamp;KEY_COLUMN_NAME=AppName")]
public class ApplicationSettings : ChoConfigurableObject
{
    [ChoPropertyInfo("path", DefaultValue = "C:\")]
    public string Path;

    [ChoPropertyInfo("OS", DefaultValue = "Windows")]
    public string OS;

    [ChoPropertyInfo("singleInstanceApp", DefaultValue = false)]
    public bool SingleInstanceApp;
}

2. Now instantiate and use it as below

static void Main(string[] args)
{
    ApplicationSettings applicationSettings = new ApplicationSettings();

    ChoConsole.Pause();

    applicationSettings.OS = "Microsoft";

    ChoConsole.Pause();
}

The configuration section will be generated automatically for the first time in [appExeName].xml as below

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <sectionGroup name="fireBirdDictionarySectionHandlerTest">
      <section name="applicationSettings" type="Cinchoo.Core.Configuration.ChoDictionarySectionHandler, Cinchoo.Core, Version=1.0.1.1, Culture=neutral, PublicKeyToken=b7dacd80ff3e33de" />
    </sectionGroup>
  </configSections>
  <fireBirdDictionarySectionHandlerTest>
    <applicationSettings cinchoo:configObjectAdapterType="Cinchoo.Core.Configuration.ChoFireBirdADODictionaryConfigObjectAdapter, ChoFireBirdADODictionarySectionHandler, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" xmlns:cinchoo="http://schemas.cinchoo.com/cinchoo/01/framework">
      <cinchoo:configObjectAdapterParams xmlns:cinchoo="http://schemas.cinchoo.com/cinchoo/01/framework"><![CDATA[CONNECTION_STRING='User=SYSDBA;Password=masterkey;Database=C:\Users\raj\AppData\Local\Temp\Sample.fdb;DataSource=localhost';
        TABLE_NAME=APPLICATION_SETTINGS;LAST_UPDATE_DATETIME_COLUMN_NAME=LastUpdateTimeStamp;KEY_COLUMN_NAME=AppName]]></cinchoo:configObjectAdapterParams>
    </applicationSettings>
  </fireBirdDictionarySectionHandlerTest>
</configuration>

Cinchoo – Configuration framework, part 25

Using ChoMySqlADODictionaryConfigStorage

UPDATE:

This article is outdated. Please visit the below codeproject article for more updated information on this storage plug-ins

Cinchoo – Using MySql database as configuration source

Using MySql database as configuration store using Cinchoo framework made easy with this storage plug-in. Using ChoMySqlADODictionaryConfigStorage, you can read and store application configuration information easily. It is based on ChoDictionaryAdapterConfigurationSection pattern and uses ADO.NET as the database access medium. You can take this one as an example and implement various plug-ins targeting various other databases. Here is how you can use this storage

  • Download and install MySql from here.
  • Create a table using the below Sql. I designed this table in such a way you can use them for multiple applications. Thats why I set the ‘AppName’ as primary key.

CREATE TABLE `application_settings` (
 `Path` varchar(255) DEFAULT NULL,
 `OS` varchar(50) DEFAULT NULL,
 `SingleInstanceApp` bit(1) DEFAULT NULL,
 `LastUpdateTimeStamp` datetime NOT NULL,
 `AppName` varchar(255) NOT NULL,
 PRIMARY KEY (`AppName`)
)

  • Create a VS project and add reference to ChoMySqlADODictionaryConfigStorage.dll
  • Define the configuration section object decorated with ChoDictionaryAdapterConfigurationSectionAttribute as below.
[ChoDictionaryAdapterConfigurationSection("mySqlDictionarySectionHandlerTest/applicationSettings",
    typeof(ChoMySqlADODictionaryConfigObjectAdapter),
    @"CONNECTION_STRING='server=localhost;User Id=root;password=admin;Persist Security Info=True;database=test';
    TABLE_NAME=APPLICATION_SETTINGS;LAST_UPDATE_DATETIME_COLUMN_NAME=LastUpdateTimeStamp;KEY_COLUMN_NAME=AppName")]
public class ApplicationSettings : ChoConfigurableObject
{
    [ChoPropertyInfo("path", DefaultValue = @"C:\")]
    public string Path;

    [ChoPropertyInfo("OS", DefaultValue = "Windows")]
    public string OS;

    [ChoPropertyInfo("singleInstanceApp", DefaultValue = false)]
    public bool SingleInstanceApp;
}

2. Now instantiate and use it as below

static void Main(string[] args)
{
    ApplicationSettings applicationSettings = new ApplicationSettings();

    ChoConsole.Pause();

    applicationSettings.OS = "Microsoft";

    ChoConsole.Pause();
}

The configuration section will be generated automatically for the first time in [appExeName].xml as below

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <sectionGroup name="mySqlDictionarySectionHandlerTest">
      <section name="applicationSettings" type="Cinchoo.Core.Configuration.ChoDictionarySectionHandler, Cinchoo.Core, Version=1.0.1.1, Culture=neutral, PublicKeyToken=b7dacd80ff3e33de" />
    </sectionGroup>
  </configSections>
  <mySqlDictionarySectionHandlerTest>
    <applicationSettings cinchoo:configObjectAdapterType="Cinchoo.Core.Configuration.ChoMySqlADODictionaryConfigObjectAdapter, ChoMySqlADODictionaryConfigStorage, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" xmlns:cinchoo="http://schemas.cinchoo.com/cinchoo/01/framework">
      <cinchoo:configObjectAdapterParams xmlns:cinchoo="http://schemas.cinchoo.com/cinchoo/01/framework"><![CDATA[CONNECTION_STRING='server=localhost;User Id=root;password=admin;Persist Security Info=True;database=test';
        TABLE_NAME=APPLICATION_SETTINGS;LAST_UPDATE_DATETIME_COLUMN_NAME=LastUpdateTimeStamp;KEY_COLUMN_NAME=AppName]]></cinchoo:configObjectAdapterParams>
    </applicationSettings>
  </mySqlDictionarySectionHandlerTest>
</configuration>

Cinchoo – Configuration framework, part 19

Using ChoFireBirdConfigStorage

UPDATE:

This article is outdated. Please visit the below codeproject article for more updated information on this storage plug-ins

Cinchoo – Using FireBird database as configuration source

 

In this section, I’ll go over the details of using ChoFireBirdConfigStorage in your application. It provides name/value-pair configuration information from FireBird Database.  ChoFireBirdConfigurationSectionAttribute is the corresponding attribute used to decorate the configuration object class.

1. Define the configuration section object decorated with ChoFireBirdConfigurationSectionAttribute as below. You must provide ConnectionString and TableName where the configuration data stored. The table will be created if not exists. The table will have two columns (CONFIG_DATA varchar(250), LAST_UPDATTED_TIME TimeStamp). ConnectionString and TableName can be overridden through configuration file.

[ChoFireBirdConfigurationSection("sample", @"User=SYSDBA;Password=masterkey;Database=C:\Sample.fdb;DataSource=localhost; Port=3050;Dialect=3; Charset=NONE;",
    "APP_SETTINGS")]
public class SampleConfigSection : ChoConfigurableObject
{
    #region Instance Data Members (Public)

    [ChoPropertyInfo("name", DefaultValue = "Mark")]
    public string Name;

    [ChoPropertyInfo("message", DefaultValue = "Hello World!")]
    public string Message;

    #endregion

    [ChoAfterConfigurationObjectLoadedHandler]
    void OnAfterConfigurationObjectLoaded(object sender, ChoConfigurationObjectEventArgs e)
    {
        Console.WriteLine(sender.ToString());
    }
}

2. Now instantiate and use it as below

class Program
{
	static void Main(string[] args)
	{
		SampleConfigSection sampleConfigSection = new SampleConfigSection();
		Console.WriteLine(sampleConfigSection.ToString());

		//Shutdown the framework to stop the background services...otherwise the application will not terminate
		ChoFramework.Shutdown();
	}
}

The configuration section will be generated automatically for the first time in HelloWorld.exe.xml as below

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="sample" type="Cinchoo.Core.Configuration.ChoNameValueSectionHandler, Cinchoo.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b7dacd80ff3e33de" />
  </configSections>
  <sample cinchoo:connectionString="User=SYSDBA;Password=masterkey;Database=C:\Sample.fdb;DataSource=localhost; Port=3050;Dialect=3; Charset=NONE;" cinchoo:tableName="APP_SETTINGS" cinchoo:configDataColumnSize="250" xmlns:cinchoo="http://schemas.cinchoo.com/cinchoo/01/framework" />
</configuration>
The corresponding meta-data looks as below
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <sample bindingMode="TwoWay" defaultable="true" silent="true">
    <configStorage>Cinchoo.Core.Configuration.ChoFireBirdConfigStorage, Cinchoo.Core.Configuration.Storage.FireBirdConfigStorage, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null</configStorage>
    <logInfo condition="true" directory="Settings" fileName="Cinchoo.Core.Configuration.ChoFireBirdClientSectionHandler.Test.SampleConfigSection.log" />
  </sample>
</configuration>

Cinchoo – Configuration framework, part 18

Using ChoSqlServerConfigStorage

UPDATE:

This article is outdated. Please visit the below codeproject article for more updated information on this storage plug-ins

Cinchoo – Using SQLServer database as configuration source

 

 

In this section, I’ll go over the details of using ChoSqlServerConfigStorage in your application. It provides name/value-pair configuration information from SqlServer Database.  ChoSqlServerConfigurationSectionAttribute is the corresponding attribute used to decorate the configuration object class.

1. Define the configuration section object decorated with ChoSqlServerConfigurationSectionAttribute as below. You must provide ConnectionString and TableName where the configuration data stored. The table will be created if not exists. The table will have two columns (CONFIG_DATA varchar(250), LAST_UPDATTED_TIME Timestamp). ConnectionString and TableName can be overridden through configuration file.

[ChoSqlServerConfigurationSection("sample", @"Data Source=shreeya-pc\SQLExpress;Initial Catalog=Cinchoo;Integrated Security=True", "APP_SETTINGS")]
public class SampleConfigSection : ChoConfigurableObject
{
    #region Instance Data Members (Public)

    [ChoPropertyInfo("name", DefaultValue = "Mark")]
    public string Name;

    [ChoPropertyInfo("message", DefaultValue = "Hello World!")]
    public string Message;

    #endregion

    [ChoAfterConfigurationObjectLoadedHandler]
    void OnAfterConfigurationObjectLoaded(object sender, ChoConfigurationObjectEventArgs e)
    {
        Console.WriteLine(sender.ToString());
    }
}

2. Now instantiate and use it as below

class Program
{
	static void Main(string[] args)
	{
		SampleConfigSection sampleConfigSection = new SampleConfigSection();
		Console.WriteLine(sampleConfigSection.ToString());

		//Shutdown the framework to stop the background services...otherwise the application will not terminate
		ChoFramework.Shutdown();
	}
}

The configuration section will be generated automatically for the first time in HelloWorld.exe.xml as below

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <sample cinchoo:connectionString="Data Source=your-pc\SQLExpress;Initial Catalog=Cinchoo;Integrated Security=True" cinchoo:tableName="APP_SETTINGS" cinchoo:configDataColumnSize="250" xmlns:cinchoo="http://schemas.cinchoo.com/cinchoo/01/framework" />
  <configSections>
    <section name="sample" type="Cinchoo.Core.Configuration.ChoNameValueSectionHandler, Cinchoo.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b7dacd80ff3e33de" />
  </configSections>
</configuration>
The corresponding meta-data looks as below
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <sample bindingMode="TwoWay" defaultable="true" silent="true">
    <configStorage>Cinchoo.Core.Configuration.ChoSqlServerConfigStorage, Cinchoo.Core.Configuration.Storage.ChoSqlServerNameValueConfigStorage, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null</configStorage>
    <logInfo condition="true" directory="Settings" fileName="ChoSqlServerConfigStorageDemo.SampleConfigSection.log" />
  </sample>
</configuration>