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
        ChoConfigurationManager.ApplicationConfiguration = 
        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 – 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.

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

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.

This is the second part of [Cinchoo – Using SQLServer database as configuration source] article. So far we learned about using SQL Server database as configuration source in a polling approach. Cinchoo configuration manager polls for the change in the underlying table for every elapsed interval (configurable). This approach is ideal in a situation where SQL Server query notification service is not available or is turned off by administrators.

In this section, I’m going to detail you about using SQL Server 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.

In this approach, we are going to leverage SQL Server query notification service for change notification. It is available in SQL Server 2005+/ADO.NET 2.0.

For more details on this configuration source, please visit the code project article below

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

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.

For more details on this configuration source, please visit the code project article below

Cinchoo – Using SQLServer database as configuration source

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>