Category Archives: Uncategorized

Test base class thanks to Rob Connery

I saw this great testbase class in a Tekpub video. Thank goodness for tekpub videos. I wish everything that I purchased was that pragmatic.

public class TestBase
{
	public static string GetCaller()
	{
		StackTrace stackTrace = new StackTrace();
		return stackTrace.GetFrame(2).GetMethod().Name;
	}

	public void IsPending()
	{
		Console.WriteLine("{0} -- pending", GetCaller());
	}

	public void Describes(string description)
	{
		Console.WriteLine("-----------------------");
		Console.WriteLine(description);
		Console.WriteLine("-----------------------");
	}
}

Supercalifragilisticexpialidocious

Do not be afraid to type a little. Press all those little buttons on your keyboard. Last time, we talked about object types.  Since you get to make up your own types (what power you have!), give them a great name.  Give them a name that explains EXACTLY what they are. Two years from now, you will have to get back into that code again and explicit, maybe even what seemed like overzealous naming, will warm your heart.  Since you are making objects (and you are making objects aren’t you??), you will get auto-complete on the names anyway. You will not have to type out Song.Supercalifragilisticexpialidocious again, Visual Studio will do it for you!

This is one of the best things you can do to make your life easier as a programmer (I promise).

Happy typing,

Jim

Using log4net instead of the debugger

My current logging strategy for debugging

In a method, at a debug level, log at least the values of each parameter you are passing in. For Example:

With a method defined like this:

public int DoThisThing(int firstNumber, int secondNumber)

My log4net statement might look like this:

Log.InfoFormat(“MyClass just ran DoThisThingwith firstNumber’{0}’ and secondNumber’{1}’”, firstNumber, secondNumber);

I find myself using this as a persistent debugging tool. It can be really handy to read back through the logs.

I generally use the Colored Console Appender if I am watching live.

If you haven’t used them, the technologies I am talking about are:

log4net

BareTail (for watching multiple logs or reading old logs)

log4net smtp caching appender or how to not get 10,000 emails

This post begins with thanks to a post on www.l4ndash.com by Ken Parrish and a few other posts I found online.

I began using Ken’s code in production but found that it didn’t always reliably fire for me. I found that even though I had a flush interval of 5 minutes, I might get a log email with 10 errors and the ninth error could be two hours before the tenth. It seems that the logger would only fire when a larger event fired on the thread I was running. (The project is a window service).

After pulling down the log4net source code, I found that somehow I didn’t have the state just right when I called Flush on the BufferingAppenderSkeleton.

Being lazy, I ended up modifying Ken’s code to skip that flush all together instead of figuring out how to get that state right. It had something do to with a lossybuffer setting I didn’t care about.

Here is the code I ended up with:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using log4net.Appender;
using log4net.Core;

namespace log4net.Extensions
{
public class SmtpCachingAppender : SmtpAppender
{
private readonly List<LoggingEvent> _loggingEvents = new List<LoggingEvent>();

private int _numberOfCachedMessages;
private bool _timeToFlushHasElapsed;
private Timer _timer;

public SmtpCachingAppender()
{
FlushIntervalTime = new TimeSpan(0, 5, 0);
MinNumberToCacheBeforeSending = 20;
}

public TimeSpan FlushIntervalTime { get; set; }

public int MinNumberToCacheBeforeSending { get; set; }

public int MaxBufferSize { get; set; }

public override void ActivateOptions()
{
if (FlushIntervalTime > TimeSpan.Zero)
{
_timer = new Timer(OnTimer, null, FlushIntervalTime, FlushIntervalTime);
}
base.ActivateOptions();
}

private void OnTimer(Object stateInfo)
{
_timeToFlushHasElapsed = true;
SendBuffer();
}

private void SendBuffer()
{
try
{
if (MaxBufferSize != 0)
{
int numRemoved = _loggingEvents.Count – MaxBufferSize;
if ((numRemoved > 0) && (numRemoved <= _loggingEvents.Count))
{
_loggingEvents.RemoveRange(0, numRemoved);
}
}

_numberOfCachedMessages++;

if (((MinNumberToCacheBeforeSending != 0) && (_numberOfCachedMessages >= MinNumberToCacheBeforeSending)) || _timeToFlushHasElapsed)
{
if (_loggingEvents.Count > 0)
{
LoggingEvent[] bufferedEvents = _loggingEvents.ToArray();

base.SendBuffer(bufferedEvents);

_loggingEvents.Clear();
}
// Reset cache buffer conditions.
_numberOfCachedMessages = 0;
_timeToFlushHasElapsed = false;
}
}
catch (Exception)

{
//We never want to crash so we let nothing happen here purposefully
}
}
protected override void SendBuffer(LoggingEvent[] events)
{
foreach (var loggingEvent in events.Where(loggingEvent => !_loggingEvents.Contains(loggingEvent)))
{
_loggingEvents.Add(loggingEvent);
}
SendBuffer();
}
}
}

