June 14, 2017

A ConcurrentStreamWriter Class

A class for writing to a stream from multiple threads:

public interface IConcurrentStreamWriter
{
    void WriteStream(
        string theStringToWrite);
}

/// <summary>
///     A concurrent stream writer. Allows concurrent/queued writes to a stream
/// </summary>
///
/// <seealso cref="T:ASM.DEK.Printer.Micron.PrintEngine.Timing.Timers.IConcurrentStreamWriter"/>
/// <seealso cref="T:System.IDisposable"/>
public class ConcurrentStreamWriter : IConcurrentStreamWriter, IDisposable
{
    private readonly Func<StreamWriter> _streamWriterProvider;
    private readonly ConcurrentQueue<string> queuedWrites = new ConcurrentQueue<string>();
    private readonly AutoResetEvent _autoResetEvent = new AutoResetEvent(false);

    private bool _exit;

    public ConcurrentStreamWriter(
        Func<StreamWriter> streamWriterProvider)
    {
        Contract.Requires<ArgumentNullException>(
            streamWriterProvider != null);

        _streamWriterProvider = streamWriterProvider;

        Task.Factory.StartNew(
            WriteQueueThreadRoutine, 
            TaskCreationOptions.LongRunning);
    }

    public void WriteStream(
        string theStringToWrite)
    {
        if (!string.IsNullOrEmpty(theStringToWrite))
        {
            queuedWrites.Enqueue(theStringToWrite);
            _autoResetEvent.Set();
        }
    }

    #region private

    private void WriteQueueThreadRoutine()
    {
        using (var stream = _streamWriterProvider())
        {
            while (!_exit)
            {
                _autoResetEvent.WaitOne();
                if (queuedWrites.Count > 0)
                {
                    WriteQueueImpl(stream);
                }
            }
        }
        _autoResetEvent.Dispose();
    }

    private void WriteQueueImpl(
        StreamWriter stream)
    {
        try
        {
            string stringToWrite = "";
            do
            {
                if (queuedWrites.TryDequeue(out stringToWrite))
                {
                    stream.WriteLine(stringToWrite);
                }
            } while (queuedWrites.Count > 0);
            stream.Flush();
        }
        catch (IOException ioex)
        {
            Trace.WriteLine("IOException caught: " + ioex);
        }
    }

    #endregion private

    #region Dispose Implementation

    // Use C# destructor syntax for finalization code.
    ~ConcurrentStreamWriter()
    {
        Dispose(false);
        Debug.Assert(false, "Detected ConcurrentStreamWriter object was undisposed");
    }

    private bool _isDisposed;

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(
        bool disposing)
    {
        if (_isDisposed)
            return;

        if (disposing)
        {
            _exit = true;
            _autoResetEvent.Set();
        }

        _isDisposed = true;
    }

    #endregion Dispose Implementation
}
It uses a ConcurrentQueue object to queue the stream requests up and an AutoResetEvent to release a writer on a separate thread to actually output the stream contents.

May 25, 2017

Fluent Builder Template

Fluent interfaces Create a more simplified language style approach to coding.
Here is a template for an object builder class that gives a fluent interface for the construction of objects:
[ ExcludeFromCodeCoverage ]
public class $XXX$Builder
{
    private $IYYY$ _mock$IYYY$ = Substitute.For<$IYYY$>();

    public $XXX$Builder With$IYYY$(
        $IYYY$ param )
    {
        _mock$IYYY$ = param;
        return this;
    }

    public static implicit operator $XXX$( $XXX$Builder builder )
    {
        return builder.Build();
    }

    public $XXX$ Build()
    {
        return new $XXX$( _mock$IYYY$ );
    }
}
Replace $XXX$ with your concrete builder target type
For each service replace $IYYY$ with the service name

2 Dimensional List Sort Using Linq

A 2 dimensional list sort
[ Test ]
public void List2DSortTest()
{
    var table = new List<List<string>>
    {
        new List<string> { "1", "Mbukuravi", "2", "Wnuk-Lipinski Settlement", "M2M" },
        new List<string> { "2", "Liaedin", "Ulrich's Rock", "Valigursky Landing", "L1M" },
        new List<string> { "3", "Miao Thixo", "2 A", "Sekelj Laboratory", "M3M" },
    };

    var newTable = table.OrderBy( list => list[ 1 ] ).ToList();
    Assert.That( newTable[ 0 ][ 1 ] == "Liaedin" );
    Assert.That( newTable[ 1 ][ 1 ] == "Mbukuravi" );
    Assert.That( newTable[ 2 ][ 1 ] == "Miao Thixo" );

    var newTable2 = table.OrderByDescending( list => list[ 1 ] ).ToList();
    Assert.That( newTable2[ 2 ][ 1 ] == "Liaedin" );
    Assert.That( newTable2[ 1 ][ 1 ] == "Mbukuravi" );
    Assert.That( newTable2[ 0 ][ 1 ] == "Miao Thixo" );

    var newTable3 = table.OrderBy( list => list[ 2 ] ).ToList();
    var newTable4 = table.OrderByDescending( list => list[ 2 ] ).ToList();
}

March 2, 2017

An Exception Handling String Formatter

A string extension class to safely use string.Format().
public static class StringExtensions
{
    // Safe format, capture any Format Exceptions.
    public static string TryFormat(
        this string formatText,
        params object[] parameters)
    {
        string res = "";
        try
        {
            res = string.Format(formatText, parameters);
        }
        catch (FormatException fe)
        {
            string msg = "Formatting string error : formatText=" + formatText + 
                                ", parameters=\'" +
                              string.Join( ",", parameters ) + "\', exception=" + fe;
            Trace.WriteLine("string.Format code needs fixing - " msg);
            res = formatText;
            Debug.Assert(false, msg);
        }
        return res;
    }
}
I have seen this method take down a complete application because too few parameters were passed.

Thread Safe Enum Access Using Interlocked

Here is an example class that makes reading and writing an enum thread safe (when writing or reading the enum value)
/// <summary>
///     A thread safe MyEnum.
/// </summary>
public class ThreadSafeMyEnum
{
 // Volatile is not needed (esp. on x64 or x86) : 
 // http://stackoverflow.com/questions/7177169/how-to-apply-interlocked-exchange-for-enum-types-in-c 
 // http://stackoverflow.com/questions/425132/a-reference-to-a-volatile-field-will-not-be-treated-as-volatile-implications
 private int _enumAsInt;

 public MyEnum Value // added for convenience
 {
  get { return ( MyEnum ) Interlocked.CompareExchange( ref _enumAsInt, 0, 0 ); }
  set { Interlocked.Exchange( ref _enumAsInt, ( int ) value ); }
 }
}

NUnit Parameterised Unit Test Classes

NUnit can have paramterised unit test classes (as opposed to parameterised tests, that are also possible):
[ TestFixture( MachineEnum.None ) ]
[ TestFixture( MachineEnum.Lathe ) ]
[ TestFixture( MachineEnum.Miller ) ]
public class SomeTests
{
 private readonly MachineEnum _machineEnum = MachineEnum.None;

 public SomeTests(
  MachineEnum machineEnum )
 {
  _machineEnum = machineEnum;
 }

 ...
}

February 20, 2017

Double Equals Extension Class

Doubles cannot be compared without specifying an acceptable error
//     A double extensions class.
public static class DoubleExtensions
{ 
 public static bool IsEqualTo(
  this double val1,
  double val2,
  double resolution ) // Resolution of the double comparison, specifies an acceptable error level
 {
  double compare = Math.Abs( val1 - val2 );
  bool res = compare < resolution;
  return res;
 }
}