October 25, 2019

Expand Environment Variables Extension

An extension to expand environment variables within a string

namespace Common.Environment.EnvironmentVariableExtension
{
  public static class StringEnvironmentVariableExtension
  {
    public static string ExpandEnvironmentVariables(this string path)
    {
        Debug.Assert(path != null);
        string result = "";
        result = Environment.ExpandEnvironmentVariables(path);
        return result;
    }
  }
}
and usage
using Common.Environment.EnvironmentVariableExtension;

[Test]
public void ExpandEnvironmentVariablesUsage()
{
    string path = "%Temp%";
    string tempPath = path.ExpandEnvironmentVariables();
}

October 23, 2019

Using StackTrace Object to Help Debugging

This is useful when you need to ensure that an action (eg. breakpoint) occurs only when the method was invoked in the correct context. Frequently the area of interest could be invoked from several areas/contexts, the StackTrace object allows you to ensure that you are debugging the common method within the correct invokation context

StackTrace st = new StackTrace(false);
var found = st.GetFrames().Any(sf => sf.GetMethod().Name.Contains("MethodName"));

if (found) // This ensures that the action occurs in the correct context
{
 if (ix == 1) // or some other condition
 {
  Trace.WriteLine("Stack Trace of where the exception occurred: " + st.ToString());
     Debugger.Break(); // Forces a breakpoint here
  
  throw new MyException("Test exception");
 }
}

Be aware that a StackTrace object is computationally quite expensive. This technique might not work where the method being debugged is called at a high rate and which finishes processing very quickly. However, we are using it here for debugging only.