Category Archives: Configuration

Cinchoo – Running in hosted / UnitTest environment

Cinchoo discovers, opens and saves its own settings automatically in application folders. In hosted environments like IIS / MS-Test / NUnit etc, the base folder is protected from saving such changes. Cinchoo abnormally terminates the application with failure.

To overcome it, you must initialize Cinchoo configuration manger to the fully accessible folder at the application startup.

ChoConfigurationManager.OpenExeConfiguration(@”C:\Temp\test1.config”);

 

Cinchoo – Using Array/Collections in Configuration Object

How to use Array or Collections in configuration object

Download sample source files

Cinchoo – Application configuration is one of the feature Cinchoo framework provides for the developer.  Application configuration is the information that application reads/writes at run time from the source. .NET already provides extensive support through several predefined configuration section handlers for the developers. But require some pluming development work on top of them to complete the exercise. Cinchoo framework simply them with less code and read/write configuration values to the underlying data sources seamlessly.

In this section, I’m going to detailed out on using Array or Collection objects in your configuration object. ChoXmlSerializerConfigurationSection is suitable for this type of needs. It is a section used to consume configuration object containing user defined objects. In here, we going to explore a way to consume array of objects from configuration source.

Listing 1.1 Configuration Object

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

    [ChoPropertyInfo("employees")]
    [XmlArray("employees")]
    public ObservableCollectionEx<Employee> Employees = new ObservableCollectionEx<Employee>();

    protected override bool OnBeforeConfigurationObjectLoaded()
    {
        if (Employees != null)
            Employees.Clear();

        return base.OnBeforeConfigurationObjectLoaded();
    }

    protected override void OnAfterConfigurationObjectLoaded()
    {
        if (Employees != null)
            Employees.WireCollectionChangedEvent();

        Console.WriteLine(ToString());
        base.OnAfterConfigurationObjectLoaded();
    }
}

The code above illustrates about defining configuration object. It contains two members, name and Employees. name is a simple string configuration member. Cinchoo does the job of consuming it from source out of the box. The next member, Employees, is the collection of Employee objects. In order to consume from the source, it can be defined as List<T>, Array or ObservableCollection. But the problem here is the receiving change notification when collection changed or when one of its item gets changed. That’s why I’ve created a modified version of ObservableCollection class, to meet the purpose of two way binding. Take a look at the attached sample for its implementation. Besides that you must decorate this member with XmlArrayAttribute.

Next you need to take care few house keeping tasks of managing this collection member. Override OnBeforeConfigurationObjectLoaded method, to clear the collection before the configuration object is loaded from the source. On to next, override OnAfterConfigurationObjectLoaded method to wire the collection changed event to property changed event. I know it is kind of confusing. Read the sample to get clarity on it.

Now let’s define and consume the object as shown below

Listing 1.2 Main Method

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

    int random = Math.Abs(ChoRandom.NextRandom());
    Employee e1 = new Employee() { Id = random, Name = "Name{0}".FormatString(random) };
    appSettings.Employees.Add(e1);

    ChoConsole.PauseLine();

    foreach (Employee o in appSettings.Employees)
        o.Name = o.Name + "1";

    ChoConsole.PauseLine();
}

Build and run the sample, the configuration file looks as expected below

Listing 1.3 Configuration Output

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="appSettings" type="Cinchoo.Core.Configuration.ChoXmlSerializerSectionHandler, Cinchoo.Core" />
  </configSections>
  <appSettings>
    <Name>Raj</Name>
    <employees>
      <Employee Id="1416154546" Name="Name141615454611" />
      <Employee Id="1121887979" Name="Name11218879791" />
    </employees>
  </appSettings>
</configuration>

That’s all, the object is ready to be used to consume collections. Download and try for yourself. Thanks.

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.

Cinchoo – Controlling configuration outputs

In this section I’ll be depicting approach to control the Cinchoo configuration manager output files. There are situation you may want to enable / disable framework’s configuration files, meta data configuration files, application configuration files etc. Here is how you can do via executable configuration file (app.config/web.config) as below

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <configSections>
        <section name="appFrxSettings" type="Cinchoo.Core.ChoAppFrxSettings, Cinchoo.Core" />
    </configSections>
    <appFrxSettings appEnvironment="" sharedEnvironmentConfigFilePath=""
        appFrxFilePath="" doNotShowEnvSelectionWnd="false" applicationHostType=""
        disableFrxConfig="false" disableAppConfig="false" disableMetaDataConfig="false" />
</configuration>

Define appFrxSettings configuration section as above in your main executable configuration file (app.config/web.config). Cinchoo framework will create this section with default values if not found at the first run.  In here, the attributes to look into are

  • disableFrxConfig – true, will stop creating framework configuration files. Default value is false.
  • disableMetaDataConfig – true, will stop creating framework meta data configuration files (under config/meta folder). Default value is false.
  • disableAppConfig – true, to stop creating application configuration files. Uncommon to turn this option off. Default value is false.

