November 6, 2014

Debug with an IntegerOptionFile

Sometimes it is useful when debugging within an application to change the logic using an external influence, for example, using a value in a file. I have made the class as small as possible so that it can be copied and pasted anywhere for temporary debugging help Something that can be used like this:
...
int myOption = IntegerOptionFile.WriteValue(1)
...
int myOption = IntegerOptionFile.ReadValue()
if (myOption == 1)
{
    PerformSomeOptionalCode()
}
...
Here we can change a special option file and have the code change behaviour:
using System.IO;
...
// Use this to help debug an application by writing code
// that can be switched by reading a value from a text file
internal static class IntegerOptionFile
{
    private static readonly string optionFilePath = Path.Combine(
        Path.GetTempPath(), "intoption.txt");

    public static void WriteValue(int option)
    {
        File.WriteAllText(optionFilePath, option.ToString());
    }

    // Consider defining a suitable default value
    public static int ReadValue(int def = default(int))
    {
        int option = def;
        bool res = File.Exists(optionFilePath);
        if (!res)
        {
            WriteValue(def);
        }
        res = File.Exists(optionFilePath);
        if (res)
        {
            string tmp = File.ReadAllText(optionFilePath);
            if (tmp.Length > 0)
            {
                int.TryParse(tmp, out option);
            }
        }
        return option;
    }
}
By using a text file we can change the value from a simple notepad editor and have the running program change behaviour immediately. Note that this is only temporary code used for debugging/investigating a problem, not for release code.

No comments: