Thursday, August 4, 2011

Setting up a Ubuntu 10.10 machine

My first thought was to start my rails journey on a Win7 machine. There are a few tutorial out there and even an msi package installing ruby and rails for you for windows.... It did not take me long however to realize, that even if you can get rails running on windows, most tools and tutorials are tailored for a Linux based machine. If learning something new, better learn it right, eh?

I am not a Linux expert whatsoever so I wasn't sure where to start. What distribution to install, which version etc... A little bit of research revealed that the Ubuntu installation is a favorite in the Rails community.... Does that mean that I have to install a Linux Ubuntu system from scratch?!? The short answer is no! You can actually download a VM Image of a fully configured Ubuntu 10.10 machine. How neat is that? The only thing left is to install a VMWare player and you're good to go. You have a Ubuntu machine working. Great!

So Friend, don't be afraid to leave the Microsoft world completely and embrace the power of Ubuntu. It's so easy to get started. If you screw up the installation, no big deal, just unzip the downloaded image and you have a clean start! (unless you have a VMWare Workstation which allows you to take snapshot of your machine at any time...in that case, you just need to revert to a snapshot).







Wednesday, August 3, 2011

Learning Ruby and Rails

I have been doing Microsoft Development for most of my career, mostly using .NET and C#. I feel confident in my ability to tackle any project using this platform. It is a great feeling, no question about that, and I am always excited to start a new project.

Of course, even in C#, I am far from knowing everything! There is always something to learn especially with the new features such as the Asynchronous library that will be released in C# 5. But for now, I want to learn what I really don't know about the "other (non-Microsoft) side" of things. There is a lot of noise about Ruby and Rails and a growing demand for Ruby on Rails developers, so learning to build sites with Rails is certainly not a bad idea, is it?

I spent the last few weeks deep diving into ruby and rails, feeling happy by the incredible possibilities offered by Ruby and overwhelmed at the same time by the new syntax and inherent philosophy. There is definitely a steep learning curve when coming from a static language like C#.

Learning by doing is for me the best way to integrate and understand the core concepts of a new technology. So guess what! I will spend a lot of time trying stuff out. Be prepare to see a lot of posts relating my journey to the other side and away from the comfort zone!

Thursday, July 28, 2011

Optimizing components registration in Castle

Some of our users complained that the time needed to start one of our desktop application was too long (~50s). There is a lot of things happening under the hood when starting the application so I decided to use my favorite profiler tool (yeah I know, jetbrain again!) to profile the application.

The new version of the profiler comes with a bunch of new features. Since I wanted to exactly know what was happening and where time was being lost, I went with the high accuracy mode and of course, checked the start profiling immediately since the time spent to start the application is our concerned.


The results were really interesting and I could not really believe it at first: 70% of the time was spent registering components in our IoC Container of choice. Castle! Looking closer at the profiler output, I could see that we were registering close to 1000 components in the container (991 exactly). The registration is (of course) based on some predefined convention (yeah convention again) to register the type automatically in the container. 1000 components is a lot, but nothing too crazy and there is no way so much time should be spent just to register them anyways.


Now look at what happens here. The components validation is taking 96% of the overall registration time. I guess the kernel is always trying to check if a component being registered is valid or not. If you have a lot of invalid components (which happens obviously when registering components with convention), the time spent in validation degenerates to an O(N^2/2) operation! There had to be a way to disable the validation and optimize the registration....

And indeed, I found the OptimizeDependencyResolution! Apparently this is a way to optimize registration, but it breaks startable facility in castle 2.1, which happens to be the version we are using currently. I decided to take the plunge and upgrade to castle 2.5, where a fix was provided. It meant also updating to NHibernate 3.1 and FluentNhibernate 1.2...ARGHHS versioning hell all over again. An hour later, I was back on track and the app was running. At that point, I was so glad that we had integration tests to test our FluentNhibernate mapping etc... Upgrading all at once without that security net would have been a real nightmare otherwise.

Back to our OptimizeDependencyResolution. The only thing that was left to do was to encapsulate the registration with
using (kernel.OptimizeDependencyResolution())
{
//do registration logic here
}
The time to load the application with that one only code change dropped to 9s! Wow now we're talking!

So Dear Reader, don't spend time guessing where you can optimize your code. First only optimize when a performance problem occurs, NEVER BEFORE! Then use a profiler to discover the bottleneck of your application.

Wednesday, July 27, 2011

Test your conventions with reflection

I am not a big fan of using reflection in .NET. Most of the time, people believe that reflection is well known, easy to understand and part of the standard tools available to all .NET developers. I strongly believe that reflection can do more harm than good. Used wisely however, it can be really helpful...let see an example!

In one of the application I am working on, we encapsulate all the user actions changing the underlying domain in command objects, using the well-known command pattern. Each command should be kept into a command history so that one can track at all-time what has changed and how. One requirement to the system is the ability to rollback to any previous state of the project (and thus reverse all changes made since that state) and AT ALL TIME. Yes dear readers, it means that on top of the domain, the history of all command needs to be persisted as well.

We have an in-house Xml Serialization Framework that we use to serialize the commands. In order to serialize a Command, let say a DeleteCommand, we need to define an object implementing the ISerializer<DeleteCommand> , for instance DeleteCommandSerializer. Now we have hundreds of commands in the system. How to make sure that we don't forget to write a serializer for a new command? In other words, how to ensure that our convention "Each command should have a serializer" is met? Write a test!

