Saturday, October 11, 2014

Collection was modified; enumeration operation might not execute.

Problem:
Iterating through a loop of DataTable.Rows and you try and delete a row and get:
Collection was modified; enumeration operation might not execute.
foreach (DataRow dr in dt.Rows)
{
   if ((int)dr["ID"] > 5)
      dr.Delete();
}


Simplest Solution:
Don't loop on the original collection of Rows, but instead do a Select("") and pull those DataRows into an Array and loop on that.  Now you can Delete() to your heart's content.

foreach (DataRow dr in dt.Select(""))
{
   if ((int)dr["ID"] > 5)
      dr.Delete();
}

Thursday, September 25, 2014

Designing Your Application to be Unit Testable

The easiest way to structure any application so that it is unit testable is to break up the main sections of the work being down into some basic pieces.  These are:

  1. Get your data
  2. Do work with your data
  3. Commit changes to your data
With this basic application structure you can now separate the pulling and processing of the data.  You are in complete control of that data being used by the processing code and can manipulated it as you see fit.  It is the ideal structure for unit testable code.  

public class MyMainWorker
{
    public void RunWorker()
    {
        // Optional begin your transaction here
        DataSet ds = GetData();
        object o = Execute(ds);
        // Begin your transaction
        SaveData(ds);
        // Commit your transaction
    }

    private void SaveData(DataSet ds)
    {
        throw new NotImplementedException();
    }

    private object Execute(DataSet ds)
    {
        throw new NotImplementedException();
    }

    private DataSet GetData()
    {
        throw new NotImplementedException();
    }
}

Wednesday, September 24, 2014

?? Operator is great for defaulting objects

If you need to default an object, an easy way to do this is with the null-coalescing operator.  In this example I need to default MyTempClass if I cannot pull it from another location.

using System;

namespace Tips
{
    public class NullCoalescingOperator
    {
        public void RunTip()
        {
            MyTempClass myTempClass = null;
            MyTempClass myOtherTempClass = new MyTempClass()
            {
                MyProperty = 1
            };
            MyTempClass x = myTempClass ?? myOtherTempClass;
            Console.WriteLine("{0}", x.MyProperty);
        }
    }

    public class MyTempClass
    {
        public int MyProperty { get; set; }
    }
}