There is one another way you can control these parameters via your application code, programmatically. Subscribe to Application object’s AfterAppFrxSettingsLoaded event and set these values. Example below shows the code snippet to accomplish it

ChoApplication.AfterAppFrxSettingsLoaded += ((s, e) =>
    {
        if (e.Value is ChoAppFrxSettings)
        {
            ChoAppFrxSettings z = e.Value as ChoAppFrxSettings;
            z.DisableAppConfig = false;
            z.DisableFrxConfig = true;
            z.DisableMetaDataConfig = true;
        }
    }
};

Make sure you subscribe to this event at the start of the application in order to override these parameters. That all, give it a try.

Cinchoo – Support of UDT as Configuration values

Download Sample.zip – 4.4 KB

1. Introduction

Cinchoo is the application framework for .NET. One of the main functionalities it provides to the users is the application configuration management. Application configuration is the information that the 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 run through with sample in defining and using User Defined Types (UDT) as configuration values. In general, all the configuration values are simple and intrinsic. Sometimes, we may want to manage read and save complex UDT data objects data.

2. Requirement

This configuration library is written in C# for the .NET 4.0 Framework. It is part of Cinchoo framework, which is a great library with lot of features like Configuration Management, common ApplicationHost, Shell features, etc.

3. “Hello World!” Sample

Let’s begin by looking into a simple example of an application consuming two configuration values name and address. name is required configuration value and address is a another required configuration value containing structured XML data as defined below.

Listing 3.1 Sample configuration file

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="appSettings" type="Cinchoo.Core.Configuration.ChoNameValueSectionHandler,
       Cinchoo.Core, Version=1.0.1.1, Culture=neutral, PublicKeyToken=b7dacd80ff3e33de" />
  </configSections>
  <appSettings>
    <add key="name" value="Mark" />
    <add key="address">
        <value>
            <address>
                <street>10 River Road</street>
                <city>New York</city>
                <state>NY</state>
            </address>
        </value>
  </appSettings>
</configuration>
  • Download the 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 and Cinchoo.Core.Configuration namespace
  • Copy and paste the below command line object

Listing 3.2 Defining Configuration Object

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

    [ChoPropertyInfo("Address")]
    public Address Address;

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

The code above illustrates about defining configuration object. First thing defines a configuration (example, AppSettings) class from ChoConfigurableObject, it indicates that this object is a configuration object. And it must be decorated with one of the available configuration section attributes, will be discussed later. In this example, I’ve used ChoNameValueConfigurationSectionAttribute with appSettings as section name to complete the definition. You can use any configuration sections available in Cinchoo framework. It specifies that this configuration section is the NameValueConfigurationSection. With this definition, we turned the above configuration object provides name/value-pair configuration information from a configuration section.

Define configuration value members Name and Address either 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 is the optional configuration member. It is given nameas configuration member name with the DefaultValue as Mark‘. It means that if the configuration value is missing from the source, it will be defaulted to DefaultValue.

Address configuration member is an optional member as well. It was given with addressas configuration name, which will consume the payload in XML format from configuration file. It is of Address user defined type. Cinchoo framework makes it simplified the way of consuming/saving the structured Xml data into user defined type from configuration file. Below is the definition of Address UDT type.

Listing 3.2 Defining Address UDT type

public class Address : ChoEquatableObject<Address>
{
    private string _street;
    public string Street
    {
        get { return _street; }
        set
        {
            if (value != _street)
            {
                _street = value;
                RaisePropertyChanged("Street");
            }
        }
    }

    private string _city;
    public string City
    {
        get { return _city; }
        set
        {
            if (value != _city)
            {
                _city = value;
                RaisePropertyChanged("City");
            }
        }
    }

    private string _state;
    public string State
    {
        get { return _state; }
        set
        {
            if (value != _state)
            {
                _state = value;
                RaisePropertyChanged("State");
            }
        }
    }
}

The code above illustrates about defining Address UDT type. It must be derived from ChoEquatableObject, it indicates that this object will notify its changes to configuration framework. It defines three members (Street, City and State), with get and set accessors. Provides property change notifications via INotifyPropertyChanged pattern, which abstracted inside ChoEquatableObject. Once you have these change notification implemented for all properties, this object is eligible for sending all changes to the framework.

Listing 3.3 Main Method

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

    //Update the address value in xml value

    if (applicationSettings.Address == null)
        applicationSettings.Address = new Address() { Street = "10 River Road", City = "New York", State = "NY" };


    ChoConsole.PauseLine();
}

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

Now compile this program and run. It will create the section in [appExeName].xml (HelloWorld.exe.xml) file under bin/Config folder.

