JSON support in Delphi2010, a simple example

During last ITDevCon in Verona (ITALY) I talked in a session with title “Marshal and UnMarshal in Delphi 2010″ (we have published some photos about this great conference here).
In the first part of the session I’ve talked about JSON and many attendees were very interested in JSON and his application in everyday programming. I’m a real JSON fan so I decided to write this post about JSON support in Delphi2010. In my session I talked about serialization and deserialization, in this post I’ll show an example of code to do some JSON generation.

program JsonTypes;
  Obj, RestoredObject, JSON: TJSONObject;
  arr: TJSONArray;
  json := TJSONObject.Create;
    WriteLn('Empty JSON Object: ' + sLineBreak,json.ToString);
    json.AddPair('FirstName', TJSONString.Create('Daniele'));
    WriteLn('Simple JSON Object with property: ' + sLineBreak, json.ToString);
    json.AddPair(TJSONPair.Create('LastName', 'Teti'));
    WriteLn('Simple JSON Object with 2 property: ' + sLineBreak, json.ToString);
    arr := TJSONArray.Create;
    arr.Add('Via Roma, 12');
    json.AddPair(TJSONPair.Create('Contacts', arr));
    WriteLn('JSON Object with a property array: ' + sLineBreak, json.ToString);
    obj := TJSONObject.Create;
    json.AddPair('MyUndefinedPersonObject', obj);
    WriteLn('JSON Object with a nested Object: ' + sLineBreak,json.ToString);
    Write('Writing JSON object to file [jsonfile]...');
    RestoredObject := TJSONObject.ParseJSONValue(
      ) as TJSONObject;
    WriteLn('Readed JSON object from file: ' + sLineBreak, RestoredObject.ToString);
    json.Free;  //Every contained object is automatically freed
  readln; //If you want to see the output while in Delphi IDE

JSON is a lightweight data-interchange format and in Delphi 2010 you have full support for it with the built-in DBXJSON unit.

DataSnap Filters Compendium

What’s DataSnap Filters Compendium

DataSnap Filters Compendium (DSFC) is a compendium of 9 filters for DataSnap 2010.
The filters are divided into 3 groups:




