Monthly Archives: March 2010

Sort projects alphabetically in Visual Studio

It is a well-known bug in Visual Studio that projects in solution folders are not sorted alphabetically. In solutions with a lot of projects this is often a problem, because it’s kind of hard to find the project you need. So I needed a way to permanently sort projects in solution folders, and it’s actually very easy to do.

Let’s say you have the following visual studio solution:

The project AAA was added after the project ZZZZZZ, so it’s not alphabetically sorted. In order to sort it, right click the ZZZZZZ project and select Rename. Then select another project to end the edit. As you will see, the projects will be sorted:

And then, and this is important, be sure to collapse the solution folders, and then quit and restart Visual Studio. You will then see that the projects remain sorted!

Clone objects

Today a collegue asked for a clean way to clone objects in C#,  so that you really have different objects instead of a reference copy . So imagine that you have a class Employee as follows:

public class Employee
{
public string FirstName { get; set; }
public string LastName { get; set; }
}

and you would copy it:

Employee original = new Employee()
{
FirstName = "Homer",
LastName = "Simpson",
};
Employee copy = original;
copy.FirstName = "Marge";
Console.WriteLine(string.Format("{0} {1}",
original.FirstName, original.LastName));
Console.WriteLine(string.Format("{0} {1}",
copy.FirstName, copy.LastName));

Changing the first name of the copied object obviously also changes the first name of the original object, because it has been copied by refererence and so original and copy refer to the same object:
 

And this was not wat we wanted.
To solve it, we first write an extension method that will be available on each class that implements the ICloneable interface:
 
static class Extensions
{
public static T Clone<T>(this T objectToClone) where T : ICloneable
{
return (T)objectToClone.Clone();
}
}
 
Next we have to make the Employee class implement the ICloneable interface:
 
public class Employee : ICloneable
{
public string FirstName { get; set; }
public string LastName { get; set; }

#region ICloneable Members
public object Clone()
{
return new Employee() {FirstName = FirstName, LastName = LastName};
}
  #endregion
}

And if we now use the Clone method like:
 
Employee copy = (Employee)original.Clone();

then the new object is really a copy of the original:
 

If you want to clone a list of objects, add an extension method like this:

static class Extensions
{
public static IList<T> Clone<T>(this IList<T> listToClone)
where T : ICloneable
{
return listToClone.Select(item => (T)item.Clone()).ToList();
}
}

and to clone this list is then very simple:

IList<Employee> copiedList = originalList.Clone();

This example clones only the Employee object (known as shallow copy, see here), but what if the Employee class contains other reference types? In this case we have to implement a deep copy, meaning that every subclass has to implement ICloneable too, for example, if you have a City:

public class City: ICloneable
{
public string CityName { get; set; }
#region ICloneable Members
public object Clone()
{
return new City() { CityName = CityName };
}
#endregion
}

then Employee has to clone it like:

public class Employee : ICloneable
{
public string FirstName { get; set; }
public string LastName { get; set; }
public City City{ get; set; }
#region ICloneable Members
public object Clone()
{
return new Employee() {FirstName = FirstName,
LastName = LastName, City = (City)City.Clone() };
}
#endregion
}

We can do one other improvement. As you see we always have to cast the Clone operation to its actual type. To solve  that we can create a generic ICloneable interface:

interface ICloneable<T> : ICloneable
{
new T Clone();
}

and adapt the classes to it:

public class Employee : ICloneable<Employee>
{
public string FirstName { get; set; }
public string LastName { get; set; }
public City City{ get; set; }
#region ICloneable<Employee> Members
Employee ICloneable<Employee>.Clone()
{
return new Employee() { FirstName = FirstName,
LastName = LastName, City = City.Clone() };
}
#endregion

#region ICloneable Members
object ICloneable.Clone()
{
return new Employee() { FirstName = FirstName,
LastName = LastName, City = City.Clone() };
}
#endregion
}

