Archive

Archive for October, 2012

Pluralize words

October 21, 2012 Leave a comment

Whenever I’ve needed the plural form of a word, I’ve always relied on the Inflector class from the Castle ActiveRecord project.

string plural = Inflector.Pluralize("planet");
Console.WriteLine (plural);

Since .NET 4.0, Microsoft has added their own PluralizationService class to pluralize words. Microsoft’s PluralizationService class is actually used in the Entity Framework tools to generate singular or plural entity names.

var service = PluralizationService
	.CreateService(CultureInfo.GetCultureInfo("en-us"));

string plural = service.Pluralize("planet");
Console.WriteLine(plural);

There are cases when both classes do not generate the same plural form of a word. For example, attempting to pluralize the word “virus” generates different results. Inflector will return “viri” while the PluralizationService will return “virus”. Neither generated the more common “viruses”.

Castle DictionaryAdapter – Using TypeConverter to map different types

October 20, 2012 1 comment

I’ve posted about the DictionaryAdapter a few times in the past (here and here). There are scenarios when we want to map more than just simple types to strings. For example, we have an interface IPerson with the property Birthday representing the date in ticks.

public interface IPerson
{
    string Name { get; set; }
    int Age { get; set; }
    long Birthday { get; set; }
}

If we attempt to map a DateTime to the property Birthday, an InvalidCastException will be thrown when we access the Birthday property.

var dictionary = new Dictionary<string, object>
{ 
    { "Name", "John Doe" },
    { "Age", 30 },
    { "Birthday", DateTime.Now },
};

IPerson person = new DictionaryAdapterFactory()
	.GetAdapter<IPerson>(dictionary);

Console.WriteLine(person.Birthday);

Fortunately, the DictionaryAdapter allows us to use attributes to define how properties should be mapped by creating a class that inherits from System.ComponentModel.TypeConverter.

public class DateTimeToTicks : TypeConverter
{
	public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
	{
		if (sourceType == typeof(DateTime))
			return true;
		
		return base.CanConvertFrom(context, sourceType);
	}

	public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
	{
		return ((DateTime)value).Ticks;
	}
}

We can decorate the Birthday property with the TypeConverter attribute and specify that we want to use our new type converter.

[TypeConverter(typeof(DateTimeToTicks))]
long Birthday { get; set; }

The previous example is a bit contrived. However, I have run into issues when trying to use the DictionaryAdapter with a result set from a database that contains NULLs. Here we’ve updated the IPerson interface with a Nullable<int>.

public interface  IPerson
{
    string Name { get; set; }
    int? Age { get; set; }
}

The following code will throw an InvalidCastException on line 17 after mapping the results from a SQL query:

using (var conn = new SqlConnection(connStr))
using (var cmd = new SqlCommand("select 'John Doe' as [Name], NULL as [Age]", conn))
{
    conn.Open();

    using (SqlDataReader dr = cmd.ExecuteReader())
    {
        while (dr.Read())
        {
            var dictionary = Enumerable
                .Range(0, dr.FieldCount)
                .ToDictionary(dr.GetName, dr.GetValue);

            IPerson person = new DictionaryAdapterFactory()
                .GetAdapter<IPerson>(dictionary);

            Console.WriteLine(person.Age);
        }
    }
}    

We can create another TypeConverter to check for DBNull and returns null if found.

public class DBNullable : TypeConverter
{
    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
    {
        if (sourceType == DBNull.Value.GetType())
            return true;

        return base.CanConvertFrom(context, sourceType);
    }

    public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
    {
        if (DBNull.Value.Equals(value))
            return null;

        return base.ConvertFrom(context, culture, value);
    }
}

Again, we can decorate the Age property with our new type converter.

[TypeConverter(typeof(DBNullable))]
int? Age { get; set; }

Multiple threads and refreshing Spring.NET’s context

October 4, 2012 1 comment

One of our legacy applications uses Spring.NET as a service locator. In most cases, I generally agree that using a service locator is an anti-pattern. Unfortunately, this code is littered throughout the project:

var context = ContextRegistry.GetContext() as IConfigurableApplicationContext;
IService service = context.GetObject("name-of-object") as IService;

Spring.NET exposes a method that refreshes all the object definitions.

var context = ContextRegistry.GetContext() as IConfigurableApplicationContext;
context.Refresh();

Unfortunately, if another thread is attempting to resolve an object from the container while the context is being refreshed, a NullReferenceException is thrown.

System.NullReferenceException: Object reference not set to an instance of an object.
   at Spring.Context.Support.AbstractApplicationContext.GetObject(String name) in c:\_prj\spring-net\trunk\src\Spring\Spring.Core\Context\Support\AbstractApplicationContext.cs:line 1538
   at ConsoleDemo.Program.<Main>b__1() in C:\projects\ConsoleDemo\ConsoleDemo\Program.cs:line 30

A simple solution is to utilize the ReaderWriterLockSlim class to allow multiple threads to resolve objects while allowing us to block all the threads when we need to refresh the object definitions.

public static class ServiceLocator
{
    private static readonly ReaderWriterLockSlim locker;

    static ServiceLocator()
    {
        locker = new ReaderWriterLockSlim();
    }

    public static T GetObject<T>(string name) 
        where T : class
    {
        locker.EnterReadLock();
        try
        {
            var context = ContextRegistry.GetContext() as IConfigurableApplicationContext;
            return context.GetObject(name) as T;
        }
        finally
        {
            locker.ExitReadLock();
        }
    }

    public static void RefreshContext()
    {
        locker.EnterWriteLock();
        try
        {
            var context = ContextRegistry.GetContext() as IConfigurableApplicationContext;
            context.Refresh();
        }
        finally
        {
            locker.ExitWriteLock();
        }
    }
}

Developers and QA – pair testing

October 2, 2012 1 comment

I’m writing this from a developer’s perspective. I don’t have the experience or background to present this from a tester’s perspective.

Most people are familiar with pair programming and its benefit in a wide spectrum of scenarios. However, I don’t see very many people practicing pair testing. I find that pair testing with both a developer and tester to be extremely beneficial to both people. The savings in communication overhead is worth it by itself.

  • Collaboration – Not only do I rely on my testers to verify functionality, but to identify scenarios where a system or function would fail. In other words, testers are also users of a system. When soliciting feedback about a feature or update, I always involve the business, developers, and testers. Unfortunately, I rarely see this happening.
  • Knowledge sharing – Occasionally when I’m working with someone who isn’t as familiar with a system, they aren’t really sure what type of questions to ask. I find that people really open up once I start explaining the system from start to finish. Not all questions are going to be answered in a single pair testing session, especially for a complex system. Being able to ask questions face-to-face allows a person to understand the system faster and more thoroughly.
  • Mutual Learning – The best way to learn something is to teach it. Over many sessions, I’ve found many ways to test my own code more effectively and have gained new perspectives on how something may be used. Testers gain a more thorough understanding of the system they are testing and learns how a developer steps through and debugs issues.
  • Safety net – I find that one of the most valuable traits of a good tester is the ability to ask good questions. I very much dislike working with people who do not ask questions if they don’t understand a topic. There have been many times where asking questions have led me to question the way I’ve implemented something. Perhaps it was a small issue that I overlooked or a hidden issue that we managed to uncover as part of our collaboration. Whichever the case, it helps me from having tunnel vision.

In my opinion, breaking down the communication barrier between developers and testers is one the most important goals that a team can achieve.