Click here to Skip to main content
Click here to Skip to main content
Add your own
alternative version
Go to top

How design patterns can help you in developing unit testing-enabled applications

, 15 Nov 2007
This article shows how you can mix together Model-View-Presenter, Domain Model, Services, ActiveRecord, and Repository patterns to create a testable application.
Northwind.zip
nunit.framework.dll
Northwind.DataAccess
Northwind.DataAccess.csproj.user
Properties
Query
Repository
Northwind.DataAccess.Test
Northwind.DataAccess.Test.csproj.user
Properties
Northwind.Domain
Dao
Model
Northwind.Domain.csproj.user
Presentation
Properties
Repository
TransferObjects
Northwind.Domain.Test
Northwind.Domain.Test.csproj.user
Properties
Northwind.Presentation
Northwind.Presentation.csproj.user
Properties
Northwind.Presentation.Test
Northwind.Presentation.Test.csproj.user
Properties
Northwind.Services
Northwind.Services.csproj.user
Properties
Northwind.Services.Test
Northwind.Services.Test.csproj.user
Properties
Northwind.TransferObjects
Model
Northwind.TransferObjects.csproj.user
Presentation
Properties
Northwind.TransferObjects.Test
Northwind.TransferObjects.Test.csproj.user
Properties
Northwind.UI
Northwind.UI.csproj.user
NorthWind.UI.suo
Properties
Settings.settings
Northwind.UI.Controls
Northwind.UI.Controls.csproj.user
Properties
Castle.ActiveRecord.dll
Castle.Core.dll
Iesi.Collections.dll
log4net.dll
NHibernate.dll
NMock2.dll
using Castle.ActiveRecord;
using Northwind.Domain;
using Northwind.TransferObjects.Model;
using NHibernate.Collection;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

namespace Northwind.TransferObjects.Presentation
{
    /// <summary>
    /// This class exposes conversion facilities, like converting a domain object to a transfer object and updating a domain object from a transfer object source.
    /// </summary>
    /// <typeparam name="T">A domain model class</typeparam>
    public static class TOHelper<T> where T : class
    {
        /// <summary>
        /// Creates a new transfer object from a domain object
        /// </summary>
        /// <param name="targetType">Transfer object type to be created</param>
        /// <param name="domainObject">The domain object from which data will be retrieved</param>
        /// <returns>A new transfer object</returns>
        public static object GetTO(Type targetType, object domainObject)
        {
            object[] constructorArgs = new object[targetType.GetConstructors()[0].GetParameters().Length];

            int i = 0;
            foreach (ParameterInfo parameterInfo in targetType.GetConstructors()[0].GetParameters())
            {
                string paramName = parameterInfo.Name;
                //first letter must be uppercase
                paramName = paramName.Substring(0, 1).ToUpper() + paramName.Substring(1);
                PropertyInfo piSource = domainObject.GetType().BaseType.GetProperty(paramName);
                if (piSource == null)
                {
                    piSource = domainObject.GetType().GetProperty(paramName);
                }

                if (piSource != null)
                {
                    object value = piSource.GetValue(domainObject, null);
                    if (value == null)
                    {
                        
                    }
                    else
                    {
                        if (value is List<object>)
                        {
                            IList<object> list = new List<object>();
                            foreach (Object o in (List<object>)value)
                            {
                                Type sourceChildItemType = o.GetType();
                                Type targetChildItemType = null;

                                if (targetChildItemType == null)
                                {
                                    foreach (Attribute att in sourceChildItemType.GetCustomAttributes(true))
                                    {
                                        if (att is MappedTO)
                                        {
                                            string transferObjectFullName = ((MappedTO)att).TransferObjectFullName;
                                            targetChildItemType = Type.GetType(transferObjectFullName);
                                            if (targetChildItemType == null)
                                            {
                                                throw new Exception(transferObjectFullName + " object not found");
                                            }
                                            break;
                                        }
                                    }
                                }

                                if (targetChildItemType != null)
                                {
                                    object targetChildItem = TOHelper<T>.GetTO(targetChildItemType, o);
                                    list.Add(targetChildItem);
                                }
                            }
                            constructorArgs[i] = list;
                        }
                        else
                        {
                            constructorArgs[i] = value;
                        }
                    }
                }
                i++;
            }

            Assembly asm = System.Reflection.Assembly.GetExecutingAssembly();
            string typeName = targetType.FullName;
            object instance = asm.CreateInstance(typeName, true, BindingFlags.CreateInstance, null, constructorArgs, new System.Globalization.CultureInfo("en-US"), null);