My config entry looks like this:

<appender name=”LimitedSmtpAppender” type=”log4net.Extensions.SmtpCachingAppender”>
<threshold value=”WARN”/>
<to value=”blah@blah.com”/>
<from value=”blah@blah.com”/>
<subject value=”ERROR: This was bad on this server”/>
<IncludeContextLogEvents value=”false”/>
<smtpHost value=”1.2.3.4″/>
<bufferSize value=”0″/>
<lossy value=”false”/>
<priority value=”high”/>
<FlushIntervalTime value=”00:00:30″/>
<MinNumberToCacheBeforeSending value=”10″/>
<MaxBufferSize value=”0″/><!– USE WITH CARE setting this to something other than 1, CAN make you lose messages permanently…–>
<layout type=”log4net.Layout.PatternLayout”>
<param name=”ConversionPattern” value=”%date{yyyy-MM-dd HH:mm:ss.fff} [%-2thread] [%-5level] [%logger] %message%newline%exception”/>
</layout>
</appender>

Happy logging,

-Jim

StructureMap – Where did the code put my keys?

This last week, I was refactoring an older code base with a co-worker that had no tests. As we started looking at the code, I realized that it was untestable as it sat. It seemed like there was a ‘New’ every 100 lines. We moved all the dependencies up using a bit of constructor injection.

As we got things into a testable state, I found we had a stack of ‘news’ at the top of the service, maybe 15 news all in a pile. This made our NUnit test setup harsh, and it was still hard to move classes and methods around. I looked to StructureMap for some relief.

StructureMap is an open source ‘Inversion of Control Container’. It news up your objects as you need them.  This will make your code more testable and happy. Goodness knows, we like happy code…

Generally, to use StructureMap, you put interfaces in your constructor parameters instead of primitive types or concrete objects. StructureMap will look for the greediest constructor of each class and try to use that one. It will new up a concrete instantiation of each interface listed in the constructor as it is needed.

To Get Started:

You will have to ‘bootstrap’ the structuremap engine. Below is a sample class that does just that:

public class IocContainerBootstrapper : Registry
{
private static bool _hasStarted;

public static void Bootstrap()
{
new IocContainerBootstrapper().BootstrapStructureMap();
}

public void BootstrapStructureMap()  //Initializes the structuremap container
{

ObjectFactory.Initialize(x => x.Scan(scanner =>
{
scanner.TheCallingAssembly();
scanner.WithDefaultConventions();
}
));

}

public static void Restart()
{
if (_hasStarted)
{
ObjectFactory.ResetDefaults();
}

else
{
Bootstrap();

_hasStarted = true;
}
}
}

Once you have this class in place and a reference to StructureMap in your project, call the Bootstrap method from your ‘Main()’ method in a windows service or the global.asax for the web. The bootstrapper example above will look in to the calling assembly. ‘WithDefaultConventions’ will assume that for each interface ‘IThingy’, there will be a concrete class called ‘Thingy’. You can explicitly name which concrete you require if that convention does not work for your situation.

Once you have called the bootstrapper like this:

private static IocContainerBootstrapper _bootStrapper; …

private static void Main(string[] args)
{

_bootStrapper = new IocContainerBootstrapper();
_bootStrapper.BootstrapStructureMap();

You can immediately log out everything StructureMap found to instantiate with something like this log4net call:

Log.DebugFormat(“We bootstrapped ‘{0}’:”, ObjectFactory.WhatDoIHave());

Once you have StructureMap running, you can tell it to spin up an instance of your upper level class like this:

_myThingySettings = ObjectFactory.GetInstance<IMyThingySettings>();

This call will spin up a concrete MyThingySettings and a concrete instance of every interface listed in its constructor. It will also spin up concretes as needed for any of those concretes, all the way down the dependency chain with this one call. You want to do this as high in your call stack as possible. There is a good article to read about this called The Three Calls Pattern in the Castle Project.

Now you have your objects and you can get to work!

Enjoy,

-Jim

Related Links:

http://martinfowler.com/articles/injection.html

http://docs.castleproject.org/Windsor.Three-Calls-Pattern.ashx

http://structuremap.net/structuremap/

Save the date

Or how to save yourself from the date – the DateTime.Now() call specifically.

I was privy to a production problem where a process that was calling DateTime.Now() rolled past midnight and everything went to pot.

These days, I try to abstract myself away from all that fun with an interface.

public interface ITimeActions
 {
 DateTime GetTodaysDate();
 }

The concrete implementation can be the actual call:
public  class TimeActions : ITimeActions
 {
      public DateTime GetTodaysDate()
           {
                return DateTime.Now;
           }
 }

Now, whenever I need the current date, I implement the interface instead of the concrete and I can test my code or save myself if I need to run for a different day.

Happy Coding,

-J

Start Windows service in a console window

I spend a lot of time writing windows services. If I had to install every one I worked on locally, my box would be terribly tired and a mess to boot.

A friend showed me a trick for starting the service in a console window. Use this code in your Main. You may have to add the string[] args parameter.

static void Main(string[] args)
        {
	   //Start IOC Container Structuremap
           //http://structuremap.net/structuremap/
            _bootStrapper = new IocContainerBootstrapper();
            _bootStrapper.BootstrapStructureMap();

            //This configurator starts up log4net
            XmlConfigurator.Configure();

            Log.DebugFormat("The SweetService service bootstrapped '{0}':"
              , ObjectFactory.WhatDoIHave());

            //Add '/console' to start options &gt; Command Line Arguments in
            //your project properties
	    //to get the service to start in console for debugging
            if (args.Length > 0 && args[0] == "/console")
            {
      Log.Debug("Starting this sweet service in Console mode for debugging");
               SweetService myService = new SweetService();
                myService.OnStart(args);
                Console.ReadKey();
            }
            else
            {
                ServiceBase[] servicesToRun = new ServiceBase[]
                  { new LabImportEngine() };
                Run(servicesToRun);
            }
        }

Put  ‘/console’ in your Start Options / Command line arguments in your visual studio project properties and set your project type to Console Application.

When you start the project now in a debugger, you will get a lovely console window with all your log4net output and you never had to install the service to work on it.

For this example, I am using log4net and I am using a colored console appender.  That makes the output in the console window great.

Enjoy,

Jim

Rollin’ rollin’ rollin’ – rollin’ back your data back in integration tests

Just got back from Iowa Code Camp 7, which was fantastic btw.
Had a funny moment sitting in Lee Brandt’s nHibernate demo where two of my co-workers and I all realized that we were doing some rocket surgery. We had just started refactoring a legacy codebase by adding integration tests and were manually rolling back the database changes with several lines of handwritten sql deletes… (sorry). Looking at Lee’s demo code, we saw him using a transaction for the rollbacks and I hung my head in shame.

Thank you Mr. Tim Squires for writing out this code sample for me:

using NUnit.Framework;
using System.Transactions;
namespace ProjectName.Tests.Integration
{
    [TestFixture]
    public class TestClass
    {
        private TransactionScope _transactionScope;
        [SetUp]
        public void SetUp()
        {
            _transactionScope = new TransactionScope(TransactionScopeOption.RequiresNew);
        }
        //...Test some stuff, insert records, update records, etc...
        [TearDown]
        public void TearDown()
        {
            _transactionScope.Dispose();
        }
    }
}