Listing 3.4 HelloWorld.exe.xml

<?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="Mark" />
    <add key="Address">
      <value>
        <Address>
          <State>NY</State>
          <Street>10 River Road</Street>
          <City>New York</City>
        </Address>
      </value>
    </add>
  </appSettings>
</configuration>

Cinchoo framework automatically checks and identifies the payload of each configuration values and consumes them safely.

It is very simple to work with configuration using Cinchoo framework. Try for yourself. Thanks.

Cinchoo – Consuming Xml as configuration value

Download Sample.zip – 4.6 KB

1. Introduction

Cinchoo is the application framework for .NET. One of the main functionality it provides to the users is the application configuration management. Application configuration is the information that 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 run through with sample in consuming xml data as configuration value. In general, all the configuration values are simple and intrinsic. Sometimes we may want to manage read and save xml data.

2. Requirement

This configuration library is written in C# for the .NET 4.0 Framework. It is part of Cinchoo framework, which is a great library with lot of features like Configuration Management, common ApplicationHost, Shell features, etc.

3. “Hello World!” Sample

Let’s begin by looking into a simple example of an application consuming two configuration values name and address. name is required configuration value and address is a another required configuration value containing structured xml data as below

Listing 3.1 Sample configuration file

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="appSettings" type="Cinchoo.Core.Configuration.ChoNameValueSectionHandler,
       Cinchoo.Core, Version=1.0.1.1, Culture=neutral, PublicKeyToken=b7dacd80ff3e33de" />
  </configSections>
  <appSettings>
    <add key="name" value="Mark" />
    <add key="address">
        <value>
            <address>
                <street>10 River Road</street>
                <city>New York</city>
                <state>NY</state>
            </address>
        </value>
  </appSettings>
</configuration>
  • Download the 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 and Cinchoo.Core.Configuration namespace
  • Copy and paste the below command line object

Listing 3.2 Defining Configuration Object

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

    [ChoPropertyInfo("address")]
    public string Address;
}

The code above illustrates about defining configuration object. First thing define a configuration (ex. AppSettings) class from ChoConfigurableObject, it indicates that this object is a configuration object. And it must be decorated with one of the available configuration section attributes, will be discussed later. In this example, I’ve used ChoNameValueConfigurationSectionAttribute with appSettings as section name to complete the definition. You can use any available configuration sections except ChoSingleTagConfigurationSection, which does not support complex configuration values. It specifies that this configuration section is the NameValueConfigurationSection. With this definition, we turned the above configuration object provides name/value-pair configuration information from a configuration section. Define configuration value members Name and Address either 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 is the optional configuration member. It is given nameas configuration member name with the DefaultValue as Mark‘. It means that if the configuration value is missing from the source, it will be defaulted to DefaultValue. Address configuration member is an optional member as well. It was given with addressas name, which will consume the payload in xml format from configuration file. Once you have the configuration object defined as above, it is now ready to use in your application. Here is how you can create and use it.

Listing 3.3 Main Method

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

    //Update the address value in xml value
    appSettings.Address = "<address><street>10 River Road</street><city>New York</city><state>NY</state></address>";

    ChoConsole.PauseLine();
}

We start by creating a new instance of AppSettings object, That’s all. All the heavy lifting of loading configuration values to the object is done by the framework under the hood. Now compile this program and run. It will create the section in [appExeName].xml (HelloWorld.exe.xml) file under bin/Config folder.

Listing 3.4 HelloWorld.exe.xml

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="appSettings" type="Cinchoo.Core.Configuration.ChoNameValueSectionHandler,
       Cinchoo.Core, Version=1.0.1.1, Culture=neutral, PublicKeyToken=b7dacd80ff3e33de" />
  </configSections>
  <appSettings>
    <add key="name" value="Mark" />
    <add key="address">
        <value>
            <address>
                <street>10 River Road</street>
                <city>New York</city>
                <state>NY</state>
            </address>
        </value>
  </appSettings>
</configuration>

Cinchoo framework automatically checks and identifies the payload of each configuration values and consume them safely. It is very simple to work with configuration using Cinchoo framework. Try for yourself. Thanks.

Cinchoo – Open configuration files in AppData folder

By default, Cinchoo framework creates and uses App.exe.Config and other configuration files under the executable folder. In a protected environment, where the ‘program files’ folder is protected and no write access is available, you will need to instruct the framework to use ‘AppData’ folder or any other write accessable folder for all the configuration management. This can be done as below

Step 1. In the Main Method, subscribe to ChoApplication.AfterConfigurationManagerInitialized event

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

Step 2. In that event, invoke one of the ChoConfigurationManager.OpenExeConfiguration() method as below

static void ChoApplication_AfterConfigurationManagerInitialized(object sender, EventArgs e)
{
	ChoConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
}

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.