Category Archives: Configuration

Cinchoo – Configuration Framework, Part 29

Support of Complex Object as configuration value

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 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 feature, using and saving custom user defined object as configuration values. So far Cinchoo framework supports only scalar text values. It limits the configuration object member values from having any complex objects.

In standard .NET framework, it is not supported in straight way. You will have to create custom configuration section and put a plumbing code to parse the values. In Cinchoo framework, it is simplified to handle the complex objects as configuration values.

Here is how you can define configuration members to support custom user defined type

[ChoNameValueConfigurationSection("appSettings")]
public class AppSettings : ChoConfigurableObject
{
	[ChoPropertyInfo("name", DefaultValue = "Tom")]
	public string Name;

	[ChoPropertyInfo("address", DefaultValue="10, River Road, Piscataway, NJ 08880 && New York")]
	public ChoCDATA Address;

	[ChoPropertyInfo("employer", DefaultValue = "<Sample>ABCD Inc.</Sample>")]
	public string Employer;

	[ChoPropertyInfo("department")]
	public Department Department;

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

In the above sample configuration object, Department member is defined as Department type, it is defined as below

[ChoXmlSerializerConverter(typeof(Department))]
public class Department : INotifyPropertyChanged
{
	private int _deptCode;

	[XmlAttribute("deptCode")]
	public int DeptCode
	{
		get { return _deptCode; }
		set
		{
			_deptCode = value;
			RaisePropertyChanged("DeptCode");
		}
	}

	private string _deptName;

	[XmlAttribute("deptName")]
	public string DeptName
	{
		get { return _deptName; }
		set
		{
			_deptName = value;
			RaisePropertyChanged("DeptName");
		}
	}

	public event PropertyChangedEventHandler PropertyChanged;

	protected void RaisePropertyChanged(string propertyName)
	{
		if (propertyName.IsNullOrWhiteSpace()) return;

		PropertyChangedEventHandler propertyChanged = PropertyChanged;
		if (propertyChanged != null)
			propertyChanged(this, new PropertyChangedEventArgs(propertyName));
	}
}

Key things to remember when you define custom object in order to use in configuration object

  • Should be decorated as ChoXmlSerializerConverter which helps to serialize the object to Xml string.
  • Must implement INotifyPropertyChanged in order to notify member changes to Configuration Manager.
  • Decorate appropriate Xml serialization attribute to its members (ie. XmlAttribute, XmlElement etc)

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)
{
	AppSettings appSettings = new AppSettings();

	//Modify the members
	appSettings.Address.Value = "11, Oak Road, Woodbridge, NJ 08827";
	appSettings.Employer = "<Sample1>ZZZ1 Inc.</Sample1>";
	if (appSettings.Department == null)
		appSettings.Department = new Department() { DeptCode = 10, DeptName = "Comp Sc." };
	else
		appSettings.Department.DeptCode = appSettings.Department.DeptCode + 20;

	ChoFramework.Shutdown();
}

If you compile and run this sample, the output of the configuration will be seen as below

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="appSettings" type="Cinchoo.Core.Configuration.ChoNameValueSectionHandler, Cinchoo.Core" />
  </configSections>
  <appSettings>
    <add key="name" value="Tom" />
    <add key="address">
      <value><![CDATA[11, Oak Road, Woodbridge, NJ 08827]]></value>
    </add>
    <add key="employer">
      <value>
        <Sample1>ZZZ1 Inc.</Sample1>
      </value>
    </add>
    <add key="department">
      <value>
        <Department deptCode="11" deptName="Comp Sc." />
      </value>
    </add>
  </appSettings>
</configuration>

That’s it folks, it is as easy as to store and consume custom user defined member in Configuration object.

Advertisements

Cinchoo – Configuration Framework, Part 28

Support of CDATA / Xml as configuration value

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 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 about new feature, using and saving CDATA / Xml  as configuration values. So far Cinchoo supports the configuration object member values as simple text values. It limits the configuration object member values from having any complex text.

In standard .NET framework, it is not supported in straight way. You will have to create custom configuration section and put a plumbing code to parse the values. In Cinchoo, it is simplified to handle CDATA/Xml values.

Here is how you can define configuration members to support CDATA / Xml values

