Book Review: “ZeroMQ” (PACKT Publishing)


Some days ago I was contacted by a representative from PACKT Publishing asking me to write a review for their last book about the ZeroMQ library.


In 2009 I was looking for a fast, very fast, messaging system for a complex project and I meet ZeroMQ. At that time there was the 1.x version and I wrote a Delphi wrapper for the C dll that some days later has been included in the official ZeroMQ distribution.

Now, after 4 year since then, I’m using ZeroMQ for a lot of things. I’ve talked about ZeroMQ to the popular ITDevCon (The European Delphi Conference), so I’m very happy to write about ZeroMQ another time.

So, back to the book review…

The book title is simply “ZeroMQ”, but the subtitle explains what you’ll really learn from it: “Use ZeroMQ and learn how to apply different message patterns”.

Yes, this book is really a crash course in ZeroMQ. In about 100 pages, this “small but full of interesting things” book, explains all the most useful message patterns implemented in ZeroMQ. Congrats to Faruk Akgul (the author).

Traditional message queuing systems use a broker. However, ZeroMQ is brokerless. In a brokerless design, applications can directly communicate with each other without any broker in the middle. All the complexity is hidden, and handled, by ZeroMQ. In this situation there isn’t the “single point of failure”. In some cases this architecture cannot be used, but when it can be, you can gain a lot of flexibility, speed with no added complexity.

Let’s give a more  deeper overview for each chapter.

Chapter 1: Getting Started

In this chapter there are some informations about the messaging architectures in general (good for newcomers to the topic) and about ZeroMQ messaging (in particular). Some concepts introduced in this chapter are reused a lot in the rest of the book.

In chapter 1 is introduced the first and the simpler ZeroMQ pattern, the request-replay.

Chapter 2: Introduction to Socket

This chapter starts with a nice introduction to the publish-subscribe pattern and the related filtering (ZeroMQ can filter messages with a very simple “match” pattern). Then, the chapter talks about one of the most interesting patterns when speed is important: the pipeline pattern. While is talking about the pipeline, it explain the ZMQ_PULL and the ZMQ_PUSH socket types. At the end of the chapter, there is an introduction to the Valgrind’s tools suite to detect memory leaks in C/C++ programs. In Delphi can be used FastMM or other similar tools for the same thing.

Chapter 3: Using Socket Topology

In this chapter there is a small introduction to the types of Internet Sockets and TCP. There there is a nice comparison between the “plain” sockets and the ZeroMQ sockets.

At the end, there is an introduction to the CZMQ, a small helper library which lets

C developers to code their ZeroMQ applications easier and shorter. For a Delphi programmer there are a number of ZeroMQ wrapper that makes its use really a snap.

Chapter 4: Advanced Patterns

In this last chapter, are introduced some advanced variation of the previously introduced patterns. Then, there is a nice explanation of some critical situations that could happened in a messaging system. To help the programmer to handle this cases there a number of examples of the ZeroMQ “High Watermark” setting. As very last topic, there is a well known problem, the infamous “slow subscribers in a publish-subscribe pattern”.


The “ZeroMQ” book published by PACKT Publishing is a small but very nice book. Can be very useful to all those people that don’t know about messaging or want add the power of ZeroMQ to their messaging knowledge.

As in every single thing, there are good aspects and bad aspects.

This book is good for an introduction but is not so good for advanced users. There are some other ZeroMQ patterns and features that are not explained at all. However, these patterns are not the most used, or are advanced stuff, so this could not be a big issue.

Considering, the price, the contents and the informative density, is a definitely a good book that can be read, and studied, in few hours and could change your way to do things in everyday programming (messaging are very often not used, or used in a bad way, simply because usually is complex to write and maintain a good messaging system).

One of the more nice features about ZeroMQ is that it can use different transportation protocols. The same library and the same code can be used to do messaging between machines, between processes or between threads in the same process (ipc). As last note, ZeroMQ can handle, without much effort, millions of messages per seconds. If you need speed… consider this.

P.S. I’ll translate and publish on this blog, some of the C examples contained in the book, in Delphi. Stay tuned.

How to serialize a TList of objects with Delphi

Some weeks ago a customer asked to me if it is possibile serialize a TList of objects. “Hey, you should use a TObjectList for this”, I said, but he absolutely needs (I dont know why) of a TList.

This is the (simple) sample code tested with Delphi XE2 Update4. Enjoy.

unit Unit4;



  TForm4 = class(TForm)
    Button1: TButton;
    Memo1: TMemo;
    procedure Button1Click(Sender: TObject);
    { Private declarations }
    { Public declarations }

  TPerson = class
    FName: String;
    procedure SetName(const Value: String);
    property Name: String read FName write SetName;

  Form4: TForm4;



