The official Fatica Labs Blog! RSS 2.0
# Friday, 15 February 2013

In the last post I shown a Publish/Subscribe communication pattern with ZeroMQ and its C# binding library showing an asynchronous way in dispatching messages through many clients. Well this is not the only way we have. Another strategy is to have a listener and many clients sending messages to it and awaiting for response. All this is achieved by changing the Socket type we create.

You can find the code for this example and the previous one here.


Here the code for the client:


After the connect, we start a loop sending a message to the server, and receiving the reply from it.

Here is the server:


Please note the Bind() function, this is the line saying server is listening for calls. Code contains a test, proving messages are handled in sequence even if many client are sending messages in concurrency. This is part of the key point of this communication pattern:


Request/Reply key Point:

  • Client pass without error the Connect call, even if the server is not yet listening.
  • The client send call is never blocking.
  • The client Receive() blocks until server reply.
  • It is not possible to Send another message if no reply from server is received.
  • Server is guarantee to process one request at a time ( queue )

So there is a sort of state on the cannel, and we have some feedback about the fact the recipient handle our messages. If you heard about the Saga pattern you probably guess when this scenario can be used.

Friday, 15 February 2013 19:12:15 (GMT Standard Time, UTC+00:00)  #    Comments [0] - Trackback
C# | communication | ZeroMQ

# Tuesday, 12 February 2013

Zero MQ is a server less message queuing facility that does not require any additional services to work ( ie no MSMQ needing ). I show here an example in how to use that library from C# by creating a small pub subscribe scenario. Just to clarify is a scenario having a publisher sending some messages and one or more subscriber that will be notified of that message.

You can find all the source code for this example here.


In order to get started, we need a wrapper callable for .NET, since ZeroMQ exposes a native interface. I did use clrzmq for the purpose in my project, I did clone my version just to fix some bug in compiling when there is spaces in subdir, so the actual version I use is here.

Then I download the latest stable 3.2.2 RC 2 at the moment I’m writing and launched the setup. The binary after the setup will contain something like this:


Notice the naming containing the –vXXX subfix. this is the C++ Runtime Version the library is built against. Pick the correct one for your system ( you must have a Visual C++ runtime installed )  and rename it as libzmq.dll, since the wrapper expect the dll with this name. Alternatively you can download the wrapper via nuget:

PM> Install-Package clrzmq –Pre

In order to just see the example you can just checkout the example repository.


The example is divided in two (console) application, a publisher and a receiver. Let’s see the sender below:



Really simple, the key point are the SocketType.PUB, meaning we use the socket to publish messages, and the Bind in which we decide an address and a protocol where to listen for connections. Then we start sending some rubbish on the created channel. Message are string, but eventually they are byte[]. The Send overload accepting a string is actually a wrapper additional bonus.

Notice that:

  • No server is required in order to dispatch messages
  • Send is not blocking: independently if there is subscriber or not, Send function exits immediately.

Let’s see the the subscriber:


the key points here are the SocketType.SUB, the subscriber market, the Connect that must match the publisher protocol/address, and the SubscribeAll ( there is a less eager Subscribe that allow to specify a filter for the messages ).

Notice that:

  • You can start/stop a subscriber at any moment, it will be notified soon of the published messages
  • Messages are not queued at all.

Last point maybe is a little confusing if you expect something like MSMQ: there is no messages buffer somewhere storing non consumed messages ( ie there is no Permanent Subscriptions as in ActiveMQ ), if you want that feature you must implement it externally.

So, a great and simple library, having the simplicity,lightness  no service requirement as a pro, but the drawback of needing the Visual C++ runtime and the leak of a permanent subscription out of the box.


I had a chance to test the example codebase here on a Widow7 almost clean machine ( without any VisualStudio in ) and the solution works by XCOPY deploying msvcr100.dll and msvcp100.dll, included into the repository. Taths a great thing and it makes the 0 in the 0MQ being an actual 0 :D

Tuesday, 12 February 2013 15:26:11 (GMT Standard Time, UTC+00:00)  #    Comments [0] - Trackback
C# | communication | ZeroMQ

# Wednesday, 25 July 2012