[ChoNameValueConfigurationSection("appSettings")]
public class AppSettings : ChoConfigurableObject
{
	[ChoPropertyInfo("name", DefaultValue = "Tom")]
	public string Name;

	[ChoPropertyInfo("address", DefaultValue="10, River Road, Piscataway, NJ 08880 && New York")]
	public ChoCDATA Address;

	[ChoPropertyInfo("employer", DefaultValue = "<Sample>ABCD Inc.</Sample>")]
	public string Employer;
}

In the above sample configuration object, Address member defined as ChoCDATA type to accommodate CDATA value. Employer member is defined as string type, to hold the xml value. Cinchoo automatically checks the configuration member value for any xml tags present, if it does then the section value will be created as Xml element, otherwise it will be created as Xml attribute.

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)
{
	AppSettings appSettings = new AppSettings();

	//Modify the members
	appSettings.Address = new ChoCDATA("11, Oak Road, Woodbridge, NJ 08827");
	appSettings.Employer = "<Sample1>ZZZ1 Inc.</Sample1>";

	Console.WriteLine(appSettings.ToString());
	ChoFramework.Shutdown();
}

Since Address is CDATA member, any modification must be done by creating new ChoCDATA object with new value and assign to it. And for the Employer member, it is straight forward to modify. Cinchoo framework will take care of it under the hood.

If you compile and run this sample, the output of the configuration will be seen as below

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="appSettings" type="Cinchoo.Core.Configuration.ChoNameValueSectionHandler, Cinchoo.Core" />
  </configSections>
  <appSettings>
    <add key="name" value="Tom" />
    <add key="address">
      <value><![CDATA[11, Oak Road, Woodbridge, NJ 08827]]></value>
    </add>
    <add key="employer">
      <value>
        <Sample1>ZZZ1 Inc.</Sample1>
      </value>
    </add>
  </appSettings>
</configuration>

That’s it folks, it is as easy as to store and consume CDATA / Xml values in Configuration object.

Cinchoo – ConfigurationManager Tips 1

Cinchoo is the application framework for .NET. One of the main functionality it provides to the users is application configuration management. Application configuration is the information that application reads and/or writes at run-time from the source. Please take a look at ‘Cinchoo – Simplified Configuration Manager’ jump start article on using configuration framework in your application.

In this section, I’ll talk about a way to hook up the existing configuration files to your files through application configuration file. And how to set environment specific configuration files to the applications.

For more up to date information about this article, please visit the below CodeProject link

Cinchoo – ConfigurationManager Tips 1

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 27

Using Converters

Download source files (Require .NET 4.0 / Visual Studio 2010)

Cinchoo configuration framework takes care of converting most of the intrinsic type configuration object members from text value like string to int, string to enum etc. In cases where you have custom type members, you will have to use converters to convert the text value to object. Cinchoo support the following types of converters

  1. System.ComponentModel.TypeConverter – For more information about it, visit ‘How to: Implement a TypeConverter
  2. System.Windows.Data.IValueConverter
  3. Cinchoo.Core.IChoValueConverter – It is similar interface to IValueConverter.

TypeConverters can be specified two ways using ChoTypeConverterAttribute 

  1. At each object member level – Will take priority over second option
  2. At the object type level

Lets go over with sample configuration object defined below

[ChoNameValueConfigurationSection("appSettings")]
public class AppSettings : ChoConfigurableObject
{
    [ChoPropertyInfo("name", DefaultValue = "Raj")]
    public string Name;

    [ChoPropertyInfo("address", DefaultValue = "21, Melbloum Lane, Edison NJ 08837")]
    public string Address;

    [ChoPropertyInfo("Color", DefaultValue = "Yellow")]
    public ConsoleColor Color;

    [ChoPropertyInfo("height", DefaultValue = "5.6")]
    public double Height;

    [ChoPropertyInfo("SSN", DefaultValue = "111-00-3333")]
    [ChoTypeConverter(typeof(SSNConverter))]
    public string SSN;

    [ChoPropertyInfo("Location", DefaultValue = "10, 12")]
    public Point Location;

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

In here,

