Question

So I'm using Settings.settings on a Windows Service that I'm currently working on and it works fine for my needs. The only problem I've had so far is the way that invalid values are handled. As far as I know, if I edit the exe.config file and type in an invalid value in one of the properties, the default value that was captured at design time will be used.

This is all good if you want to keep your service running no matter what, but I need a means to find about it, so that I can notify the user and prevent him from spending hours trying to figure out why the service isn't working as intended even though no errors were reported.

Is there a way to check that all properties have valid values in the exe.config file when using settings? I haven't been able to find any.

Was it helpful?

Solution

You can use SettingsLoaded event. Open Settings.cs file and in the constructor attach SettingsLoaded. Sthm like this:

// This class allows you to handle specific events on the settings class:
//  The SettingChanging event is raised before a setting's value is changed.
//  The PropertyChanged event is raised after a setting's value is changed.
//  The SettingsLoaded event is raised after the setting values are loaded.
//  The SettingsSaving event is raised before the setting values are saved.
internal sealed partial class Settings {

    public Settings() {
        this.SettingsLoaded += OnSettingsLoadedEvent;
    }

    private void OnSettingsLoadedEvent(object sender, SettingsLoadedEventArgs settingsLoadedEventArgs)
    {
        if (SomeNumParam >= 100)
        {
            const string msg = "SomeNumParam is invalid! Value must be between 0 and 100";
            Console.WriteLine(msg);
            throw new ArgumentOutOfRangeException(msg);
        }
    }

}

OTHER TIPS

This is all good if you want to keep your service running no matter what, but I need a means to find about it, so that I can notify the user and prevent him from spending hours trying to figure out why the service isn't working as intended even though no errors were reported.

This seems exactly the opposite of what it should be doing. Having a program run with invalid configuration information doesn't make sense. Typically a Windows Service during load or at some point when it needs to refresh the settings, needs to validate them, if it can't it should be writing to the Event Log and then stop. The event log should write what parameter(s) are incorrect, and it is typically up to the system administrator to monitor event logs in Error condition.

Another option is to use a logging system (for example Log4net) which supports multiple ways to handle logging (to a database, mail, etc).

If you problem is with the default values, I'd recommend creating default values that are not valid.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top