{$R *.dfm}

procedure TForm4.Button1Click(Sender: TObject);
  list: TList;
  m: TJSONMarshal;
  json: TJSONObject;
  p1: TPerson;
  p2: TPerson;
  p1 := TPerson.Create;
  p2 := TPerson.Create;
    p1.Name := 'Daniele Teti';
    p2.Name := 'Peter Parker';
    list := TList.Create;

      m := TJSONMarshal.Create;
        // Register a specific converter for field FList
        m.RegisterConverter(TList, 'FList', function(Data: TObject; Field: String): TListOfObjects
            l: TList;
            j: integer;
            l := Data as TList;
            SetLength(Result, l.Count);
            for j := 0 to l.Count - 1 do
              Result[j] := TObject(l[j]); // HardCast from pointer

        json := m.Marshal(list) as TJSONObject;
          Memo1.Lines.Text := json.tostring;

{ TPerson }

procedure TPerson.SetName(const Value: String);
  FName := Value;


The output is, as expected, the following:

{"type":"System.Classes.TList","id":1,"fields":{"FList":[{"type":"Unit4.TPerson","id":2,"fields":{"FName":"Daniele Teti"}},{"type":"Unit4.TPerson","id":3,"fields":{"FName":"Peter Parker"}}],"FCount":2,"FCapacity":4}}

Delphi MVC Web Framework – “Hello World”

This is the first “Hello World” for my Delphi MVC Web Framework.

program DelphiMVCWebFramework;


  MVCEngine in 'MVCEngine.pas',
  BaseController in 'BaseController.pas';

  mvc: TWebMVCEngine;
  mvc := TWebMVCEngine.Create;
  mvc.AddRoute('/', procedure(Context: TWebContext)
      Context.Write('Hello World');

Features list (some of them are in the internal roadmap)

  • Completely MVC
  • Addressable with servername/controllername/actionname?par1&par2
  • Addressable with servername/controllername/actionname/par1/par2
  • Can also use anonymous methods as actions for very simple app (in the sample)
  • Really RESTful (Level 3 of the Richardson Maturity Model)
  • Fully integrable into WebBroker and DataSnap
  • Supports multiple resource rapresentations
  • Completely customizable routing using internal formatting or regex
  • Inspired to ASP.NET, Sinatra, Java Spring MVC, Java Restlet
  • Scriptable views support (Pascal, Razor, Lua)
  • Component based
  • Session support
  • ORM support using dorm
  • Classic TDataSet support
  • State server to support real loadbalancing using reverse proxy
  • Can be deployed as standalone (in the example), ISAPI dll and Windows Service
  • Fully support https
  • More to come…
  • This framework is still under development.

    Are you interested in? :-)


    The project is open source and you can fint it here

Duck Typing in Delphi

During a new dorm feature development, I’m faced a nice problem:

I want to have a generic access to a “kind” of list

Let’s say:

procedure DoSomething(Obj: TMyListType);

But, I want to have that generic access without a Layer Supertype object, because I need to be able to use objects from other libraries or 3rd party. In this case traditional polimorphism is not usable, so I’ve opted for an interface…

procedure DoSomething(MyIntf: IMyListInterface);

Cool, but I want to have that access without any change to that object. So implement an interface is not a viable solution. This is particulary true because the generics data structure in Delphi do not implement an interface. Will be nice to have a fully interfaced list and dictionaries in a future Delphi version.

So, how I could implement a generic access to a generic list?

procedure DoSomething(MySomething: ???);

However, operations on that list are few and well known, so I’ve opted for a “DuckTyping“.

Introducing the duck
Introducing the duck

The name of the concept refers to the duck test, attributed to James Whitcomb Riley, which may be phrased as follows:

“When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck.”

So, in my case, I’ve created an Adapter object wich adapts the external interface (few, well know operations) to the “duck” inside it.

The adapter is useful because I can use the compiler checking that the RAW RTTI access doesn’t allow.

Write an “RTTI adapter” using the new Delphi RTTI, is very simple. This is the code of the class TDuckTypedList that allow to use any object as a “list”. How I can define that the object is actually a list?

The criteria is:

If the object has
– An “Add” method with one parameter of type TObject (or descendant);
– A “Count” property;
– A “GetItem” method that have an integer parameter and return an object;
– A “Clear” method;
then, that object is a list.

So I can write the following:

DuckObject := TDuckTypedList.Create(Coll);  //the adapter
for x := 0 to DuckObject.Count - 1 do

I’ve done some speed tests comparing this way to the classic static way, and the speed is almost the same because the RTTI lookup is cached in the constructor of the adapter. So, so far so good.

This solution is already in use inside the dorm code in a feature branch.

Full code is available in the dorm SVN

Any comments?

ITDevCon 2011, recap

Last Friday ended the third edition of ITDevCon, the European Conference on Delphi and its related technologies.
ITDevCon this year was even bigger and funny.
There have been more present, more sponsors, more speakers, more topics and a lot of people with the desire to learn new things and improve their every day work.

A special thanks goes to all the speakers who participated and the sponsors who have contributed their support to make this conference a major event for the European community Delphi.

I hope that the content and the organization is liked to you at least half of how much it is liked to me.
We are organizing slides, videos and examples for each speech to put it all on-line available to participants at the conference as soon as possible. You will receive an email informing you of how to download all the material available.
In the coming days, on the conference website ( we will post all the pictures we have done in these three days.

If you have any photos that you want to see published, send them to me, we’ll publish it on the official website.

Some friends (and speakers) already blogged about the conference:


Paweł Głowacki

Primoz Gabrijelcic

Marco Cantù

And now, Daniele Teti :-)

ASAP I’ll publish the slides of every speeches.

If you want to see the tweet about the conference, you can go here.

Here’s some photos from the conference.

During the “Country Evening” some of us have been singing with the good “Tex Roses” friend (an italian country band). Probably there are at least 15 video documenting my “performance”!

Here’s the video recorded by Primož (the Delphi Geek)

I thank again all those who have spoken and all those who have attended to ITDevCon.
See you next year.

– Daniele

App Android ITDevCon2011 disponibile sul Market (ITALIAN)

Manca solo una settima all’inizio di ITDevCon2011. Per permettere a tutti gli iscritti (e far decidere chi è ancora indeciso) di sfruttare al meglio i due giorni di intensa formazione, abbiamo appena pubblicato l’applicazione ITDevCON2011 sul’Android Market.
Trevete il programma completo della conferenza, i profili degli speaker e informazioni sugli sponsor.
Inoltre, potrete definire i vostri speech preferiti in modo da essere avvisati subito prima dell’inizio dello speech.
Potrete votare e commentare ogni speech. Potete commentare da subito inserendo le vostre aspettative per lo speech o alcune delucidazioni sul contenuto. Il voto invece sarà possibile solo a speech avvenuto.

Dal punto di vista tecnico, questa applicazione Android utilizza un servizio REST scritto con Delphi utilizzando DataSnap e i Mobile DataSnap connectors per Android.
Per chi fosse interessato al “Making”, durante la conferenza potrà assistere allo speech di Salvatore Sparacino che illustrerà i vari step dello sviluppo e le soluzioni tecnologiche adottate.
Per definire il vostro profilo, votare e commentare, dovrete utilizzare il codice fornito al momento dell’iscrizione. Se non siete partecipanti, o ancora non vi è arrivato il codice di accesso, potete utilizzare l’applicazione come “anomymous”. In questo caso non potrete salvare i vostri speech preferiti Né votare o commentare.


La time table
Speaker details
Dettagli dello speaker (in questo screenshot, DavidI)

Il link da dove installare l’applicazione è il seguente:

Happy ITDevCon2011

ITDevCon2011 Android App

In less that a week, ITDevCon2011 will begin. To allow all members (and to let decide who is still undecided) to take advantage of the two days of intense training, we have just published the application ITDevCON2011 on the Android Market. You’ll find full conference program, speaker profiles and information about the sponsors.
In addition, you can define your favorite speeches in order to be alerted immediately before the start of the speech.

You can vote and comment every speech. You can comment now by entering your expectations for the speech or some clarifications on the content. The vote, however, is allow only after the speech.
From a technical standpoint, this Android application uses a Delphi DataSnap REST service and the DataSnap Mobile Connectors for Android.

For those interested in the “Application Making Of” during the conference may attend the speech of Salvatore Sparacino illustrating the various steps of development and the technological solutions adopted. Very cool! Salvatore will talk about a REAL app, not only a demo!

To define your training profile, add rates and comments, you have to use the code provided at registration. If you’ll not attend, or you have not received your access code, you can use the application as “anomymous.” In this case, you cannot save your favorite speeches or votes or comments.


The time table
Speaker details
Speaker details (here DavidI)

The link to install the application is as follows:

Happy ITDevCon2011!

ITDevCon 2011 Time Table

Yes, it is a bit late, but this year has been really difficult to choose between all the speeches proposals arrived from all over the world.
The new Delphi XE2 version (and the RAD Studio XE2 Suite too) are really full of new cool features and many of the best delphi developers want to show what can be done in Delphi XE2. Great situation!

However, also this year, there will be many talks and many speakers. For the first time there will be 2 plenary sessions with more than one speaker in the main TObject hall. During these sessions all the attendants will be in the same hall and I’m sure that there will be very interesting Q&A time at the end of the sessions.
As usual there will be english and italian speeches. In every time frame you will find a suitable talk for your language.

This year we are glad to have DavidI as a conference speaker. Thanks to be with us David!

As you can see from the time table, there will be many topics, but if you are particulary interested in Firemonkey, LiveBindings, DataSnap and Mobile, you will find a specific sets of speeches about these topics.

In particular:

  • DavidI and Pavel Glowacky will show all the cool stuff available in Delphi XE2
  • Marco Cantù will held an interesting session about Firemonkey development
  • Bruno Fierens will held a 2 parts session about Firemonkey cross-platform component development.
  • I’ll hold 2 sessions about LiveBindings and how to use them with the most popular Data Access Design Patterns
  • Debora Mizzoni (web) and Luca Giacalone (android) will talk about mobile development with RadPHP
  • Salvatore Sparacino will show how to use the datasnap mobile connectors to develop a real-world app
  • and many others on many others topics

This year we’ll have also a “Conference App” very similar to the Google I/O one. With this app you will be able to:

  • Read the time table
  • Set you preferred speeches
  • Read infos about the speakers
  • Comment on speeches
  • Share you comments about itdevcon on facebook and twitter
  • Read infos about our sponsors

This app has been developed using Delphi and the datasnap mobile connectors (for the backend) and an Android device for the frontend. ASAP the app will be published on the Android Market. Here’s some screen shots from the “ITDevCon2011” android app.

The home screen
The time table with all the speeches infos. The starred ones are your preferred speeches.
Speaker's details

The principal developer of this app (Salvatore Sparacino) will explain all parts (datasnap, the connectors, and the android development) in a specific talk. Are you interested in mobile development using Delphi as backend? If yes, you cannot miss his talk!

The time table is available here.
The complete speakers list is available here.

You can register for the event here.

There are interesting discounts for groups, students and for whom will buy RAD Studio XE2 in these days. If you are interested, contact directly our sales office at dir_comm at

See you in Verona!

In the core of LiveBindings expressions of RAD Studio XE2

WARNING! I’ve been authorized by EMBARCADERO to write about RAD Studio XE2.

RAD Studio XE2 is full of nice and exciting features. One of the most awaited of them is the LiveBindings.

The LiveBindings is available to the VCL and the new FireMonkey framework and allows to connect a property object to another using an expression and a set of observers.
Let’s say Edit1.Text “is binded to” Person1.Name also in a bidirectional way. The “link” between a property (or a group of properties) and another property can also be very complex.

The following is an example of a complex bind expression that return a value:

"This is a full name: " + Trim(ToUpperCase(FirstName)) + ", " + Trim(ToUpperCase(LastName))

I’ve waited LiveBindings for ages and now they are here!

So, let’s look a deep inside to the core of livebindings expression evaluator,
the TBindingExpression.

The TBindingExpression is an abstract class that allows to evaluate an expression. But, what’s an expression? An expression is a string that return, or not return, a value. You could see an expression as a little function or procedure.
To explain the concept, I’ve build a simple expression interpreter using an XE2 beta version.

It is very simple but shows the power of expression engine.
This is the scriptengine while evaluates a simple arithmetic expression.

The expression engine is not only a “static” evaluator. Using the powerful Delphi RTTI introduced in Delphi 2010, you can also allows the expression to “read” and “call” property and method of your Delphi objects!!

So, now, some code is needed.

As you can see, you can “register” some association between a real object and an alias in the expression. So, if my object are declared as the following:

I can use a expression as the following:

Going further, you can call methods in your expression!

So, if you have methods declared as following:

You can use the following expression:

Obviously, when you link a property to another you should not use dialogs in the expressions, but this feature is VERY powerful.
You can create different expression and use them as a custom calculator for specific business rules. The expressions are strings, so you can store them in a file or in a database and use them as needed. The expression engine is not a complete scripting language, but it can be used (and abused) in a very broad range of situations.

For complex business rules, I hate the classic chain


so I usually use a DomainModel that use datasets only to read data.

The LiveBinding allows me to use (for complex business rules) the following chain


This is only an introduction to the LiveBingind engine. ASAP I’ll post other articles about it.

I’ll talk about the livebinding engine at the ITDevCon2011 conference. Will be you there?

RAD Studio XE2 will be officially presented all over the world during the “RADStudio XE2 World Tour”.
You can find the list of all launch events in the RADStudio XE2 World Tour page.

I’ll be a presenter at 3 launch events in Italy and United Arab Emitates.
These are the events where I’ll be (click to register):

  • 19th Dubai, United Arab Emirates
  • 21nd Milan, Italy
  • 22nd Rome, Italy

Stay tuned.

DataSnap Mobile Connectors in RAD Studio XE2

WARNING! I’ve been authorized by EMBARCADERO to write about RAD Studio XE2.

RAD Studio XE2 is full of nice and exciting features. One of the most interesting IMHO is the DataSnap extension called “Mobile Connectors”.

In the past, I’ve talked about connecting and using your datasnap REST service with Android, creating ad-hoc json messages and manually parsing the returned json messages. With RAD Studio XE2 this is no longer needed. If you have a DataSnap REST service, you can automatically generate the proxy connector for the major mobile platforms. Yes, just like you have been doing with Delphi or C++ since Delphi 2010.

DataSnap XE2 version supports 4 mobile platforms:

  • Android (Using Java)
  • BlackBerry (Using Java)
  • Windows Phone (Using C#)
  • iOS 4.2 (Using ObjectiveC)

If you want to enable your DataSnap server for the Mobile Connectors you have to explicitely check the feature in the “New DataSnap Server” wizard.

The generated proxies support all the standard Delphi types and maps them to the native target language. Some of the most used Delphi types (e.g. TStream, TDBXReader and so on) have been rewritten in the target language to allows a greater compatibility and a simpler programming interface. The functionalities of the various Delphi classes are not-one-to-one with the Delphi version, but  similar.

From a remote (or local) machine you can download the generated proxy and all the required files using a tool called “Win32ProxyDownloader.exe” which is in the bin folder of your RAD Studio installation. In my FieldTest version, this tool called without parameters, shows its help.

As usual you should have the RAD Studio bin folder in your PATH environment variable, so you can change your current directory to where you want the proxy and write this command in a commandprompt window:

Win32ProxyDownloader -language java_android -host localhost:8080

The proxy and all the needed files are ready in the current directory.

Mat DeLong wrote a very nice Eclipse plugin to use the proxy downloader directly from Android or BlackBerry development environment. You can find this plugin here.

You know that Android is my preferred mobile platform, don’t you?

So, let’s go with an Android example.

To use the generated java proxy, in an Android client application I can write something like this:

//Create the connection
connection = new DSRESTConnection();
//Create the proxy
proxy = new DSProxy.TServerMethods1(connection);
//Use a simple remote method
int sum = proxy.Sum(1,4));
//Use a complex remote method
TStream inStream = null;
TStream outStream = null;
String s = "abc";
inStream = new TStream(s.getBytes());
outStream = proxy.DoSomethigWithATStream(inStream, sum, "Hello DataSnap Mobile Connectors");
//here I can use the java TStream type

All the custom Delphi types (e.g. TPerson) are mapped on the target platform as TJSONObject. All the TJSONValue hierarchy has been ported, with a very similar interface, to the target platform as a wrapper of the native JSON classes.

So, you can write code as the following (Java on Android):

TJSONObject jobj = new TJSONObject();
jobj.addPairs("firstname", "Daniele");
jobj.addPairs("lastname", "Teti");
jobj.addPairs("age", 31);
jobj.addPairs(new TJSONPair("nickname", new TJSONString("Spiderman")));
if (jobj.has("firstname"))

All the proxies work in a similar way except for the Windows Phone one. Indeed, the WP proxy is asynchronous because Microsoft does not allow a sinchronous http request in the main thread. All the proxies are thread safe.

The proxies are generated on the fly by a set of specialized writers. The TDSProxyGenerator component is in charge of generate the actual proxy code in the target language/platform using one of the specialized generators.

In the next figure you can see all the available proxy generators. Some of them are there since Delphi XE but all the mobile platforms have been added in XE2.

That’s all for now.

RAD Studio XE2 will be officially presented all over the world during the “RADStudio XE2 World Tour”.

You can find the list of all launch events in the RADStudio XE2 World Tour page.

I’ll be a presenter at 3 launch events in Italy and United Arab Emitates.

These are the events where I’ll be (click to register):

RAD Studio XE2 had a lot of new features. This is really the BEST ever Delphi version since version 1.

I’ll blog about other XE2 features mostly Delphi related (as usual) so stay tuned.