  • Color is of ConsoleColor enum type. As I mentioned earlier, it is implicitly taken care by Cinchoo framework to read/store the value as string.
  • SSN is of string type, expects values in specific format (000-00-0000). It is decorated with member level type converter ‘SSNConverter’
  • Location is of Point type. But Point class bounded to PointConverter as below. No need to specify at the member level.

SSNConverter Implementation

public class SSNConverter : TypeConverter
{
    private static readonly Regex _ssnRegex = new Regex(@"^[0-9][0-9][0-9]\-[0-9][0-9]\-[0-9][0-9][0-9][0-9]$|^[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]$", RegexOptions.Compiled);
    private static readonly Regex _noSSNRegex = new Regex(@"^[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]$", RegexOptions.Compiled);
    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
    {
        return sourceType == typeof(string);
    }
    public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
    {
        if (value != null && value is string)
        {
            string ssnValue = value as string;
            if (_ssnRegex.IsMatch(ssnValue))
                return ssnValue;
            else if (_noSSNRegex.IsMatch(ssnValue))
                return "{0}-{1}-{2}".FormatString(ssnValue.Substring(0, 2), ssnValue.Substring(2, 4), ssnValue.Substring(4, 7));
        }
        throw new ArgumentException("Invalid '{0}' SSN value passed.".FormatString(value));
    }
    public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
    {
        return destinationType == typeof(string);
    }
    public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
    {
        return (string)value;
    }
}

PointConverter Implementation

[ChoTypeConverter(typeof(Point))]
public class PointConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value != null && value is string)
        {
            if (targetType == typeof(Point))
            {
                int x = 0, y = 0;
                string inValue = value as string;
                string[] parts = inValue.SplitNTrim(',');
                if (parts.Length >= 1)
                    x = System.Convert.ToInt32(parts[0]);
                if (parts.Length >= 2)
                    y = System.Convert.ToInt32(parts[1]);
                return new Point(x, y);
            }
        }
        return value;
    }
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value != null && value is Point)
        {
            if (targetType == typeof(string))
            {
                Point inValue = (Point)value;
                return "{0}, {1}".FormatString(inValue.X, inValue.Y);
            }
        }

        return value;
    }
}

You can use any existing TypeConverter / IValueConverter in your application. Try for yourself. Thanks.

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 24

Binding to WinForm controls

Download Source Files (ZIP)

In this section, I’ll talk about binding your configuration object to WinForm controls. WinForm has rich binding infrastructure, Cinchoo framework works closely with WinForms to bind the configuration object to them seamlessly. Lets walk over how you can do this.

For a sample configuration object below

[ChoNameValueConfigurationSection("sample")]
public class SampleConfigSection : ChoConfigurableObject
{
    [ChoPropertyInfo("name", DefaultValue = "Mark")]
    public string Name
    {
        get;
        set;
    }

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

PS: WinForm controls only binds to public Properties only. Please make sure you define them accordingly in your configuration object.

You can bind the above configuration object to your WinForm window in either constructor or window load event handler as below.

private void MainForm_Load(object sender, EventArgs e)
{
    SampleConfigSection settings = new SampleConfigSection();
    textBox1.DataBindings.Add("Text", settings, "Name");
    textBox2.DataBindings.Add("Text", settings, "Message");
}

That’s all. Now the changes made to configuration source will be reflected in the controls as well as the changes made to controls will be persisted automatically to underlying source based on the binding nature. Try for yourself.

Cinchoo – Configuration framework, part 23

Passing Configuration FilePath Programmatically

UPDATED: In this topic, I’m going to show you how to pass configuration object filepath programmatically. Cinchoo framework addresses this feature through IChoConfigurationParametersOverridable interface. When you define a configuration object, implement this interface as below to override the configuration file path.

[ChoNameValueConfigurationSection("applicationSettings")]
public class ApplicationSettings : ChoConfigurableObject
{
    [ChoPropertyInfo("path", DefaultValue = @"C:\")]
    public string Path;

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

    protected override void OverrideMetaDataInfo(ChoBaseConfigurationMetaDataInfo metaDataInfo)
    {
        ChoStandardConfigurationMetaDataInfo info = metaDataInfo as ChoStandardConfigurationMetaDataInfo;
        info.ConfigFilePath = @"C:\Test\ApplicationSettings.xml";
    }
}