public class City : ICloneable<City>
{
public string CityName { get; set; }
#region ICloneable<City> Members
public City Clone()
{
return new City() { CityName = CityName };
}
#endregion

#region ICloneable Members
object ICloneable.Clone()
{
return new City() { CityName = CityName };
}
#endregion
}

Castle MicroKernel/Windsor QuickStart 2: LifeStyle and LifeCycle

…continued from part 1.

Objectives

In this Hands-On Lab, you will be introduced to the Castle MicroKernel/Windsor framework. In particular, you will:
  • Understand LifeStyle
  • Understand LifeCycle

System requirements

You must have the following items to complete this lab:
  • Microsoft Visual Studio 2008 SP1 (professional edition)

Prequisites

You must have the following skills to understand this lab:
  • Fundamental knowledge of software development in .NET 3.5
  • Basic knowledge of Castle

Understand LifeStyle

LifeStyle is a strategy that is related to an instance of a component. The supported lifestyles are:

  • Singleton: only one instance will be created for the whole life of the container. This is the default lifestyle.
  • Transient: for each request a new instance if the component is created
  • PerThread: for each thread there exists only one instance of a component
  • Pooled: Instances will be pooled to avoid unnecessary constructions
  • Custom: the instantiation of components is handled by your custom ILifestyleManager implementation

The default lifestyle is singleton. To indicate which lifestyle you want to use, you can use attributes to decorate the class:

[Transient]
public class CustomerRepository : ICustomerRepository
{

}

or in the configuration file:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section
name="castle"
type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler,
Castle.Windsor"
/>
</configSections>
<castle>
<components>
<component
id="customer.business"
service="CastleExample.ICustomerBusiness, CastleExample"
lifestyle="transient"
type="CastleExample.CustomerBusiness, CastleExample" />
<component
id="customer.repository"
service="CastleExample.ICustomerRepository, CastleExample"
lifestyle="transient"
type="CastleExample.MockCustomerRepository, CastleExample" />
</components>
</castle>
</configuration>

I prefer to do it in configuration because otherwise the code will be coupled again to the Castle container, or, in complicated projects, it may be handier to do it in code but in that case, create specific classes that are responsible for these configuration tasks, so that in your code you have as little as dependencies to Castle as possible.

So try this: add a transient lifestyle to the components in the configuration file, and to see the effect, modify the constructor of CustomerBusiness and add constructors to CustomerRepository and MockCustomerRepository as follows:

public class CustomerBusiness : ICustomerBusiness
{
private ICustomerRepository customerRepository;
public CustomerBusiness(ICustomerRepository customerRepository)
{
// using constructor injection the concrete customer repository is injected
this.customerRepository = customerRepository;
Console.WriteLine("CustomerBusiness constructor");
}

}

public class CustomerRepository : ICustomerRepository
{
public CustomerRepository()
{
Console.WriteLine("MockCustomerRepository constructor");
}

}

public class MockCustomerRepository : ICustomerRepository
{
public MockCustomerRepository()
{
Console.WriteLine("MockCustomerRepository constructor");
}

}

Modify Program.cs:

static void Main(string[] args)
{

// Use business
UseRegisteredBusiness();
UseRegisteredBusiness();
UseRegisteredBusiness();
}

If you run the application, you will notice that each constructor is only called once and so there is only one instance created of the components for all calls:

Change the configuration that components use the transient lifestyle, and then run the application again to see the difference:

Now for each call of the business component, the constructors are called, which means that new objects are created for each call.

Understand LifeCycle

On the other hand there is LifeCycle, which is a strategy that is related to the different phases of an instance. It means that we can implement a number of interfaces; and these implementations are executed at the right time. Out of the box there are two groups of lifecycles:

  • Commission: these are executed when the component is being created. Interfaces are:
    • Castle.Model.IInitializable
    • System.ComponentModel.ISupportInitialize
  • Decommission: these are executed when the component is being destructed. Interface is:
    • System.IDisposable

So, bottom line: if you implement one of these interfaces for your component, Castle will take care of calling your implementations at the right time. Notice that if you use these, the coupling to Castle container will be higher.