It's where reflection comes into play:
[Observation]
public void each_concrete_command_should_have_a_defined_serializer()
{
var commandAssembly = typeof(ICommand).Assembly;
var allCommandTypes = commandAssembly.GetConcreteTypesImplementing<ICommand>();

var serializerAssembly = typeof(ISerializer).Assembly;
var allSerializerTypes = serializerAssembly.GetConcreteTypesImplementing<ISerializer>();

var allImplementationType = new Collection<Type>();

foreach(var type in allSerializerTypes)
{
foreach(var typeForGenericType in type.GetDeclaredTypesForGeneric(typeof(ISerializer<>)))
{
if (allImplementationType.Contains(typeForGenericType.DeclaredType)) continue;
allImplementationType.Add(typeForGenericType.DeclaredType);
}
}

var errorList = new List<string>();
foreach(var type inallCommandTypes)
{
if (allImplementationType.Contains(type))
errorList.Add(string.Format("No serializer found for {0}", type));
}

Assert.IsTrue(errorList.Count == 0, errorList.ToString("\n"));
}

Looking at the code above there are a few items I should point out

  1. This will retrieve all the types implementing ICommand and all the types implementing ISerializer. We suppose that all commands are defined in one assembly as well as all serializers. (that might be however the same assembly). We use the useful extension method defined here.
  2. Then we retrieve the actual type used in the open type ISerializer<>. For that I use another extension method, GetDeclaredTypesForGeneric that returns MyType (the so called DeclaredType) for a generic ISerializer<MyType>. If you are interested in the implementation, drop me a line and I will blog about that as well.
  3. Last we want to log the error. Note the use of a list to save the error. The assertion only happens at the very end of the test so that we get the exhaustive list of all commands without a serializer.

Friends, my advice is to always test the convention in your system. That will bring joy and happiness in the long run and enhance your productivity.

Finding types in an assembly implementing another type

The other day I had the need to retrieve the types defined in an assembly that were implementing another given type. How would you do that? Here is my solution:
public static IEnumerable<Type> GetConcreteTypesImplementing<T>(this Assembly assembly)
{
return assembly.GetConcreteTypesImplementing(typeof(T));
}

public static IEnumerable<Type> GetConcreteTypesImplementing(this Assembly assembly, Type typeToImplement)
{
return from type in assembly.GetConcreteTypes()
where type.IsAnImplementationOf(typeToImplement)
select type;
}

public static IEnumerable<Type> GetConcreteTypes(this Assembly assembly)
{
return from type in assembly.GetExportedTypes()
where !type.IsGenericType
where !type.IsAbstractClass()
select type;
}
The code here is fairly simple. The idee is to query all exported type in the assembly filtering out the generic and abstract types. Note that IsAbstractClass is another extension methods:
public static bool IsAbstractClass(this Type type)
{
return (type.IsAbstract || type.IsInterface);
}

Friday, April 1, 2011

Prevent Resharper from adding regions!

Resharper is an amazing tool that I use every day. I could certainly not do without anymore. There is one really annoying thing with it however: Its default behavior is to wrap interface implementation in a region!

Unless your code is being generated automatically, regions are just noise to me. If you need them to make your code easier to understand, I bet that your code is doing way to much and is certainly violating the Single Responsibility Principle.

The good thing with Resharper is that you can configure almost everything! Turning off regions for interface is a bit trickier than expected. I’m sure this has been blogged about thousands of times. I was just asked again how I managed to get rid of them but could not find it, so I wanted to capture it someplace useful.

Follow this steps, and you will be region free:
  • Go to Resharper -> Options
  • Go in the left pane to C# ->Formatting Style ->Type Members Layout
  • Unchecked "Use Default Patterns"
  • A scary XML appears on the right pane. It looks scarier than it is so stay calm
  • Find the section marked by <!--interface implementations-->
  • Find the tag <entry>
  • Remove
    <group>
    <implementsinterface immediate="true" region="${ImplementsInterface} Members">
    </implementsinterface>
    </group>
That's it!!

Thursday, March 31, 2011

Nice Feature in Rhino.Mocks. The Do() handler

I have been working with Rhino.Mocks for quite a while now and believed I knew most of the goodies available in this tool. Today I was proven wrong!

Using the extension methods Stub on a mock object, you can specify the return value for a method when being called. Keep in mind that you do not create an expectation for this method.

A sample code could be something like:
_orderFactory.Stub(x=>x.CreateOrder()).Return(new Order());
Notice that each and every time the method CreateOrder() is called on the mock object _orderFactory, the same static object created in the first method call will be returned.

Now this behaviour is more than enough for most of the tests I write. But there are times, like this morning, where I needed the CreateOrder() method to always return a new instance of Order when called. There is a really easy way to do it. Using the Do() handler:
The signature of the Do() is pretty scary at first. It takes a Delegate. That's right, an old .NET 1.0 Delegate which is not strongly typed. That's also the reason why its use can be really powerful:
_orderFactory.Stub(x=>x.CreateOrder()).Do((Func<Order>)(() =>new Order()))
And that's it! Every time the CreateOrder() method is called, the mock will return a new Order.

On a side note, I don't like to use the word stub or mock in the code, since it tends to decrease the code readability. I have created an extension method that helps make the code easier to understand
public static class RhinoMocksExtensions
{
///
/// Setup a result for the given function call
///

public static IMethodOptions<R> SetupResultFor<T>(this T mock, Function<T, R> func) where T : class
{
return mock.Stub(func);
}
...
}

//using this extension method, stub call would be
_orderFactory.SetupResultFor(x=>x.CreateOrder()).Do((Func<Order>)(() => new Order()));

Sweet!