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+

Application Setting Events

Application settings provide a useful means for configuring applications and retaining user settings between program executions. When it is necessary to monitor those settings for changes, four standard events can be subscribed to.

Configuration Settings

Application settings can be configured for a project using a designer in Visual Studio. These settings are automatically added to the configuration file for the compiled assembly, where they can be edited in a live environment using a text editor to control the execution of the program. Configuration information can also be created as user settings, which can be modified at run-time on a per-user basis.

In complex applications user settings may be changed by the user in many different ways. For example, a dialog box of options may be available to allow the user to change their personal preferences directly. Default values for controls may be stored in settings when the controls are used and the size and position of key windows may be recorded so that they appear in the same place when next accessed. If you need to monitor user settings and react when they change, adding code in all of these places can be repetitive. However, this is unnecessary as the classes that control application settings inherit functionality from ApplicationSettingsBase abstract class, which raises events when settings are changed, loaded or saved.

In this article we'll examine the four events that notify of changes to settings. To begin, create a new console application project named, "ConfigurationTest". Add a settings file to the project through its property pages and create a string setting named, "MySetting" with any value you wish.

In the code we'll be using types from the System.ComponentModel, System.Configuration and ConfigurationTest.Properties namespaces, so add the following using directives. NB: If you named the project differently, you will need to modify the final using directive accordingly.

using System.ComponentModel;
using System.Configuration;
using ConfigurationTest.Properties;

Capturing Setting Changes

Possibly the most common events that you will wish to subscribe to in order to monitor application settings are SettingChanging and PropertyChanged. These are raised when your software attempts to change any setting.

SettingChanging is raised immediately before a setting value is updated. The delegate for this event includes an instance of SettingChangingEventArgs to pass details of the setting that is about to be updated. You can check which setting is being changed by reading the SettingName property and see the new value by reading NewValue. If you do not wish to permit the change to go ahead, you can cancel it by setting the Cancel property of the object to true. This stops the setting from being updated and prevents the PropertyChanged event from being raised.

The PropertyChanged event fires after a setting's value has been updated. It provides information through an instance of the PropertyChangedEventArgs class. This lets you see which setting was updated by checking the PropertyName property. The event does not support cancellation.

The code below subscribes to the two events for default settings file, adding methods that show messages before and after any setting change. When the SettingChanging event is captured an option is given to allow cancellation. Try stepping through the program in debug mode to see the results when cancelling and when allowing the change to be made.

static void Main()
{
    Settings.Default.SettingChanging
        += new SettingChangingEventHandler(Default_SettingChanging);
    Settings.Default.PropertyChanged
        += new System.ComponentModel.PropertyChangedEventHandler(Default_PropertyChanged);

    Settings.Default.MySetting = "New Value";
}

static void Default_SettingChanging(
    object sender, System.Configuration.SettingChangingEventArgs e)
{
    Console.WriteLine("Changing {0} to {1}", e.SettingName, e.NewValue);
    Console.WriteLine("OK?");

    ConsoleKeyInfo confirmation = Console.ReadKey();
    if (confirmation.Key != ConsoleKey.Y)
    {
        e.Cancel = true;
    }
    Console.WriteLine();
}

static void Default_PropertyChanged(
    object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
    Console.WriteLine("Changed {0}", e.PropertyName);
}

Detecting Loading and Saving of Settings

The other two events provided by ApplicationSettingsBase allow you to be notified when settings are first retrieved from configuration files and when the in-memory values are saved. The SettingsLoaded event is raised when the values are loaded. This occurs when a program first reads any setting, at which point all values are loaded and cached. The event will not fire again unless the cache is first cleared with the use of the Reset or Reload methods.

The SettingsSaving event is raised when you attempt to save any updated settings. As with the SettingChanging event, you can set the Cancel property of the event arguments to cancel the operation and prevent the updated values from being written to a configuration file.

The following code demonstrates the use of the two events. Try stepping through the code to see exactly when the SettingsLoaded event is raised.

static void Main()
{
    Settings.Default.SettingsLoaded +=
        new SettingsLoadedEventHandler(Default_SettingsLoaded);
    Settings.Default.SettingsSaving +=
        new SettingsSavingEventHandler(Default_SettingsSaving);

    Console.WriteLine("MySetting = {0}", Settings.Default.MySetting);
    Settings.Default.Save();
}

static void Default_SettingsSaving(object sender, CancelEventArgs e)
{
    Console.WriteLine("Saving Settings");
    Console.WriteLine("OK?");

    ConsoleKeyInfo confirmation = Console.ReadKey();
    if (confirmation.Key != ConsoleKey.Y)
    {
        e.Cancel = true;
    }
    Console.WriteLine();
}

static void Default_SettingsLoaded(object sender, SettingsLoadedEventArgs e)
{
    Console.WriteLine("Settings Loaded");
}
20 March 2012