I just did some new project at work with heavy and extensive usage of data access over legacy databases, and I tried the DapperDotNet micro or/m instead of NHibernate. I just point before the fact that I've already all the infrastructure to map such a legacy DB in NH by using mapping by code and leveraging a lot of conventios in the DB table/field naming, so the mapping work does not make any difference for me, a part the fact that it is not needed with dapper ( or at least, not needed in the Entity based form ) since you just map the data transfer structures. So what's missing from using NH? Lets see:

  • Inheritance I was a little worried about Dapper leak of support for any kind of inheritance concept, but really I managed to do all the requirement without it, having the best dsl for querying the database did the work.
  • Identity Map We have to keep an eye to the fact the identity map does not exist anymore using a micro/orm. This not just in subsequnt queries in the same section, but when we load associations, expecially when the associated class has a lot of data. For example I had an association with an entity containing a big bounch of xml, if I load that association in a dto, I need to manage myself to load it just when the associated id changes.
  • Lazy Collections using Dapper we have to forget such automatic features, basically there is not such a concept, but I really can live without it.
  • Db Schema Create/Update I really miss that just in unit testing. You have to craft the schema by hand in your unit test. In production in my case I have no control for the schema generation *at all* so it is not a problem anyway, but I guess the NH update / generation is not enough for a real DB deployment. You probably need a DB migration in any case.
  • Linq/Hql In fact I miss LinqToNh. Not absolutely Hql. But we have to consider that a big portion of the impedence an OR/M introduces is caused to the creation of a DSL on top of plain SQL.

Let's consider the pure benefit we have from Dapper:

  • Any kind of optimized SQL is easy to submit.
  • Calling an SP handling In/out parametrs is simple as calling a query
  • Multiple resultset are easy to handle ( The Future<> in NH )
  • Bulk operations are easy too ( you still need real bulk if you realaly want to insert big amount of data )
  • Really noticeable increase in performance, due to smart ADO.NET underlayng access and to the fact we control the SQL roundtrip ourself )

So in my opinion: we probably code a little more in the data access phase, but we have more control, there is no a separate "mapping" part, that can be not so easy to mantain, but it really worth the effort to move definitely in the Micro Orm direction.

Wednesday, 25 July 2012 11:32:20 (GMT Daylight Time, UTC+01:00)  #    Comments [1] - Trackback
C# | NHibernate | ORM

# Friday, 20 July 2012

As announced by Scott Guthrie EF is today available as Open Source on Codeplex. As usual I had a first glance at the code to see what's inside. Is a big codebase as you can guess,but even with a first sight it is possible to spot some interesting things to learn. Here my list:

So nothing really complex, just good code snippets. Interesting, they internally uses XUnit for unit testing, not MSTest, and the framework for mocking is MoQ.

Friday, 20 July 2012 10:31:10 (GMT Daylight Time, UTC+01:00)  #    Comments [0] - Trackback
C# | CodeProject

# Friday, 27 April 2012

I described the “typed factory” concept here some days ago. The solution we looked at was requiring the Castle DynamicProxy dependency. If you want something simpler zero dependency and “just working” I creted a little hacking factory: AnyFactory. It is really simple and does not requires any external dependency, and can be integrated in your project by just adding a single file. I provided some documentation on the project wiki. The extension works by crafting a factory implementation using Reflection.Emit. It does not requires to configure anything since a unresolved dependency satisfying some restrictive rule is considered to be a factory, and the implementation is produced in the background.

the rules for an interface to be consider a factory are:

  • It is a public interface
  • Each method name starts with Create
  • Each method return something
  • There is no properties

The name is required to begin with Create, if it contains something after Create, this is considered to be a named binding to solve. Construction parameters can be specified, but there is a restriction: the parameter name should match the implementation constructor parameter name. ANother limitation is that we don’t support the “delegate” factory.

Friday, 27 April 2012 16:54:54 (GMT Daylight Time, UTC+01:00)  #    Comments [0] - Trackback
C# | Programming

# Tuesday, 03 April 2012

I talked about this one file utility here and here. I decided the syntax I create in the last improvement, for allowing the user to customize the exception to throw was not so usable, so I modified it. Now the resulting code to throw a specific exception is:

        /// Classical not null verification, with custom 
        /// exception and message
        public void DoSomethingWithCustomMessage(string arg1)
            Contract.Expect(() => arg1)
                .Throw((n)=>new Exception(string.Format("I'm unhappy to see that {0} is null",n)))


So there is no more any magic formatting, we just need to provide a function returning some kind of exception. The lambda argument (n) is the literal representing the name argument. I also added a wiki page on the project repository, to show the basic usage of the library so at a glance you can see how it works.

Tuesday, 03 April 2012 07:55:51 (GMT Daylight Time, UTC+01:00)  #    Comments [0] - Trackback

# Wednesday, 21 March 2012

Some days ago I came in this issue regarding thread non-safety when using MoQ. So I simple create my own fork on GitHub and solved the issue, that was really easy to do, and as a result I obtained a Mock stable even when mocked methods are called from multiple threads. I created a bounch of test to prove that worked, here below one as a sample:


So with this I made the Mock thread safe at the infrastructure level, that mean no more strange NullreferenceException and others. But what if we want our mock not thread safe? I mean there could be situation in which we want to ensure the system under test calls a certain method from a single thread,  in other word we want the mock to explicitly require single thread access to certain methods. This could happen for example when we are mocking some UI components, but there is such situations every time the object we are mocking is intrinsically non thread safe and the SUT is multithreaded. So I extended the MoQ fluent language from the internal and I obtain something like…  the example below:


So in the setup phase we declare a method ( or a setter, or a getter, as usual ) to be SingleThread(). This yield a mock throwing when the method is called from a different thread from the one which did the setup.

If you are happy with this modifications ( you would for sure find helpful the thread safety by its own ) feel free to check out my code fork on GitHub, in any case I’m trying to have that modification pulled from the main stream.

Wednesday, 21 March 2012 15:53:26 (GMT Standard Time, UTC+00:00)  #    Comments [0] - Trackback
C# | CodeProject | MoQ

# Thursday, 15 March 2012

I’ve already talked about the simple contract checking library here. I did a little improvement that allow us to write such a code:

public void DoSomethingWithCustomMessage(string arg1)
            Contract.Expect(() => arg1)
                .Throw<Exception>("I'm unhappy to see that {0} is null")


Note than {0} is replaced with the name of the argument so the library is refactoring friendly and DRY. The only restriction is that the exception type must support a constructor with a single string argument. Obviously .Throw can be used fluently after each all Expect(). As another minor improvement, even the .Expect can be called now fluently more than once, so multiple check can be done fluently too. The entire repository is on Bitbucket here. In order to use the library you just have to include the single file, but is better to point the repository since the file version can change in subsequent releases.

Thursday, 15 March 2012 16:16:42 (GMT Standard Time, UTC+00:00)  #    Comments [0] - Trackback
C# | CodeProject

# Monday, 23 January 2012

… without writing a LinqToSomething provider, of course. The Expression.<Func<T>> construction is sometimes a little frightening since we suppose to have to write some complex tree navigation in order to achieve the expression behavior, but this is not always true, there is scenarios in which we can use it without any complex tree visit. In this post we will see some real world examples using this strategy.

1) INotifyPropertyChanged without “magic strings”

This interface is implemented in its simplest form:

public string CustomerName
	   return this.customerNameValue;
	   if (value != this.customerNameValue)
		   this.customerNameValue = value;

We can leverage Linq.Expression here by this simple base class:

class PropertyChangeBase: INotifyPropertyChanged
	protected void SignalChanged<T>(Expression<Func<T>> exp)
		if (exp.Body.NodeType == ExpressionType.MemberAccess)
			var name = (exp.Body as MemberExpression).Member.Name;
			PropertyChanged(this, new PropertyChangedEventArgs(name));
		   throw new Exception("Unexpected expression");
   #region INotifyPropertyChanged Members
   public event PropertyChangedEventHandler PropertyChanged = delegate { };

By deriving our class from this one, we can easily notify a property change by writing:


This allow us to leverage intellisense, and it is refactoring friendly, so we can change the name of our property without pain. The first project I seen using this technique was Caliburn Micro, but I’m not sure is the only one and the first. Same technique is used here to test the INotifyPropertyChange behavior.

2) Argument Verification

Really similar to the problem above, we want to avoid:

static int DivideByTwo(int num) 
   // If num is an odd number, throw an ArgumentException.
   if ((num & 1) == 1)
	   throw new ArgumentException("Number must be even", "num");

   // num is even, return half of its value.
   return num / 2;

In this case we are typing NUM, that is the name of the argument, as a literal string which is bad. We would preferably write something like this:

public void DoSomething(int arg1)
	Contract.Expect(() => arg1)

