Saturday, August 30, 2014

F# Sydney - Reaching Goals and Pipelining Operator

In the last F# Sydney meeting I gave a quick session titled "Write Clean Code using the Pipelining Operator in F#". It is basically a short introduction to the pipelining operator in F#, it is only 7 mins. Here it is the video:

Nelson Lin gave a nice presentation titled "Reaching personal goals with F#, literally!" where he showed how to use discriminated unions, record types, functional lists and units of measure in a real application. Here you can watch the recording:

And Troy Kershaw (@troykershaw) presented F# news:

The main topic for our next meeting is "Using F# in C# Projects" by Brendan Duffy. Also Troy Kershaw will be presenting some cool tips for Xamarin in F#.

If you are in Sydney come and join us!, if you are not, don't worry, we will publish the videos in a few days.

Saturday, August 23, 2014

F# Sydney - Pure Functions and Option Types

A few weeks ago Troy Kershaw and I started organising  the F# User Group Sydney.

If you like functional programming (or want to learn) and you are a .net developer, then F# is the perfect language for you, join the group!

In our first meeting we had two presentations:

Stay pure and don't become a mutant
by Troy Kershaw @troykershaw 

Using option types in F#

Saturday, August 9, 2014

Introduction to Domain-Driven Design

Recently I gave a presentation at the DDD Melbourne conference about Domain-Driven Design. It was a quick introduction to the topic, inspired by Vaughn Vernon's book. Here it is the recording (I apologise for the audio quality).

Some of the snippets shown in the presentation are simplified to help beginners to understand the concepts. One clear example is the one related to Domain Events. Although you can raise events the way it is explained in the presentation, a much better approach is the one explained by Jimmy Bogard in this post. The reason why I prefer Jimmy's solution is that it allows you to handle events after the Aggregate is persisted (thanks to @lavinski for the reference).

Monday, December 12, 2011

Metrics in Brownfield Applications

Brownfield applications are everywhere, and as we all know, in most of the cases their codebases are quite messy.

During the last weeks, I have been reading a really nice book called "Brownfield Application Development in .Net" (by Kyle Baley and Donald Belcham). If you are currently working in a brownfield project and have the feeling that you could improve your career finding another job, I would recommend you to read this book first. And then, if after reading it you can't improve the application, you can go and find a better job. As they say, "change the environment, or change the environment" :).

Working in a brownfield project means that you have a version of the application running in production, probably a large amount of bugs to fix, some new features to add and a lot of places where the code could be improved.

So now the question is: how can we convince our manager to let us spend some of our time improving the existing code instead of adding new features?

Certainly that is not an easy task, but here there are some good reasons to do it:
  • Experienced developers don't want to touch messy codebases, so your manager will end up having a lot of junior developers and staff turnover. 
  • Changing existing features or adding new ones is easier when the codebase is clean (and probably the amount of time required is less). 
  • When developers are proud of the codebase, they are more committed with the quality and don't let anyone to mess it up. 
So, how do metrics can help to achieve this? Well, managers love numbers, if they see numbers, they can measure progress, they can show graphs to their bosses and they can understand (or at least try to) how the application is improved.

Here you have a list of metrics that can be useful in a brownfield application (for more details, see chapter 5 of the book):
  1. Code Coverage: percentage of the code that is covered by tests. 
  2. Cyclomatic Complexity: how complex is the application, measuring the numbers of paths in the code (if, loops). 
  3. Class Coupling: how dependent are the classes on other classes (there are two types: afferent and efferent). 
  4. Cohesion: how strongly-related are functions and responsibilities. 
  5. Distance form the main sequence: using abstractness and instability determines which classes are in the zone of pain and which ones are in the zone of uselessness. 
  6. Depth of inheritance: how many levels of inheritance the classes have. 
  7. Maintainability Index: using complexity and lines of code determines  how maintainable the code is. 

Selecting and measuring some of these metrics will help you to understand which are the pain points and will allow you to show your manager the improvements the team has done.

For more information about metrics you can check this post of Scott Hanselman and this document about NDepend metrics.

As a final thought, just a warning, metrics are just that: metrics. They should be applied with common sense. Be careful managing the manager's expectations and be sure that the entire team agrees with them.

Wednesday, July 20, 2011

MsmqException (0xC00E0051) 60 seconds after a WCF Service is executed

I know that this is the type of posts that only few people will find interesting.
But so many times I googled about some weird exception message, found that another developer wrote about it and saved me hours of work, that now, after spending several days trying to solve this issue, I feel an obligation to post about it.


When using NetMsmqBinding with a transactional queue and a Service is exposed with more than one Endpoint (two o more svc files with the same service type defined in the markup), a MsmqException is sometimes thrown just 60 seconds after the message is processed.

<%@ServiceHost language="c#" Debug="true" Service="Service" %>

<%@ServiceHost language="c#" Debug="true" Service="Service" %>

<service name="Service">
  <endpoint contract="IService1" binding="netMsmqBinding" 
    address="net.msmq://localhost/private/MsmqService/Service1.svc" />
  <endpoint contract="IService2" binding="netMsmqBinding" 
    address="net.msmq://localhost/private/MsmqService/Service2.svc" />

public class Service : IService1, IService2 {...}

