Reflections on the Naked CLR
I am teaching beginners right now, and we started out from:
using (SqlConnection connection = new SqlConnection(Settings.Default.Database))
{
connection.Open();
using (SqlTransaction tx = connection.BeginTransaction())
{
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "SELECT COUNT(*) FROM Books;";
result = (int)command.ExecuteScalar();
}
tx.Commit();
}
}
But they said that they already know this stuff and I am boring, so we moved to this:
return With.Transaction<int>(delegate(SqlCommand command)
{
command.CommandType = System.Data.CommandType.Text;
command.CommandText = "SELECT COUNT(*) FROM Books;";
return (int)command.ExecuteScalar();
});
Where the implementation is:
public static void Transaction(Proc exec)
{
using (SqlConnection connection = new SqlConnection(Settings.Default.Database))
{
connection.Open();
SqlTransaction tx = connection.BeginTransaction();
try
{
using (SqlCommand command = connection.CreateCommand())
{
command.Transaction = tx;
exec(command);
}
tx.Commit();
}
catch
{
tx.Rollback();
throw;
}
finally
{
tx.Dispose();
}
}
}
}
They didn't think it was boring any longer :-)
That made for some interesting diagrams, just to show the flow of the code. The piece of code above covers a lot of topics, next step is to introduce Unit of Work.
They are beginners, so they need to understand the basics well before they can do anything with frameworks, but I just find it so frustrating to work on the naked CLR. It is like a construction worker that can arrive on a building site with an anvil and a hammer, and then need to build all the tools before they can start working.