That again give us intellisense and refactoring awareness. You can find he code for this helper class here, and a brief description in this post.

3) The MoQ mocking library

The MoQ library is a .NET library for creating mock objects easy to use that internally leverage Linq.Expression to achieve such a readable syntax:

   mock.Setup(framework => framework.DownloadExists(""))

4) A generic Swap function:

The simplest way in creating a generic Swap function in c# is:

void Swap<T>(ref T a, ref T b)
   T temp = a;
   a = b;
   b = temp;

Unfortunately, this won’t work if we want swap two property of an object, or two elements of an array. We would like to write something like this:

   var t = new Test_() { X = 0, Y = 1 };
   Swapper.Swap(() => t.X, () => t.Y);
   Assert.AreEqual(0, t.Y);
   Assert.AreEqual(1, t.X);

or with arrays:

    int[] array = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    Swapper.Swap(() => array[0], () => array[1]);
    Assert.AreEqual(2, array[0]);
    Assert.AreEqual(1, array[1]);

We can achieve this by a simple helper class using Linq.Expression:

public class Swapper
        public static void Swap(Expression<Func<T>> left, Expression<Func>T>> right)
            var lvalue = left.Compile()();
            var rvalue = right.Compile()();
            switch (left.Body.NodeType)
              case ExpressionType.ArrayIndex:
                  var binaryExp = left.Body as BinaryExpression;
                  AssignTo(rvalue, binaryExp);

              case ExpressionType.Call:
                  var methodCall = left.Body as MethodCallExpression;
                  AssignTo(rvalue, methodCall);
                  AssignTo(left, rvalue);

          switch (right.Body.NodeType)
              case ExpressionType.ArrayIndex:
                  var binaryExp = right.Body as BinaryExpression;
                  AssignTo(lvalue, binaryExp);

              case ExpressionType.Call:
                  var methodCall = right.Body as MethodCallExpression;
                  AssignTo(lvalue, methodCall);

                  AssignTo(right, lvalue);

      private static void AssignTo<T>(T value, MethodCallExpression methodCall)
          var setter = GetSetMethodInfo(methodCall.Method.DeclaringType,methodCall.Method.Name);
              Expression.Call(methodCall.Object, setter, Join(methodCall.Arguments, Expression.Constant(value)))

      private static Expression[] Join(ReadOnlyCollection<expression> args,Expression exp)
          List<expression> exps = new List<expression>();
          return exps.ToArray();

      private static MethodInfo GetSetMethodInfo(Type target, string name)
          var setName = Regex.Replace(name, "get", new MatchEvaluator((m) =>
              return m.Value.StartsWith("g")?"set":"Set";
          var setter = target.GetMethod(setName);
          if (null == setter)
              throw new Exception("can't find an expected method named:" + setName);
          return setter;

      private static void AssignTo<T>(Expression<Func<T>> left, T value)
          Expression.Lambda<Func<T>>(Expression.Assign(left.Body, Expression.Constant(value))).Compile()();

      private static void AssignTo<T>(T value, BinaryExpression binaryExp)
          Expression.Lambda<Func<T>>(Expression.Assign(Expression.ArrayAccess(binaryExp.Left, binaryExp.Right), Expression.Constant(value))).Compile()();

This code leverages a samples by Takeshi Kiriya, I just added the ability in handling array to his own the original code.

5) Unit testing the presence of an attribute

Thomas Ardal talks in this post about how to easily unit test the presence of an attribute on a method of a class,  useful for example in MVC scenarios, or in others AOP circumstances.

A test leveraging his strategy is written as below:

    var controller = new HomeController();
    controller.ShouldHave(x => x.Index(), typeof(AuthorizeAttribute));

So we show five different simple application, I hope you find here some inspiration for your works, and feel free to write about your own ideas and enrich the list.

Monday, 23 January 2012 16:05:16 (GMT Standard Time, UTC+00:00)  #    Comments [0] - Trackback
C# | CodeProject | Linq

My Stack Overflow

Send mail to the author(s) E-mail

profile for Felice Pollano at Stack Overflow, Q&A for professional and enthusiast programmers
About the author/Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2017
Felice Pollano
Sign In
Total Posts: 157
This Year: 0
This Month: 0
This Week: 0
Comments: 124
This blog visits
All Content © 2017, Felice Pollano
DasBlog theme 'Business' created by Christoph De Baene (delarou) and modified by Felice Pollano