HASH filters
The HASH filters helps avoid to any spiteful person to modify datasnap message through an “Man in the middle” attack (http://en.wikipedia.org/wiki/Man-in-the-middle_attack).
Functioning is basing on an easy principle. After sending the message, the filter calculates the hash of the message and tags along it to the message. When the message gets to destination, the filter recovers the hash calculated by the client and recalculates it on the remaining part of the message.
If the part of the extrated hash (calculated at the beginning) and the hash recalculated to the end are equal, the message hasn’t change.
To avoid someone could modify the message and also recalculates the hash, after calculating the hash, a GUID is tagged along to the message, which just the sender and the receiver know.
This kind of filters DOES NOT AVOID THE UNAVOIDED READING OF DATA,it avoids just the modification.

CIPHER filters
The CIPHER filters are the most interesting filters. Many datasnap users have requested a built-in system to get the data transmission safe. This set of filters colud be the answer.
In the actual version I’ve implemented Symmetric-key algorithms. Maybe I’m going to develop of Asymmetric-key algorithms filters.
Implemented algorithms features are well known, I list them as follows just to be completed:

Blowfish has a 64-bit block size and a variable key length from 32 up to 448 bits.
The filter version has a keysize = 56 byte.

AES Round 2.
AES has a fixed block size of 128 bits and a key size of 128, 192, or 256 bits, whereas Rijndael can be specified with block and key sizes in any multiple of 32 bits, with a minimum of 128 bits and a maximum of 256 bits.
The filter version has a keysize = 32 byte.

Triple DES with 24 byte Blocksize, 24 byte Keysize 168 bits relevant
The filter version has a keysize = 24 byte.

Triple DES with 8 byte Blocksize, 24 byte Keysize 168 bits relevant
The filter version has a keysize = 24 byte.

COMPRESS filters
Actually the LZO compression is the only one that exists, and is one of the faster compression algorithms.
The compression ratio compared to the ZLib is worse but about 3 times faster (as the table in next paragraph shows).

DSFC has a huge suite of unit tests and speed tests.
The speed tests show how filters are fast and how the data stream size is affected by their work. Follow table contains results of speed test execution (DSFCSpeedTest) on my workstation. If you want give a meaning to those numbers, see the code of the speed test 🙂

== HASH FILTERS == 1000 iterations
MD5             =  161ms (stream size:  8304 byte, filtered stream size:  4184 byte)
MD4             =   99ms (stream size:  8304 byte, filtered stream size:  4184 byte)
SHA1            =  145ms (stream size:  8304 byte, filtered stream size:  4192 byte)
SHA512          =  344ms (stream size:  8304 byte, filtered stream size:  4280 byte)

== CIPHER FILTERS == 1000 iterations
Blowfish        =  898ms (stream size:  8304 byte, filtered stream size:  8304 byte)
Rijndael        =  941ms (stream size:  8304 byte, filtered stream size:  8304 byte)
3TDES           = 1729ms (stream size:  8304 byte, filtered stream size:  8304 byte)
3DES            = 1757ms (stream size:  8304 byte, filtered stream size:  8304 byte)

== COMPRESS FILTERS == 1000 iterations
LZO             =   79ms (stream size:  8304 byte, filtered stream size:  1113 byte)
ZLibCompression =  295ms (stream size:  8304 byte, filtered stream size:   799 byte)

Last speed test is for the only filter included in Delphi2010. It’s included only for compare times and data stream size with the other filters.

After you install DataSnapFiltersCompendium.bpl you will see following filters into the “Filters” property

New filters registered by DSFC
New filters registered by DSFC

Cipher filters have only one property for the encription key

Encryption key for the cipher filters
Encryption key for the cipher filters

Project Source Contains

  • Full Filters Code
  • Unit Test
  • SpeedTest

Download DataSnap Filters Compendium

P.S. I’ll be at ITDevCon… and you? 🙂

My AMQP Delphi wrapper is in the standard 0MQ distribution

Yes, this is a nice news!
My AMQP Delphi wrapper for 0MQ is officially included into the distribution of 0MQ.
Now sources are managed into the main svn trunk.
You can read the news in the project’s main page.
You can see the code here.

In the upcoming greatest Delphi conference ITDevCon, I’ll have a talk about MoM (Message oriented middleware) and I’ll talk about ZeroMQ too.

Using AMQP from Delphi with ZeroMQ

The Advanced Message Queuing Protocol (AMQP) is an open standard application layer protocol for Message Oriented Middleware (MoM).

The defining features of AMQP are message orientation, queuing, routing (including point-to-point and publish-and-subscribe), reliability and security.

The good news about AMQP is that AMQP mandates the behaviour of the messaging provider and client to the extent that implementations from different vendors are truly interoperable, in the same way as SMTP, HTTP, FTP, etc. have created interoperable systems.

In a so “Open” market, live an interesting project called ZeroMQ.

In a my recent Delphi project, I must choice a thin and fast messaging system, ZeroMQ has been the choice.

However, ZeroMQ has not the Delphi client for talking with the broker, so I decided to write my own.

ZeroMQ is very fast but doesn’t support some enteprise features like users management and message persistence, but is very simple to use and to intergate in a legacy system.

For example, with my wrapper, a simple “sender” is like following:

zmq := TZeroMQ.Create;
ex := zmq.CreateLocalExchange('MyExchange', zmqStyleDataDistribution);
zmq.Bind('MyExchange', 'GlobalQueue');
zmq.Send(ex, 'Hello World From Delphi');

And a simple receiver is simple as follow:

zmq := TZeroMQ.Create;
ex := zmq.CreateLocalQueue('LocalQueue');
zmq.Bind('GlobalExchange', 'LocalQueue');
zmq.Receive(msg, msgtype, msgsize, zmqBlocking);
WriteLn(msg);  //we are in a console application

In the distribution there are a complete set of examples including a simple “Chat” application.

ZeroMQ is primarily intended to power stock trading business, this is the reason becouse is very fast.

To use ZeroMQ you need the ZeroMQ server downloadable from http://www.zeromq.org/ where you can find additional info about Exchange and Queue configuration and binding.

Wrapper (beta) can be downloaded from the ZeroMQ section.

Comments and fix for the wrapper are very apreciated.

Have fun and happy messaging 🙂

Swimming World Championships: Delphi Software swim in it

From July 17th to August 2nd, The Foro Italico (in Rome) will be the heart of the 13th FINA World Championships Roma 2009, for swimming, diving, synchronised swimming and water polo. Four permanents pools and two temporary pools will be the set of the competitions for the four competitive disciplines, and all the venue will turn into a village that will host and entertain all night long over 400.000 people during 17 days of contests.

2009 Swimming World Championships

Now you are thinking: where is Delphi ?

Delphi is used (as usual) without knowing you are using it.

A software built with Delphi is used to manage the opening ceremony.
This software is designed to do the very complex attendee placement in the audience and to automate the invitation process.
The attendees will be VIP from Italy and international countries, starting from the italian president, the highest authority in Italy.



You can have a look at the software CERIMONIERE here (but the site is in Italian, sorry)

I actively participated in the design and development of this software, and now that I see it in action, in a so important and internationally well known event, I’m very proud of it, and I’m sure any member of the great Delphi community will be as well.

Delphi Developer Days

When I was at Delphi Live in San Jose, I attended Marco Cantù and Cary Jensen Masterclass about Delphi Multithreading.
Although, I’m expert of multi threading techiques and the related problems, this masterclass was very interesting and well organized as well.

IMHO, the topics have been presented in very effective manner and, as usual, in a very professional way.

After their speech, Marco introduced me to “Delphi Developer Days”.

I’ll do my best to attend their event in London.

Following some references in case you want also attend:

Delphi Developer Days 2009 London
Top Delphi experts Marco Cantù and Cary Jensen are bringing
their two-day live seminar to London on July 1-2, 2009.
For complete, details, visit http://www.DelphiDeveloperDays.com

Delphi profiling made simple… really simple!

Many users asked Embarcadero to include a profiler in the next Delphi for Win32.

Waiting for this, there are some interesting tools for profile a Delphi program.

For example, AsmProfile is an Open Source sampling profiler wich is very simple to use.


Actually AsmProfile is an “Instrumenting” profiler. It uses runtime function detouring and assembly to profile any selected function.

If you dont know differences between Instrumenting profiler and Sampling profiler, you can go here or here and read about it.

So, Suppose to have a slow code like this:

Download AsmProfiler from SVN or project home page (see the end of the article).

Now you can put 2 unit in your uses clause and initialize profiler interface directly in your dpr

So far so good… compile your app with following settings:
Delphi -> Project Options:

  • Linker -> Map file = detailed
  • Compiler -> Optimization = off
  • Compiler -> Stack frames = on

In this way, the profiler can reach procedures address for profiling phase.
Run your application and a small form will show up. In this form your must select the profiled methods and then click “Start”.

Now stress your application, click “Stop” and then “Show Results”.
In the “results” form will be shown detailed information about program execution.

Every call timing is splitted in “Calls”, “Parent Calls” and “Child calls” and some stats has been calculated too.

AsmProfiler It’s not complete like AQTime from AutomatedQA, but it’s a very usefull tool for every Delphi programmer.

You can find AsmProfiler here but I suggest to download the updated SVN version.


AsmProfile can also profile your code without change source using DllInjection.

When you only have an executable:

  • Start your executable
  • Start “dllinject.exe” (will show up a console window)
  • Get the PID of your executable via Windows Task Manager or Sysinternal Process Exlorer
  • Enter this number in the console black
  • Start profiling

My speech at “PHPCon Italia 2009”

I will talk at the italian PHPCon in Rome on March 18-20 2009.

I will talk about “Data Access Design Patterns” showing many PHP examples.

PHPCon Italia 2009
Holiday Inn Eur Parco dei Medici
Viale Castello Della Magliana 65
ROME, 00148
Web Site

Click here for discount on ticket (italian web site)

And this is the “Speaker Button”

My Speaker Button
My Speaker Button

A Simple start with MVP in Delphi for Win32, Part 1

As GUI framework such as VCL become more and more powerful, it’s common practice to let the UI layer do more than it should. Without a clear separation of responsibilities, the UI layer can often become an integral part of application and businness logic, but… this kind of responsabilities belongs to other layers of the application.
A design pattern (and his numberless variants), is especially well suited to solving this problem.

In this article I want to build a simple application using MVP pattern. Actually, pattern used is not “clear” MVP but his variation called Passive View.

Using Fowler words:

A perennial problem with building rich client systems is the complication of testing them. Most rich client frameworks were not built with automated testing in mind. Controlling these frameworks programaticly is often very difficult.

A Passive View handles this by reducing the behavior of the UI components to the absolute minimum by using a controller that not just handles responses to user events, but also does all the updating of the view. This allows testing to be focused on the controller with little risk of problems in the view.

Passive View ensures no dependecies between Model and View.

Passive View has no dependencies between view and model (Unlike most MVC-style triad)
Passive View has no dependencies between view and model (Unlike most MVC-style triad)

In this sample, “model” is a simple layer for application logic. In real world, “service layer” should incapsulate “application service” and “domain model“.

Application looks like following:

The Calculator
The Calculator
Div operator with result
Div operator with result
Div operator with a EDivByZero Exception
Div operator with a EDivByZero Exception

Connect View and Presenter
The view (the Form in VCL application) must implement an interface.

This interface should provide all method to interact with GUI:

ICalculatorView = interface
  function FirstOperand: String;
  function SecondOperand: String;
  procedure SetFirstOperand(Value :String);
  procedure SetSecondOperand(Value :String);
  function GetOperator: IGUISelectableList;
  procedure SetCalcResult(const Value: String);
  procedure SetCalcResultReadOnly(const Value: Boolean);
  function Error: IGUIEdit;

For simple interacting with GUI widget (in our example are EditFirstOperand, EditSecondoperand and EditCalcResult) we use a simple methods like following

  function FirstOperand: String;
  function SecondOperand: String;
  procedure SetFirstOperand(Value :String);
  procedure SetSecondOperand(Value :String);

But, if we need more by our widget (like populating combo box or change font color in the EditError or set ReadOnly to true) we should use another interface for a family of component.
In this sample I wrote 3 general interface:

  IGUIBaseInterface = interface

  IGUIEdit = interface(IGUIBaseInterface)
    procedure SetText(const Value: String);
    function GetText: String;
    function GetAsInteger: Integer;
    function GetAsFloat: Extended;
    procedure SetReadOnly(const AValue: boolean);
    procedure SetVisible(const Value: Boolean);
    function GetTextAsInteger: Integer;
    procedure SetTextAsinteger(const Value: Integer);
    function GetTextAsFloat: Extended;

  IGUISelectableList = interface(IGUIBaseInterface)
    procedure SetText(const Value: String);
    function GetText: String;
    procedure SetValue(const Value: String);
    function GetValue: String;
    function GetSelected: ISSKeyValue;
    procedure AddPair(AKey, AValue: String);
    procedure Clear;

For implementation details see attached sample code.

Finally in FormCreate of our form we can wire Presenter and View:

TfrmCalculatorView = class(TForm, ICalculatorView)
  //interface section
procedure TfrmCalculatorView.FormCreate(Sender: TObject);
  //Link controls with related interface
  IOperators := TGUISelectableList.Create(ComboOperators);
  IError := TGUIEdit.Create(EditError);

  //link view and presenter
  //In this version VIEW know PRESENTER
  FPresenter := TCalculatorPresenter.Create(Self);

This is a very simple example, so not all looks like real world. In a real world application, for example, view should not known the presenter class. With dependency injection you can do that (Next article in this serie will talk about this).

Every event generated by View (our Form) must be redirected to Presenter.

procedure TfrmCalculatorView.Button1Click(Sender: TObject);

Another approach is to publish some events in view interface and let presenter to bind them via standard event handler or anonimous methods (but this is for another post).

In attached sample code there is a sample application and unit test for Service Layer and View.
Required Mock Library is included in the zip file.

Simple Passive View, Sample Code

In 2nd part I’ll talk about unit test and mock object in Passive View.

.NET databinding in Delphi for Win32

Databinding is defined as: “General technique that binds two data/information sources together and maintains them in sync. This is usually done with two data/information sources with different types as in XML data binding. However in UI data binding, we bind data and information objects of the same type together (e.g. Java objects to Java UI elements).”

Databinding is common technique in VCL. Since Delphi 1 we have TDataset class for bind data and UI controls (DB Aware) in a GUI application.

In .NET world, instead, databinding is very different.

So, I’m starting to write (actually for fun) a DataBinder component to use .NET “like” databinding (or something similar to) in Delphi for Win32 too.

All the code has been written in about 2 hours.


With this component you can “bind” an object property to another object property in a declarative mode.


DataBinder.Add(Person, 'FirstName', Edit1, 'Text');

and then, every update to Person.FirstName property, will be reflected in the Edit1.Text property.

You can bind different control properties to different BO properties.


//Text = FirstName
DataBinder.Add(Person, 'FirstName', Edit1, 'Text');
//If Person is not married, TEdit become flat
DataBinder.Add(Person, 'IsMarried', Edit1, 'Ctl3D');

So in your initialization code (e.g. FormCreate) you can write somethig similat to following:

procedure TForm3.FormCreate(Sender: TObject);
binder: TDataBinder;
//Create your "BO"
Person := TPerson.Create;
//read data from "database"

//Setup databinding...
binder := TDataBinder.Create(self);
binder.Add(Person, 'FirstName'   ,      Edit1,     'Text');
binder.Add(Person, 'LastName',          Edit2,     'Text');

//The same attribute binded to 3 controls
binder.Add(Person, 'Married',     CheckBox1, 'Checked');
binder.Add(Person, 'Married'   , Edit1,     'Ctl3D');
binder.Add(Person, 'Married',     Edit2,     'Ctl3D');

//The same attribute binded to 2 controls
binder.Add(Person, 'SomeInteger', ComboBox1, 'ItemIndex');
binder.Add(Person, 'SomeInteger',     TrackBar1, 'Position');

//A derived property
binder.Add(Person, 'FullName',     Panel1, 'Caption');

//let start...

Other info asap so, stay tuned.

Download Code and compiled sample

(Source code require Delphi 2009)