All posts by Jim

Unknown's avatar

About Jim

Maker of things. I work in wood, metal, and on melted silicon chips - what have you.

Rolling rolling rolling – rolling back your data back in integration tests

A couple years ago, I had just started refactoring a legacy codebase by adding integration tests and was manually rolling back the database changes with several lines of handwritten sql deletes… (sorry). At Iowa Code Camp, I went to a Lee Brandt demo and looking at Lee’s demo code, I saw him using a transaction for the rollbacks and I hung my head in shame.

Try it like this:

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();
 }
 }
}

Happy Testing,

Jim

Tips and Tricks: 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.

Here is a way to  start a service in a console window without installing it on your box. Use this code in your Main. You will have to add the string[] args parameter if you do not have it.


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 > 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 SweetService() };
          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

My way or the highway! Activator.CreateInstance

I have an object that I always need created in one specific way. Its bits have to be loaded in a certain order and I want to control whenever that happens. Any other code requiring this object has to call my loader method.

I implement like this, using Activator.CreateInstance:

  1. Give the object a private constructor.
public class Monkey
{
     private Monkey()
     {}
}

2. In my loader class, I use Activator.CreateInstance like this:

(Monkey)Activator.CreateInstance(typeof(Monkey), true);

I also use this same activator code to spin up one of these monkeys in my test classes.

Entity Framework Validation Errors

Found this lovely little code snipped for interrogating the database validation errors sent back from an Entity Framework Save:


catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;

Enjoy,

-Jim

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("-----------------------");
	}
}

Nullable Dates in FileHelpers

I was fighting problem where I hade a DateTime? and wanted the result to be an empty string if the value is null. By default, FileHelpers was giving me ‘01010001’.

This little custom converter took fine care of the problem:

 


    public class CustomDateConverter : ConverterBase
    {
        public override object StringToField(string value)
        {
            if(value == null)
            {
                return string.Empty;
            }
            return value;
        }
    }

The field being decorated looks like this:

   
[FieldConverter(typeof(CustomDateConverter))]  
public DateTime? VerificationDate;

Extension Method Bliss

In the last six months, I have dabbled a little bit in Ruby. What I found was that I didn’t really want to work in Ruby but I wanted some of the beautiful syntax. I use extension methods to bring some of that goodness back to C#.

Here are a few favorites:

public static bool IsANumber(this string value)
{
float output;
return float.TryParse(value, out output);
}

public static bool IsNotANumber(this string value)
{
float output;
return !float.TryParse(value, out output);
}

public static string FormattedAsAPhoneNumberWithDashes(this string s)
{
if(s.IsNotANumber() || s.Length != 10)
{
return string.Empty;
}

StringBuilder formattedPhone = new StringBuilder();
formattedPhone.Append(s.Substring(0, 3));
formattedPhone.Append("-");
formattedPhone.Append(s.Substring(3, 3));
formattedPhone.Append("-");
formattedPhone.Append(s.Substring(6, 4));
return formattedPhone.ToString();
}

public static string XmlEncode(this string s)
{

return string.IsNullOrWhiteSpace(s) ? string.Empty : System.Security.SecurityElement.Escape(s);
}

public static bool IsNullOrWhiteSpace(this string value)
{
return string.IsNullOrWhiteSpace(value);
}

public static string SafeTrim(this string value)
{
return value == null ? string.Empty : value.Trim();
}

public static string SafeParseStringToDate(this string dateToParse)
{
DateTime dtTemp;
return DateTime.TryParse(dateToParse, out dtTemp) ? dtTemp.ToString() : string.Empty;

}

public static string TrimmedAndLowered(this string value)
{
return value.SafeTrim().ToLower();
}

public static string AddAProperCommaToAName(this string lastname, string firstname)
{
if (!string.IsNullOrWhiteSpace(lastname) && !string.IsNullOrWhiteSpace(firstname))
return lastname + ", " + firstname;

return !string.IsNullOrWhiteSpace(lastname) ? lastname : firstname;
}

public static bool IsNotNull(this object obj)
{
return obj != null;
}

public static bool IsNull(this object obj)
{
return obj == null;
}

public static bool In(this string value, params string[] paramArray)
{
	return value.IsNotNull() && paramArray.Any(param => param.TrimmedAndLowered() == value.TrimmedAndLowered());
}

public static bool In(this int? value, params int[] paramArray)
{
	return value.IsNotNull() && paramArray.Any(param => param == value);
}

public static bool In(this int value, params int[] paramArray)
{
	return paramArray.Any(param => param == value);
}

public static string RemoveNumericCharacters(this string value)
{
	Regex regex = new Regex("[0-9]");
	value = regex.Replace(value, "");
	return value;
}


public static string RemoveNonNumericCharacters(this string value)
{
	if (value == null)
		return string.Empty;
	Regex onlyNumeric = new Regex(@"[^\d]");
	var result =  onlyNumeric.Replace(value, string.Empty);
	
	return result;
}

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