System.ServiceModel.MsmqException (0xC00E0051): An error occurred while receiving a message from the queue: Unrecognized error -1072824239 (0xc00e0051). Ensure that MSMQ is installed and running. Make sure the queue is available to receive from. at System.ServiceModel.Channels.MsmqInputChannelBase.TryReceive(TimeSpan timeout, Message& message) at System.ServiceModel.Dispatcher.InputChannelBinder.TryReceive(TimeSpan timeout, RequestContext& requestContext) at System.ServiceModel.Dispatcher.ErrorHandlingReceiver.TryReceive(TimeSpan timeout, RequestContext& requestContext)

Note: You won't see the exception unless you enable the WCF Trace (system.diagnostics) or add an IErrorHandler.


This issue occurs because the SMSvcHost.exe is activating two ServiceHost instances using the *same* endpoint when a new message arrives.

While the first instance receives and process the message, committing the corresponding COM+ transaction, the second instance creates another COM+ transaction and waits for another incoming message.

After 60 seconds, the second transaction is aborted (COM+ timeout error 0xC00E0051) and the exception is thrown.


Instead of creating one Service with two Endpoints, you need to create two separate Services with just one Endpoint each of them.

<%@ServiceHost language="c#" Debug="true" Service="Service1"%>

<%@ServiceHost language="c#" Debug="true" Service="Service2"%>

<service name="Service1">
  <endpoint contract="IService1" binding="netMsmqBinding" 
    address="net.msmq://localhost/private/MsmqService/Service1.svc" />
<service name="Service2">
  <endpoint contract="IService2" binding="netMsmqBinding" 
    address="net.msmq://localhost/private/MsmqService/Service2.svc" />

public class Service1 : IService1 {...}
public class Service2 : IService2 {...}

After doing that, only one instance of the ServiceHost is created, so the COM+ timeout exception is not thrown anymore.

I have created a bug in

Additional Information

When the exception is thrown, sometimes the ServiceHost faults and the SMSvcHost.exe process doesn't call it again.

The following fix seems to solve this issue: 2504602 (download).

Another way to solve this is to attach a handler to the ServiceHost.Faulted event and re-create the ServiceHost every time this happens (for more details see this link).

Monday, June 20, 2011

Converting any object to dynamic

There are some scenarios in which it is useful to convert an already created object to a dynamic one, so then we can take advantage of the Dynamic Language Runtime introduced in .Net 4.0.

Two common scenarios where this conversion is useful are:
  • Passing an anonymous type to another method/object.
  • Adding a new property to an existing object.
The following code converts any object to an ExpandoObject reading all the properties of the former and adding them to the latter.

public static class DynamicExtensions
    public static dynamic ToDynamic(this object value)
        IDictionary<string, object> expando = new ExpandoObject();

        foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(value.GetType()))
            expando.Add(property.Name, property.GetValue(value));

        return expando as ExpandoObject;

Using ToDynamic() to pass an anonymous type to another method

IEnumerable<dynamic> goldCustomersWithZipCode = Customers
  .Where(c => c.Type == CustomerType.Gold)
  .Select(c => new { c.Id, c.Name, c.Address.ZipCode  }.ToDynamic());


Using ToDynamic() to add a new property

Customer customer = Customers.First(c => c.Id == 1);
dynamic customerWithLastPurchase = customer.ToDynamic();
customerWithLastPurchase.LastPurchase = customer.Purchases.Last();


Thursday, April 21, 2011

Entity Framework POCO Proxies in Asp.Net MVC

As many of you already know, the MVC framework has the ability of creating a model instance each time an http post is executed. In the following picture you can see that the component that performs that task is the ModelBinder.

It is also true that the way in which Entity Framework implements "lazy load" on POCOs is replacing the real objects with proxies. So when the context returns an entity from the database, a proxy is returned instead of the real entity (for more information about EF proxies just follow this link).

But, what if the entity is not created by the context? How can the ModelBinder create a proxy instead of the real entity?

In order to do that, we need to call the Create method of the EF DbSet and it will create the proxy for us. The following snippet shows how:

var productProxy = modelContext.Products.Create();

Now let's put this behavior inside our own ModelBinder:

public class EntityModelBinder : DefaultModelBinder
    protected override object CreateModel(ControllerContext controllerContext,
                                          ModelBindingContext bindingContext, 
                                          Type modelType)
        // Get the EF context using an IoC container
        var modelContext = DependencyResolver.Current.GetService<IModelContext>();

        var set = modelContext.Set(modelType);

        if (set != null)
            return set.Create(modelType);

        return base.CreateModel(controllerContext, bindingContext, modelType);

Finally, we need to configure our new ModelBinder in the Application_Start (Global.asax).

public class MvcApplication : System.Web.HttpApplication
    protected void Application_Start()
        ModelBinders.Binders.DefaultBinder = new EntityModelBinder();

So now, we can use the lazy load feature inside our controllers:

public class ProductController : Controller
    public ActionResult Edit(Product product)
        modelContext.Entry(product).State = EntityState.Modified;

        // Use "lazy load" to get the Category object from the DB
        var threshold = product.Category.PriceThreshold;


The source code of this sample can be downloaded from this link (MVC v3 + EF v4.1).