BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Configuration
.NET 2.0+

Using Custom Classes with Application Settings

Application settings can be created using a project's property windows, with those values being transferred into configuration files and classes that simplify their use. The settings data can be of many different types, including custom classes.

Creating a TypeConverter

Before we can use the Room type in the settings file we need to create the RoomConverter class. This must be derived from TypeConverter so start by creating the class declaration:

public class RoomConverter : TypeConverter
{
}

To create the RoomConverter we need to override three methods from the TypeConverter class. The first of these is the CanConvert method. This simply indicates whether a specific type may be converted into our desired Room type. We know that the configuration values will always be strings so the method returns true for a source type of string and false for any other type. The code for the method is as follows:

public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
    return sourceType == typeof(string);
}

The second method to override is ConvertFrom. This converts a value to a Room object. Again, we only want to work with strings so we begin by checking that the value, held in the value parameter, is indeed a string. If it isn't we let the base class handle the process.

For strings, we will assume that rooms are held as a string containing the room number followed by a comma and the room location. For example, "1,Reception". We simply extract the two values from the string, apply them to the properties of a new Room instance and return the constructed object.

The code for the method is therefore:

public override object ConvertFrom(
    ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
    if (value is string)
    {
        string[] parts = ((string)value).Split(new char[] { ',' });
        Room room = new Room();
        room.RoomNumber = Convert.ToInt32(parts[0]);
        room.Location = parts.Length > 1 ? parts[1] : null;
        return room;
    }
    return base.ConvertFrom(context, culture, value);
}

The third method that must be overridden performs the reverse of the second, converting an object of the Room class to a string that can be stored as a configuration setting. In the ConvertTo method we again check that we are converting between our custom class and a string by checking the destinationType parameter. If the destination type is correct, we use the string.Format method to create the string containing the comma-separated room number and location.

Add the following method and compile the code. This build is required before the types can be used in the application settings grid.

public override object ConvertTo(
    ITypeDescriptorContext context, System.Globalization.CultureInfo culture,
    object value, Type destinationType)
{
    if (destinationType == typeof(string))
    {
        Room room = value as Room;
        return string.Format("{0},{1}", room.RoomNumber, room.Location);
    }
    return base.ConvertTo(context, culture, value, destinationType);
}

Adding Custom Settings Using the Application Settings Grid

When you wish to create application settings based upon custom classes using the application settings grid, the process is almost the same as for any other type. First, open the project's properties and select the Settings tab. If you are told that there is no settings file, click to create one so that the grid is visible.

We'll start by adding a setting containing Employee data. Enter the name, "DefaultEmployee" in the Name column of the grid. Next, click the drop-down arrow next to the Type cell. The custom class will not be visible in the list so select the "Browse..." option. This shows a dialog box containing all of the data types that are currently available for use as application settings. The custom class is not yet in the list so we can enter it using the "Selected type" textbox. Simply type the fully-qualified name, "SettingsTest.Employee" and click the OK button.

We can now provide the value for the configuration setting by adding it to the Value column. This class uses XML serialization for settings so we need to add valid XML that can be deserialised as an Employee object into the Value cell. Add the following value to represent a developer named "John". When you leave the cell the XML will be validated. If correct, the <xml> tag and a default namespace will be added. If incorrect, an error will be displayed.

<Employee>
    <Name>John</Name>
    <Position>Developer</Position>
</Employee>

We can repeat the same process for the Room class setting. This time, add a setting with the name, "DefaultRoom", and the type, "SettingsTest.Room". The value must be in the format that the RoomConverter class understands. To create a Room setting with a room number of 1 and the name, "Reception", set the value to "1,Reception".

Once the data has been entered correctly, the grid should be similar to that shown below.

Custom Application Settings

When you save the settings you can view them in the app.config file. The userSettings section should contain the two new values:

<userSettings>
    <SettingsTest.Properties.Settings>
        <setting name="DefaultEmployee" serializeAs="Xml">
            <value>
                <Employee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
                    <Name>John</Name>
                    <Position>Developer</Position>
                </Employee>
            </value>
        </setting>
        <setting name="DefaultRoom" serializeAs="String">
            <value>1,Reception</value>
        </setting>
    </SettingsTest.Properties.Settings>
</userSettings>
21 August 2011