Posted by: Cirilo Meggiolaro | 03/14/2009

Tip of the day #151 – Creating configurable switches to your application

The use of switches for applications to enable or disable a specific feature or service is common. To help you on this task the .NET framework provides a class that reads a key from the application’s config file and exposes its value as a Boolean property.

Under the System.Diagnostics namespace resides the BooleanSwitch class that makes the work of use switches pretty straightforward.

How to…

Let’s start defining a set of switches that your application will use on the config file under the System.Diagnostics / Switches section.

      <add name=SendEmailOnError value=0/>
      <add name=LogError value=1/>

From your application code, create an instance of the BooleanSwitch class using one of the following constructor overloads available:

public BooleanSwitch(string displayName, string description);
public BooleanSwitch(string displayName, string description, string defaultSwitchValue);

Once you have a valid instance you may use the Enabled property to get or set the current switch value and perform the tasks you are planning.

The following code snippet shows a BooleanSwitch class that uses the LogError to check if logs must be saved on catch blocks:

BooleanSwitch errorLogSwitch = new BooleanSwitch(“LogError”, “Specifies whether error logs are saved or not.”);

    /// Do something
catch (SqlException sqlEx)
    if (errorLogSwitch.Enabled)
        /// Save a log error to a file for example.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: