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.


November 10, 2018

ThreadPool Extensions

A better more versatile way to do this is to use Task<> objects
public static class ThreadpoolExtensions
{
    // Execute a method/procedure on the thread pool
    // The state parameters allow you to pass parameters into the thread routine 
    public static bool ExecuteOnThreadPoolThread<T>(this Action<T> threadRoutine, T args)
    {
        return ThreadPool.QueueUserWorkItem(s => threadRoutine((T)s), args);
    }

    // Execute a method/procedure on the thread pool
    public static bool ExecuteOnThreadPoolThread(this Action threadRoutine)
    {
        return ThreadPool.QueueUserWorkItem((obj) => threadRoutine());
    }
}

SImple Application Settings Manager

Heres a quick class to read and write settings to the application config file
// A Minimal class to read and write settings directly to the application 
// config file with NO write permission constraints. It does keep a separate
// copy of the config file for each user
// Only Key/Value style settings can be written, and string ones only at that but
// converting most simple types to and from a string is trivial.
public class SettingsManager : ISettingsManager
{
    public string ReadSetting(string key)
    {
        try
        {
            var appSettings = ConfigurationManager.AppSettings;
            var result = appSettings[key] ?? string.Empty;
            return result;
        }
        catch (ConfigurationErrorsException ex)
        {
            Trace.WriteLine("Configuration file exception : " + ex);
        }
        return string.Empty;
    }

    public void WriteSetting(string key, string value)
    {
        try
        {
            var configFile = ConfigurationManager.OpenExeConfiguration(
                ConfigurationUserLevel.None);
            var settings = configFile.AppSettings.Settings;
            if (settings.Count == 0 | settings[key] == null)
            {
                settings.Add(key, value);
            }
            else
            {
                settings[key].Value = value;
            }
            configFile.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection(
                configFile.AppSettings.SectionInformation.Name);
        }
        catch (ConfigurationErrorsException ex)
        {
            Trace.WriteLine("Configuration file exception : "+ ex);
        }
    }

October 10, 2018

Binary in .Net

Use the "Convert" class.
string binStr = "1100110001";
long number = Convert.ToInt64(binStr, 2);

Console.WriteLine(binStr + " in binary : " + number + " in decimal");
also from C# version 7 it is possible to declare numeric values in terms of binary literals:
int binaryLiteral = 0b0010_0110_0000_0011;
int binaryLiteral2 = 0b0010011000000011;
Debug.Assert(binaryLiteral == binaryLiteral2);

Console.WriteLine("0b0010_0110_0000_0011 in binary : " + binaryLiteral + " in decimal");
Finally to convert a number to a binary string
int number = 9731;
string binary = Convert.ToString(number, 2);

Console.WriteLine(number + " in binary : " + binary);

July 5, 2018

Use of gcAllowVeryLargeObjects

To allow he creation of very large arrays, lists etc. insert
<configuration>  
  <runtime>  
    <gcAllowVeryLargeObjects enabled="true" />  
  </runtime>  
</configuration>
in the application config file. This only works for 64 bit applications! This could also cause problems when unit testing because you need to ensure your test runner is running in 64 bit mode with the given entry within the test runner's config file.

February 13, 2018

Example of the Visitor Pattern


A simple but non-contrived example of the Visitor pattern. Here are the main classes.

// Interface for the visiting system permit populator
public interface IPopulatorVisitor
{
    void PopulateVisit(ISet<int> permitSystemsSet);
}

public interface IPermitSystems
{
    void AcceptPopulator(IPopulatorVisitor populatorVisitor);

    bool PermitRequired(int systemId);
}

// This is the Visitor target
// It stores a set of systems that require a permit for entry
public class PermitSystems : IPermitSystems
{
    HashSet<int> _permitRequiredSystemIds = new HashSet<int>();

    // Accept Visitors here
    public void AcceptPopulator(IPopulatorVisitor populatorVisitor)
    {
        populatorVisitor.PopulateVisit(_permitRequiredSystemIds);
    }

    public bool PermitRequired(int systemId)
    {
        bool res = _permitRequiredSystemIds.Contains(systemId);
        return res;
    }
}

The Visitor class, this has removed the responsibility for deserialising the permit data from the the PermitSystems class. In this case the data is stored in 'JSonl' form, but it could be stored in other formats and a different visitor would be provided

public class PermitSystemsJsonlDeserialiserVisitor 
    : IPopulatorVisitor
{
    FileInfo _jsonlFilePath;

    public void Initialise(string jsonlFilePath)
    {
        _jsonlFilePath = new FileInfo(jsonlFilePath);
    }

    public void PopulateVisit(ISet<int> permitSystemsSet)
    {
        List permitReqdSystems;
        if (_jsonlFilePath.TryLoadFromJson(out permitReqdSystems))
        {
            if (permitReqdSystems != null)
            {
                PopulateImpl(permitSystemsSet, permitReqdSystems);
            }
        }
    }

    private static void PopulateImpl(ISet<int> permitSystemsSet, 
        List permitReqdSystems)
    {
        foreach (var sys in permitReqdSystems)
        {
            Trace.WriteLine(" Permit required for id=" + sys.id + " name=" + sys.name +
                            " permitRequired=" + sys.permitRequired);
            permitSystemsSet.Add(sys.id);
        }
    }
}
Some sample code to bring it all together
[Test]
public void PermitSystemsExperiment()
{
    IPermitSystems permitSystems = new PermitSystems();
    PermitSystemsJsonlDeserialiserVisitor jdv = new PermitSystemsJsonlDeserialiserVisitor();
    jdv.Initialise(TestFilePaths.PermitRequiredSystemsJSonFilePath);
    permitSystems.AcceptPopulator(jdv);

    Assert.That(true == permitSystems.PermitRequired(19054));
    Assert.That(false == permitSystems.PermitRequired(26));
}