November 18, 2014

When is a Hyphen not a Hyphen?

Take a look at these 2 command line strings:
CASE 1:
"%windir%\Microsoft.NET\Framework\v2.0.50727\caspol.exe" -machine -addgroup All_Code 
-site 192.168.45.111 FullTrust -name "XXX : 192.168.45.111" -description 
"Allows full trust privileges to XXX Public Safety Applications"
CASE 2:
"%windir%\Microsoft.NET\Framework\v2.0.50727\caspol.exe" -machine -addgroup All_Code 
-site 192.168.45.111 FullTrust –name "XXX : 192.168.45.111" –description 
"Allows full trust privileges to XXX Public Safety Applications"

While the first one succeds the 2nd one fails. When we converted the "-name" in the first one to hex we got
2D6E616D65
Whereas in the second we got
966E616D65

The hyphen in the first is a hyphen but in the second one it is in fact a "non-breaking hyphen". This is just visible in this email but in a notepad editor they may look exactly the same.
The morale of the story is: Beware of command line arguments copied from 3rd party sources

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.