            return instance;
        }

        /// <summary>
        /// Creates a new list of transfer objects from a domain object ArrayList
        /// </summary>
        /// <param name="targetType">Transfer object type to be created</param>
        /// <param name="domainObject">The ArrayList of domain objects from which data will be retrieved</param>
        /// <returns>A new transfer object list</returns>
        public static object GetTO(Type targetType, ArrayList domainInstances)
        {
            List<object> instance = new List<object>();
            foreach (object domainInstance in domainInstances)
            {
                //instance.Add(GetTO(targetType, domainInstance as DomainBase<t>));
                instance.Add(GetTO(targetType, domainInstance));
            }
            return instance;
        }

        /// <summary>
        /// Creates a new list of transfer objects from a domain object array
        /// </summary>
        /// <param name="targetType">Transfer object type to be created</param>
        /// <param name="domainObject">The array of domain objects from which data will be retrieved</param>
        /// <returns>A new transfer object list</returns>
        public static object GetTO(Type targetType, T[] domainInstances)
        {
            List<object> instance = new List<object>();
            foreach (T domainInstance in domainInstances)
            {
                instance.Add(GetTO(targetType, domainInstance));
            }
            return instance;
        }

        /// <summary>
        /// Updates a domain object from a equivalent transfer object
        /// </summary>
        /// <param name="TOInstance">The transfer object from which data will be retrieved</param>
        /// <param name="domainInstance">The domain object which will be updated</param>
        public static void UpdateDomainFromTO(object TOInstance, object domainInstance)
        {
            //Iterates through transfer object's properties
            foreach (PropertyInfo piTO in TOInstance.GetType().GetProperties())
            {
                //Try to get domain object property matching transfer object property
                PropertyInfo piDomain = null;
                try
                {
                    //Try to get object's basetype property
                    piDomain = domainInstance.GetType().BaseType.GetProperty(piTO.Name);
                }
                catch { }

                if (piDomain == null)
                {
                    try
                    {
                        //Try to get object's property
                        piDomain = domainInstance.GetType().GetProperty(piTO.Name);
                    }
                    catch { }
                }

                if (piDomain != null)
                {
                    //Only properties mapped to table columns will be copied (primary key + attributes)
                    bool canCopy = false;

                    foreach (object o in piDomain.GetCustomAttributes(true))
                    {
                        if (o is PrimaryKeyAttribute || o is PropertyAttribute)
                        {
                            canCopy = true;
                            break;
                        }
                    }

                    if (canCopy)
                    {
                        object value = piTO.GetValue(TOInstance, null);
                        if (value is ArrayList)
                        {
                            ArrayList list = new ArrayList();
                            foreach (object o in (ArrayList)value)
                            {
                                list.Add(o);
                            }
                            try
                            {
                                piDomain.SetValue(domainInstance, list, null);
                            }
                            catch
                            {
                                throw;
                            }

                        }
                        else
                        {
                            try
                            {
                                piDomain.SetValue(domainInstance, value, null);
                            }
                            catch
                            {
                                throw;
                            }
                        }
                    }
                }
            }
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Marcelo Ricardo de Oliveira
Software Developer
Brazil Brazil
Marcelo Ricardo de Oliveira is a senior software developer who lives with his lovely wife Luciana and his little buddy and stepson Kauê in Guarulhos, Brazil, is co-founder of the Brazilian TV Guide TV Map and currently works for ILang Educação.
 
He is often working with serious, enterprise projects, although in spare time he's trying to write fun Code Project articles involving WPF, Silverlight, XNA, HTML5 canvas, Windows Phone app development, game development and music.
 
Published Windows Phone apps:
 
 
Awards:
 
CodeProject MVP 2012
CodeProject MVP 2011
 
Best Web Dev article of March 2013
Best Web Dev article of August 2012
Best Web Dev article of May 2012
Best Mobile article of January 2012
Best Mobile article of December 2011
Best Mobile article of October 2011
Best Web Dev article of September 2011
Best Web Dev article of August 2011
HTML5 / CSS3 Competition - Second Prize
Best ASP.NET article of June 2011
Best ASP.NET article of May 2011
Best ASP.NET article of April 2011
Best C# article of November 2010
Best overall article of November 2010
Best C# article of October 2010
Best C# article of September 2010
Best overall article of September 2010
Best overall article of February 2010
Best C# article of November 2009

You may also be interested in...

| Advertise | Privacy | Mobile
Web01 | 2.8.140916.1 | Last Updated 15 Nov 2007
Article Copyright 2007 by Marcelo Ricardo de Oliveira
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid