You are on page 1of 60

BLAISE

BLAISE PASCAL
PASCAL MAGAZINE
MAGAZINE
D E L P H I,
A N D
A N D R O I D, 36
L A Z A R U S,
P A S C AL
I O S,
O X Y G E N E,
R E L A T E D
M A C,
S M A R T M O B I L E,
L A N G U A G E S
W I N D O W S & L I N U X

v4
Ul

.1
tr
a-

v4
w
id

.0
eb
an
d
v3.
0+
HS

v2.1 + EDR

EDR
0+
v2.
.2
v1

.1
v1

B
1.0
dv
an
.0
v1

BOOK Review By Jim Duff


Object Pascal Handbook
New book from Marco Cant
A WYSIWYG math editor
By David Dirkse
Blue Tooth
By Jeremy North
3D Printing Lab (maxbox)
By Max Kleiner
Converting Delphi to Lazarus and Vice Versa
Differences between Delphi and Lazarus
Lazarus for beginners:
Starting your first program
By Howard Page-Clark
TMS XData and TMS Aurelius Learning by Example
By Wagner Landgraf
UpdateMode and FireDAC DataSets
Cary Jensen
AMQP (Advanced Message Queuing Protocol)
By Fikret Hasovitch

Publisher: Foundation for Supporting the Pascal Programming Language


in collaboration with the Dutch Pascal User Group (Pascal Gebruikers Groep)
Stichting Ondersteuning Programmeertaal Pascal
BLAISE
BLAISE PASCAL
PASCAL MAGAZINE
MAGAZINE 36
D E L P H I, L A Z A R U S, S M A R T M O B I L E S T U D I O, A N D P A S C A L R E L A T E D
L A N G U A G E S FOR A N D R O I D, I O S, M A C, W I N D O W S & L I N U X

CONTENTS

Articles
BOOK Review By Jim Duff
Object Pascal Handbook
New book from Marco Cant Page 5
A WYSIWYG math editor
By David Dirkse Page 10
Blue Tooth
By Jeremy North Page 16
3D Printing Lab (maxbox)
By Max Kleiner Page 23
Converting Delphi to Lazarus and Vice Versa
Differences between Delphi and Lazarus Page 28
Lazarus for beginners:
Starting your first program
By Howard Page-Clark Page 35
TMS XData and TMS Aurelius Learning by Example
By Wagner Landgraf Page 40
UpdateMode and FireDAC DataSets
Cary Jensen Page 50
AMQP (Advanced Message Queuing Protocol)
By Fikret Hasovitch Page 54

MOTION

BLAISE
BLAISE PASCAL
PASCAL MAGAZINE
MAGAZINE
Advertisers

Barnsten 27
BetterOffice 33
BLAISE PASCAL MAGAZINE 4
Cary Jensen (Jensen Data Sytems) 2
Components 4 Developers 60
Computer Math & Games 22
Evers Custom Technology 9
Mitov Software 15
Raize Software 34
Vogelaar Electronics 39

2 COMPONENTS
DEVELOPERS 4 Nr 4 / 2014 BLAISE PASCAL MAGAZINE
Alexander Alexeev Peter Bijlsma Michal Van Canneyt,
www.alexander@blaisepascal.ru -Editor peter @ blaisepascal.eu michael @ freepascal.org
Alexander @ blaisepascal.ru

Marco Cant David Dirkse Daniele Teti


www.marcocantu.com www.davdata.nl www.danieleteti.it
marco.cantu @ gmail.com E-mail: David @ davdata.nl d.teti@bittime.it

Bruno Fierens Primo Gabrijeli Fikret Hasovic


www.tmssoftware.com www. www.
bruno.fierens @ tmssoftware.com primoz @ gabrijelcic.org

Cary Jensen Wagner R. Landgraf Sergey Lyubeznyy


www.jensendatasystems.com
http://caryjensen.blogspot.nl

Kim Madsen Felipe Monteiro de Cavalho Mattias Gaertner


www.component4developers

Jeremy North Benno Evers Detlef Overbeek


b.evers www.blaisepascal.eu
jeremy.north @ gmail.com @everscustomtechnology.nl Email:editor @ blaisepascal.eu

Howard Page Clark Rik Smit Bob Swart


E-mail: hdpc @ talktalk.net www.eBob42.com
Bob @ eBob42.com

Wim Van Ingen Schenau


-Editor
wisone @ xs4all.nl

Please note:The spacings in the emails was added on purpose. Please delete for use
editor @ blaisepascal.eu

Authors - alphabethical order


A Alexander Alexeev L Wagner R. Landgraf, Sergey Lyubeznyy
B Peter Bijlsma, K Max Kleiner
C Michal Van Canneyt, Marco Cant, M Kim Madsen, Felipe Monteiro de Cavalho
D David Dirkse, Daniele Teti N Jeremy North,
F Bruno Fierens O Tim Opsteeg, Inoussa Ouedraogo
G Primo Gabrijeli, P Howard Page-Clark,
H Fikret Hasovic S Rik Smit, Bob Swart,
J Cary Jensen

Editor - in - chief
Detlef D. Overbeek, Netherlands Tel.: +31 (0)30 890.66.44 / Mobile: +31 (0)6 21.23.62.68
News and Press Releases email only to editor@blaisepascal.eu

Editors
Peter Bijlsma, W. (Wim) van Ingen Schenau, Rik Smit,
Correctors
Howard Page-Clark, James D. Duff
Trademarks
All trademarks used are acknowledged as the property of their respective owners.
Caveat Whilst we endeavour to ensure that what is published in the magazine is correct, we cannot accept responsibility for any errors or omissions.
If you notice something which may be incorrect, please contact the Editor and we will publish a correction where relevant.
Subscriptions ( 2013 prices )
1: Printed version: subscription 60.-- Incl. VAT 6 % (including code, programs and printed magazine,
6 issues per year excluding postage).
2: Electronic - non printed subscription 45.-- Incl. VAT 21% (including code, programs and download magazine)

Subscriptions can be taken out online at www.blaisepascal.eu or by written order, or by sending an email to office@blaisepascal.eu
Subscriptions can start at any date. All issues published in the calendar year of the subscription will be sent as well.
Subscriptions run 365 days. Subscriptions will not be prolonged without notice. Receipt of payment will be sent by email.
Subscriptions can be paid by sending the payment to:
ABN AMRO Bank Account no. 44 19 60 863 or by credit card: Paypal
Name: Pro Pascal Foundation-Foundation for Supporting the Pascal Programming Language (Stichting Ondersteuning Programeertaal Pascal)
IBAN: NL82 ABNA 0441960863 BIC ABNANL2A VAT no.: 81 42 54 147 (Stichting Programmeertaal Pascal)
Subscription department Edelstenenbaan 21 / 3402 XA IJsselstein, The Netherlands / Tel.: + 31 (0) 30 890.66.44 / Mobile: + 31 (0) 6 21.23.62.68
office@blaisepascal.eu

Copyright notice
All material published in Blaise Pascal is copyright SOPP Stichting Ondersteuning Programeertaal Pascal unless otherwise noted and may
not be copied, distributed or republished without written permission. Authors agree that code associated with their articles will be made
available to subscribers after publication by placing it on the website of the PGG for download, and that articles and code will be placed on
distributable data storage media. Use of program listings by subscribers for research and study purposes is allowed, but not for commercial
purposes. Commercial use of program listings and code is prohibited without the written permission of the author.

Nr 4 / 2014 BLAISE PASCAL MAGAZINE


COMPONENTS
DEVELOPERS 4 3
PAGE-CLARK
LEARN TO PROGRAM
HOWARD
USING LAZARUS HOWARD PAGE-CLARK

USING LAZARUS
LEARN TO PROGRAM
HARDCOVER ELECTRONIC POCKET

16 GB 1421
Vogelaar Electronics
RPi ArchVE
RPi-ArchVE
Complete IO
RPi-B+ Raspberry Pi
version B+

VE09206 Delphi AVR


Controller with SDK

Delphi AVR
development board
with SDK

POCKET VE08201 DelphiStamp with SDK

GREAT NEW OFFERS AT OUR WEBSITE:


WWW.BLAISEPASCAL.EU
4 COMPONENTS
4
DEVELOPERS
Nr 4 / 2014 BLAISE PASCAL MAGAZINE
BOOK Review By Jim Duff
Marco Cant Delphi and Appmethod are trademarks of
Embarcadero Technologies.
Object Pascal Handbook Other trademarks are of the respective owners,
October 2014 Draft
as referenced in the text. The author and publisher
Author: Marco Cant have made their best efforts to prepare this book,
Publisher: Marco Cant and the content is based upon the final release of the
Editor: Peter W A Wood software.
Cover Designer: Fabrizio Schiavi (www.fsd.it) The author and publisher make no representation or
Copyright 1995-2014 Marco Cant, Piacenza, warranties of any kind with regard to the
Italy. World rights reserved. completeness or accuracy of the contents herein and
accepts no liability of any kind including but not
limited to performance, merchantability, fitness for
any particular purpose, or any losses or damages of
any kind caused or alleged to be caused directly or
indirectly from this book.
The Object Pascal Handbook,
October 2014 Draft.
ISBN-10: * ISBN-13: *

Electronic edition licensed to Embarcadero


Technologies Inc.
Any other download or sale outlet is likely to be
illegal.
Do not distribute the PDF version of this book
without permission. Print edition to become available
as the book is completed in early 2015.
More information on
http://www.marcocantu.com/objectpascal

This review is about the latest book written by


our well known Pascal person, Marco Cant.
For any new developers or readers, please see
The author created example code in this publication part of the extracted 'About Myself, The
expressly for the free use by its readers. Source code Author' that gives a short preview of Marco.
for this book is copyrighted freeware, distributed via
the web site http://code.marcocantu.com. That is then followed by a sub-set of the
The copy- right prevents you from republishing the book's contents.
code in print or electronic media without permission.
Readers are granted limited permission to use this Now to get down to the actual review...
code in their applications, as long at the code itself is One's first comments are usually based upon
not distributed, sold, or commercially exploited as a the opening chapters that provide us with the
stand-alone product. objectives of the book. In this case, as well as
Aside from this specific exception concerning having provided some interesting background
source code, no part of this publication may be stored of Object Pascal and the author, the first
in a retrieval system, transmitted, or reproduced in standard and simple coding item of "Hello,
any way, in the original or in a translated language, World" is supported by the book's first
including but not limited to photocopy, photograph, pictures, initially the First Console Application's
magnetic, or other record, without the prior output image. This is immediately followed by
agreement and written permission of the publisher. the First Visual Application's two images: the
view of Button1, followed by the view of its
output image, on the most popular modern
day 'computer' - a telephone. Yes, this
confirms the relevance of such a technical
book in these modern days.
Nr 4 / 2014 BLAISE PASCAL MAGAZINE 5
BOOK Review Marco Cant Object Pascal Handbook (Continuation 1)

6 Nr 4 / 2014 BLAISE PASCAL MAGAZINE


BOOK Review Marco Cant Object Pascal Handbook (Continuation 2)

Nr 4 / 2014 BLAISE PASCAL MAGAZINE 7


BOOK Review Marco Cant Object Pascal Handbook (Continuation 3)
As the book is about Object Pascal, there is A couple of details from the book's draft plus
merely a handful of images, unlike books that the Table of Contents have been partially
relate to visual control/forms etc. copied below in order to provide you with
However, the supporting elements of the relevant items referred to in this chat above.
subject matters are code based samples. Good luck reading this for now, until you get
These are also followed by detailed the full copy from Marco.
explanations of most items, which appear as a
short note or a tip that provide a conclusive A Companion Web Site
summary of what has been said. The book has a companion web site with
further information, links, updates and more.
The pictorial book cover is an ancestral based There are both a static, traditional site with
diagram that supports the Object relativity of information at:
such coding. http://www.marcocantu.com/
objectpascalhandbook
A code sample within Breaking the Flow with and online pages on Google+ (using a bit.ly
Break and Continue is followed by a summary link) and Facebook at
Here Comes GoTo Now Way ... goto http://bit.ly/objectpascalgplus
statements generally look like erratic jumps, https://www.facebook.com/
and are really completely discouraged. Did I objectpascalhandbook
mention they are not supported in Object
Table of Contents
Pascal? No, I didn't, nor am I going to show {Multiple sub-paragraphs have been removed to
you a code example. To me goto is long gone. reduce its space in this magazine}
01: Coding in Pascal
Another partial item that has been copied from Let's Start with Code
the book is as follows, advising potential Syntax and Coding Style
readers what the book and Object Pascal are Language Keywords
all about today. "What is the Object Pascal The Structure of a Program
language for? Compiler Directives
02: Variables and Data Types
From writing desktop apps to client-server Variables and Assignments
Data Types
applications, from massive web server
Simple User-Defined Data Types
modules to middleware, from office
Expressions and Operators
automation to apps for the latest phones and Date and Time
tablets, from industrial automated systems to Typecasting and Type Conversions
Internet virtual phone networks... this is not 03: Language Statements
what the language could be used for, but what Simple and Compound Statements
it is currently used for today, in the real world" The If Statement
Wow, what a fact. This is further supported by Case Statements
Appendix A: the evolution of Object Pascal, The For Loop
While and Repeat Statements
the last part being the subject Going Mobile.
04: Procedures and Functions
Procedures and Functions
Given Marco Cant's background, this book is Parameters and Return Values
most helpful for coders, when the number of Inlining
'computers' in this day and age have grown in Advanced Features of Functions
types, operating systems and ownerships. 05: Arrays and Records
Such a large book, containing 333 pages, is a Array Data Types
well provided software development Record Data Types
document, based on its title - Object Pascal Records with Methods
What About Pointers?
Handbook - in this day and age. My review of
File Types, Anyone?
this book definitely gives it a positive vote.
06: All About Strings
Unicode: An Alphabet for the Entire World
James D (Jim) Duff The Char Type Revisited
ADUG Member Melbourne Australia. The String Data Type
Yes, Marco has been way down here a few Strings and Encodings
times. Other Types for Strings
Part II: OOP in Object Pascal

8 Nr 4 / 2014 BLAISE PASCAL MAGAZINE


BOOK Review Marco Cant Object Pascal Handbook (Continuation 4 End)
07: Objects Appendix Summary
Introducing Classes and Objects A: The Evolution of Object Pascal
The Object Reference Model Wirth's Pascal
Private, Protected, and Public Turbo Pascal
The Self Keyword The early days of Delphi's Object Pascal
Constructors Object Pascal From CodeGear to Embarcadero
Nested Types and Nested Constants Going Mobile
08: Inheritance
Inheriting from Existing Types
A Common Base Class
Protected Fields and Encapsulation
From Inheritance to Polymorphism
Abstracting Methods and Classes
Safe Type Cast Operators About the Author
Visual Form Inheritance My name is Marco and I've spent most part of the
09: Handling Exceptions past 20 years writing, teaching, and consulting on
Try-Except Blocks software development with the Object Pascal
The Finally Block language. I wrote the Mastering Delphi best-
Exceptions in the Real World selling series and later self-published several
Global Exceptions Handling Handbooks on the development tool (about the
Exceptions and Constructors different versions from Delphi 2007 to Delphi XE).
Advanced Exceptions I have spoken at a large number of programming
Part III: Advanced Features conferences in most continents, and taught to
14: Generics hundreds of developers.
Generic Key-Value Pairs
Generics in Object Pascal Having worked as an independent consultant and
Generic Constraints trainer for many years, in 2013 my career took a
Predefined Generic Containers sudden change: I accepted a position as Delphi
Generic Interfaces and now RAD Studio product manager at
Smart Pointers in Object Pascal Embarcadero Technologies, the company that
Covariant Return Types with Generics builds and sells these great development tools,
15: Anonymous Methods along with the new Appmethod product...
Syntax and Semantics of Anonymous Methods
Using Local Variables
Anonymous Methods Behind the Scenes
Anonymous Methods in the Real World

COMPONENTS
DEVELOPERS 4 Specialist help and consultancy
for kbmMW

Benno Evers is our specialist for


questions about kbmMW.
He can help you with basic
questions regarding kbmMW as
well as with turnkey Development
and Consultancy. Hes a specialist
in netwoks, internet and CUSTOM TECHNOLOGY
hardware. b.evers@eversct.nl

Nr 4 / 2014 BLAISE PASCAL MAGAZINE 9


A WYSIWYG math editor By David Dirkse
Introduction
On top of the form are the buttons of the main menu, below
starter expert them the buttons for the selection of graphic symbols.
Delphi
Bitmaps and coordinates.
This article describes part of a math The contents are saved in vectorized form, not as bitmap
editor under construction. Purpose of this
images. To show the contents, paint-procedures are needed.
editor is the integration of text (roots,
fractions ...), with drawings , equation Painting takes place in two bitmaps, map1 and map2.
graphers and geometrical constructions. Parts of map2 may be copied to a paintbox to show the image.

Elements and symbols are placed on an


A4 sized form. An element may be a
character, line of characters, a frame with
elements and lines etcetera. Elements are
responsible for the painting of their
contents. Examples of symbols are lines,
circles, roots or parenthesis. Symbols are
added to an element.

This article focusses on the positioning of


elements.
This was more dificult then expected,
main reason are the requirements for
editing.
Before continuing, a few words about the
general setup of the editor.

Figure 1: A reduced picture of the editor at work:.


10 COMPONENTS
DEVELOPERS 4 Nr 4 / 2014 BLAISE PASCAL MAGAZINE
A WYSIWYG math editor (Continuation 1)
Map1 contains one full page. The relative positions of blocks within blocks:
Trial painting takes place in map2, where map1 is
used to restore overwritten parts of map2. Only
modified areas of map2 are copied to the paintbox.
This avoids flicker.

A page dimension is 760 * 1080 pixels.


The document may hold 30 pages.
A page is selected by the vertical tabs at the right side
of the form.

A map's Y-cordinate must be increased by Ypagetop


to be relative to the full document.
Ypagetop = (page number -1)*1080.
Text
Mousecoordinates are relative to the paintbox. The Y- All text is placed inside a line element.
mousecoordinate must be increased by Ybias to be Lines, frames and blocks are not allowed to overlap.
relative to map1 or map2.
Ybias may be changed by the vertical scrollbar at the Data Structures
Elements are stored in an array called elements.
right side of the form.
type Telementtype =
Blocks and Frames (elFree,elDoc,elblock,elFrame,elframeBG,
elCoord,elImage,elTable,elLine,elChar,
A block is a rectangular element which may hold
elMacro,elColumn,elXTab,elYTab);
other elements or symbols.
A frame is a block with an extra frame-edge around TElement = record
it. elType : TelementType;
Blocks and frames may be placed at any place on the elCode : byte;
document, but they are not allowed to overlap. p1 : word; // type
dependent params
Elements within a block or frame have coordinates p2 : word;
that are relative to that block or frame. x,y : smallInt;// position
At design time, blocks have an edge painted around relative to parent
them to show its boundaries. width : smallInt;
Blocks and frames may clip symbols, so drawings are height : smallInt;
limited to their space. end;
Below is pictured a block and three different frames.
Also there are clipped dash-dot lines. var elements : array[1..maxelement];

Element 1 is the document.


Macro's are structures of elements and symbols.
Roots and fractions are macro's.
Like characters, they are placed inside lines.

To record the relationship between elements, a tree


structure is introduced.
TLinks = record
parent : dword;
child : dword;
next : dword;
previous : dword;
end;

var links : array[1..maxelement] of Tlinks;

Nr 4 / 2014 BLAISE PASCAL MAGAZINE


COMPONENTS
DEVELOPERS 4 11
A WYSIWYG math editor (Continuation 2)
links[56] holds the connections of element[56]. Positioning
The links array cannot be changed directly. It is Text and painting cursors move over the paintbox.
modified by procedures that accomplish tree Question is which element they hoover at a given
operations such as element insertion and deletion. It time.
includes the UNDO system. The X and Y fields of an element are relative to its
An element within another element is called a child. parent.
A parent may only point to one child. Therefore, an Advantage is, that there is no need to recalculate the
element has the next field that actually points to the postion of the children if an element changes
next child within the parent element. position.

Below is how the element connections


are pictured:

Parent, child, next and previous have the value zero


if no connection is present. First a procedure which supplies the (x,y) coordinates
The schematic of a document with a frame with two of an element relative to the full document.
children:
procedure AbsXY(var x,y : smallInt; el :
dword);
//supply document relative [x,y] of element el
begin
x := element[el].x;
y := element[el].y;
repeat
parentEL(el);
if el > 1 then
begin
x := x + element[el].x;
y := y + element[el].y;
end;
Elements 3 and 4 both have 2 as parent.
until el <= 1;
Element 4 is the next of 3. Element 3 is the previous end;
of 4.
Now a fuction which finds the element a pixel
To navigate through the tree, there are functions such belongs to.
as: The result is the element number.
The x,y params in the call are bitmap relative.
function ParentEl(var nel : dword) : boolean;
function ChildEl(var nel : dword) : boolean;
function NextEl(var nel : dword) : boolean;
function previousEl(var nel : dword) : boolean;

Function ChildEL (nel) looks for a child of element


nel. If present, nel becomes the child number and
true is returned, else nel is not changed.
The other functions operate likewise. Advantage of
this code is that the function may be part of
conditional testing statements such as if,
while . do or repeat . until.
This concludes the introduction.
12 COMPONENTS
DEVELOPERS 4 Nr 4 / 2014 BLAISE PASCAL MAGAZINE
A WYSIWYG math editor (Continuation 2)
function XY2Element(x,y : smallInt; ELset : px,py are coordinates of the parent left top.
TELset) : dword; bx,by are coordinates of the child element.
//convert x,y of bitmap to lowest element
//ELset is set of elements to search for Below is the backbone flowchart of the XY2Element( )
var el : dword;
bx,by,px,py : smallInt; function.
inside : boolean;
begin On exit, variabele el holds the element number.
result := 1; See code for the details.
el := 1; //document
px := 0;
While painting blocks or frames, the overlap with
py := 0;
y := y + Ypagetop; //make doc relative
other elements must be checked continuously.
inside := true; This is done by the function overlapOK( )
while inside and childEL(el) do x1,y1,x2,y2 are the left-top and right-bottom
repeat coordinates of the rectangle to be tested.
bx := px + element[el].x; //abs coord
MinX, minY are minimal required dimensions of the
by := py + element[el].y;
if element[el].elType in ELset rectangle.
then Too small rectangles are skipped.
inside := (x >= bx) and
function OverlapOK(x1,y1,x2,y2 : smallInt;
(x < bx + element[el].width) and
minX,minY : smallInt) : boolean;
(y >= by) and
(y < by + element[el].height) //return true if rect x1,y1,y2,y2 does not overlap other blocks
else inside := false; //ESset holds elements to check for
if inside then const ESset = [elDoc,elBlock,elFrame,elFrameBG,
begin elCoord,elTable,elImage];
result := el; var
px := bx; el : dword;
py := by; ctr : byte;
end; begin
until inside or (nextEL(el) = false); result := ((x2-x1) >= minX)
end; and ((y2-y1) >= minY);
if result
Elset is the set of elementtypes we look for, not then
begin
mentioned element types are neglected. ctr := 0;
Type TElSet = set of TelementType; el := XY2Element(x1,y1,ESset);
repeat
case ctr of
0 : result := el = XY2Element(x1,y2,ESset);
1 : result := el = XY2Element(x2,y1,ESset);
2 : result := el = XY2Element(x2,y2,ESset);
end; //case
inc(ctr);
until (result = false) or (ctr > 2);

if result
then result := EmptyBlock(el,x1,y1,x2,y2);
end; //if result
end;

The four corners of the rectangle must be in the same


element.
This however is not sufficient for complete overlap
checking, look below for two cases:

Nr 4 / 2014 BLAISE PASCAL MAGAZINE


COMPONENTS
DEVELOPERS 4 13
A WYSIWYG math editor (Continuation 3 - End)

function EmptyBlock takes care of the extra overlap check.


For all children of element el, a check is made for overlap with rectangle x1,y1,x2,y2.
function EmptyBlock(el : dword;x1,y1,x2,y2 :
smallInt) : boolean;
//helper of OverlapOK function
//return OK if block does not surround or cross other block
var xx1,yy1,xx2,yy2 : smallInt;
begin
result := true;
if childEl(el) then
repeat
AbsXY(xx1,yy1,el);
with element[el] do
begin
xx2 := xx1 + width - 1;
yy2 := yy1 + height - 1;
end;
result := (xx2 < x1) or (xx1 > x2)
or (yy2 < y1 + YPageTop)
or (yy1 > y2 + YPageTop);
until (nextEL(el) = false)
or (result = false);
end;

The list of element types includes type elYtab.


This element is for vertical shifting of the contents.
An Ytab element with parameter p1 = 100 shifts all
next elements within the parent 100 pixels down.
The opposite takes place at undo of the Ytab.
BLAISE PASCAL MAGAZINE
Please note, that there is no such element as page. is proud to announce the first edition of
Pages are painted as part of the complete document. David Dirkses book:

The math editor is, and will be, under construction


for some time.
A general blueprint and some basic procedures Computer Math and
however are needed before designing the details.
Games in Pascal
This concludes the article about element positioning.

14 COMPONENTS
DEVELOPERS 4 Nr 4 / 2014 BLAISE PASCAL MAGAZINE
A NEW EXPERIENCE
ELECTRIFYING
COMPONENTS

MITOV
MITOV
SO F TWA R E

GET THE
EXPERIENCE:
TRY

http://www.blaisepascal.eu/subscribers/UK_Components_Mitov.html
Nr 4 / 2014 BLAISE PASCAL MAGAZINE 15
Using Bluetooth Classic in Delphi XE7 By Jeremy North
Article Scope
This article will only cover Bluetooth Classic.
Upcoming articles will focus on Bluetooth LE and
A major feature of Delphi XE7 was the using Bluetooth Tethering.
inclusion of Bluetooth support. The main
marketing for this feature was for allowing Bluetooth Classic for iOS
Bluetooth connectivity within Tethering. It is important to understand there is no
However the support for Bluetooth included implementation for Bluetooth Classic for iOS devices.
in XE7 is not restricted to using Bluetooth This warrants considerable caution in interpreting the
Thetering much-hyped Bluetooth Tethering support.
(Tethering refers to connecting one device to another. In
While Tethering does indeed support Bluetooth, it
the context of mobile phones or Internet tablets, tethering
just doesn't work with iOS devices. There are
allows sharing the Internet connection of the phone or
substantial licensing fees required to get Bluetooth kits
tablet with other devices such as laptops. Connection of
the phone or tablet with other devices can be done over to get access to the Bluetooth Classic API's for iOS.
wireless LAN (Wi-Fi), over Bluetooth or by physical I asked why Bluetooth Tethering support for iOS
connection using a cable, for example through USB. couldn't use Bluetooth LE but was told tethering was
too heavy (a lot of data) to be considered.
If tethering is done over Wi-Fi, the feature may be Bluetooth Classic support is available for all other
branded as a Mobile Hotspot. The Internet-connected supported operating systems. I will be using a Mac
mobile device can thus act as a portable wireless access Mini paired with a Nexus 7 tablet for all sample
point and router for devices connected to it.) applications.

Types of Bluetooth Fire Monkey or VCL


There are two different types of Bluetooth The Bluetooth units are in the System namespace
connectivity available today. There is Bluetooth which means they are compatible with VCL and Fire
Classic and Bluetooth Smart. Monkey applications which is good if you are still
using the VCL for applications. The main unit is
Bluetooth Smart System.Bluetooth; System.BluetoothConsts and then
Bluetooth Smart is the marketing name behind what the platform specific implementation units:
is most commonly known as (especially to developers) System.Android.Bluetooth, System.Mac.Bluetooth,
Bluetooth Low Energy (Bluetooth LE). System.Win.Bluetooth.
It is important to know apart from a couple of generic
Bluetooth v4. base classes, some exceptions and basic types;
Bluetooth LE is all the rage at the moment due to its Bluetooth Classic and Bluetooth LE support do not
ability to not drain the life out of your supporting share any code.
device. Developers will mostly know Bluetooth Smart As previously mentioned I will be using OS X and
(a newer marketing term) as Bluetooth Low Energy
Android so I certainly won't be using VCL for my
(Bluetooth LE) or Bluetooth v4.This doesn't mean the
application.
protocols are compatible because they are not.
Checking to see if anyone is home
Before we can start programming, we need to make
Bluetooth Classic
Bluetooth Classic is the name give to the original sure our adapters are recognised. Many of the new
Bluetooth implementation once the Low Energy APIs from Embarcadero they are all centred on a
Bluetooth specification was bought under the static Manager class and Bluetooth Classic support is
Bluetooth umbrella. These are Bluetooth versions no different in this respect.
from 1.0 up to and including 3.x however since Using TBluetoothManager we can get information
version 4; it is said that when a device supports about the current adapter and output the
Bluetooth v4, it supports both classic and smart information.
variations. The original Bluetooth implementation
was re-named Bluetooth Classic as soon as the Low
Energy Bluetooth
specification was brought
under the Bluetooth umbrella.
Bluetooth Classic includes versions
from 1.0 up to and including 3.x.
With the arrival of version 4 it is
now true that when a device
supports Bluetooth v4, it will
support both Classic and Smart variations.
Figure 1: Bluetooth related products
16 COMPONENTS
DEVELOPERS 4 Nr 4 / 2014 BLAISE PASCAL MAGAZINE
Using Bluetooth Classic in Delphi XE7 (Continuation 1)
procedure TfrmMain.CheckStatusButtonClick(Sender: Although this is a good fall-back, I encourage
TObject); everyone to utilize the ToString method more and
var
LAdapter: TBluetoothAdapter;
don't worry descendants can always override
begin ToString if you don't like the ancestor
if TBluetoothManager.Current = nil then implementation.
StatusLabel.Text :=
'No Bluetooth Manager available' Windows (no Bluetooth support) Figure 2
else
begin
LAdapter :=
TBluetoothManager.Current.CurrentAdapter;
if LAdapter <> nil then
StatusLabel.Text := LAdapter.AdapterName
+ ' - ' + LAdapter.Address
else OS X Figure 3
StatusLabel.Text :=
'No adapter available';
end;
end;

One annoying thing about new classes within the Android


RTL or your favourite presentation framework is the Before deploying to Android you need to make sure
continued non-implementation of the ToString the Bluetooth permission is set in the project options
method. This method should be utilised more. In the for the Android target. Figure 4
sample above, I should have just being able to write
LAdapter.ToString (instead of my crude
concatenation I would use Format in a real work app by
the way). Instead calling ToString gives me the class
name.

Figure 5: Android Bluetooth cofiguration

Nr 4 / 2014 BLAISE PASCAL MAGAZINE


COMPONENTS
DEVELOPERS 4 17
Using Bluetooth Classic in Delphi XE7 (Continuation 2)
Finding Devices to connect with instead of using the host operating system for pairing
This isn't a TCP/IP connection where we might devices. This functionality doesn't work on OS X it
know the IP address or computer name in which to is something only the operating system can do.
connect to up front. The first thing to do is to scan the If you do wish to use these features in your
airwaves for other Bluetooth supporting devices applications, make sure to include the Bluetooth
within range to communicate with. Admin permission for Android.
As most will know you can either discover new
devices or view a list of devices that have already
paired. Accessing the list of paired devices is done
Making a connection
using the PairedDevices property available on the
To actually communicate to a paired device a service
current adapter being used.
needs to be published. The service is identified by a
The following code displays the list of paired devices
unique identifier. You can also define a description
(and their device class string value) in a list box.
for the service which will appear when the available
procedure TfrmMain.LoadPairedDevices;
var services are requested.
LPairedDevices: TBluetoothDeviceList; Use the CreateServerSocket method on the current
LDevice: TBluetoothDevice; adapter to create the service. You provide a Name,
LDescription: string; unique identifier and if data sent is it should be
begin
if TBluetoothManager.Current.CurrentAdapter secure. The code below shows how to create a unique
<> nil then service.
begin
LPairedDevices := const
TBluetoothManager.Current.CurrentAdapter BLAISE_UUID: TGuid =
.PairedDevices; '{8BE07D9D-2427-4B55-85A5-82DF2C7D7325}';
for LDevice in LPairedDevices do StrBlaiseDemoService =
begin 'Blaise Bluetooth Classic Demo';
LDescription := Format('%s (%s)', var
[LDevice.DeviceName, LServerSocket: TBluetoothServerSocket;
TBluetoothDevice.ClassDeviceString( begin
LDevice.ClassDevice)]); LServerSocket := TBluetoothManager.Current.
PairedDevicesListBox.Items CurrentAdapter.CreateServerSocket(
.AddObject(LDescription, LDevice); StrBlaiseDemoService, BLAISE_UUID, True);
end;
end; end;
end;
Once the service has been created, returning the list of
The TBluetoothDevice objects in the available services for a device is just a matter of
PairedDevices list are lifetime managed for you so calling the GetServices method on the specific device.
there is no need to worry about freeing the objects. In the image below the Android tablet has created the
Instead of using the PairedDevices property on an service which has been connected to under OS X.
adapter, you could use either of the NOTE: If the reverse is done the Name given to the
GetPairedDevices methods available on the service does not appear, only the GUID (the name is
manager. There is a method that operates on the blank even though it is set).
current adapter and also a version
that accepts an adapter to work on. Figure 6
Discoverable and Discovery
What's the difference?
discover new devices, or
view a list of devices that have
already paired.

With the Bluetooth Manager it


is possible to make your device
discoverable and to discover
devices. This will not be
covered in this article
(if requested it could be in
the future). I'm not convinced
these are features a user would
find useful in an application

18 COMPONENTS
DEVELOPERS 4 Nr 4 / 2014 BLAISE PASCAL MAGAZINE
Using Bluetooth Classic in Delphi XE7 (Continuation 3)
Using Bluetooth means you need to poll the created Sending and Receiving data
sockets (client or server) for any data that is available. All of the work occurs in the Execute methods of the
The client socket can read and write directly to the server and client threads. They share a lot of common
created socket; however it must connect to the server code so they both descend from a class called
socket. Regardless of the application type, one of the TIOThread which implements the concept of
end-points will be designated the server and the sending text and the execution of events which a
other the client. Read or Write occurs. There is a single public method
called SendText. This method is used by the interface
to pass the sent text either to the Server thread or to
the Client thread for processing. The IOThread
stores the text in a list. Under Windows you might
have previously protected access to the list of text
using a critical section; however the cross-platform
way is to use the TMonitor class.
procedure TIOThread.SendText(const AText: string);
begin
TMonitor.Enter(FTextLock);
try
FTextToSend.Add(AText);
finally
TMonitor.Exit(FTextLock);
end;
end;

There are two protected methods to allow reading


and sending data on a specific TBluetoothSocket
instance. These methods should be called in
descendant classes once the socket is known to be
capable of performing these operations.
procedure TIOThread.ReadAvailableData(const
ASocket: TBluetoothSocket);
Polling var
Polling inefficiently can drain a portable device's LData: TBytes;
battery very quickly. You need to decide what begin
LData := ASocket.ReadData;
anacceptable interval between data requests is
if Length(LData) > 0 then
allowed to be DoReadDataEvent(
How crucial is the timing of information that TEncoding.UTF8.GetString(LData));
travels between connections? A chat application end;
could probably poll in the seconds; a live update of
procedure TIOThread.SendAvailableData(const
sports results might actually change polling times ASocket: TBluetoothSocket);
depending on the game state to preserve battery life. var
Two minutes into the first quarter it could be I: Integer;
begin
seconds, two minutes to go in the last with scores tied
TMonitor.Enter(FTextLock);
a user will want millisecond delays. It is a value try
you will need to determine best fits the application for I := 0 to FTextToSend.Count - 1 do
you are creating. begin
ASocket.SendData(TEncoding.UTF8.GetBytes(
FTextToSend[I]));
Timers or Threads DoSendDataEvent(FTextToSend[I]);
The answer will almost always be threads when end;
communication is required between a client and FTextToSend.Clear;
server. It provides cleaner and better separated code finally
TMonitor.Exit(FTextLock);
increasing maintainability. It doesn't clog up the end;
main thread with communication tasks leaving the end;
main thread to make sure the user interface continues
to be responsive. The constructor for TIOThread expects two events,
This article is not about threading and multi- one for when a read occurs and a second when a
threading techniques; if you are not confident using send occurs. The code to trigger the events is
threads then I suggest some training is this area boilerplate. The synchronisation occurs in the event
should be a priority. handlers, instead of inside the thread. This is a design
decision and can be done either way.
Figure 7: Apple watch

Nr 4 / 2014 BLAISE PASCAL MAGAZINE


COMPONENTS
DEVELOPERS 4 19
Using Bluetooth Classic in Delphi XE7 (Continuation 4)
procedure TIOThread.DoReadDataEvent(const AData: NOTE:
string);
begin
You can't use -1 to indicate no timeout,
if Assigned(FOnReadData) then use $FFFFFFFF instead.
FOnReadData(Self, AData); In the server thread class the timeout value can be
end; configured when the thread is created.
Remember this timeout will increase the time it takes
procedure TIOThread.DoSendDataEvent(const AData:
string);
for the next server check.
begin
if Assigned(FOnSendData) then procedure TServerThread.Execute;
var
FOnSendData(Self, AData);
LSocket: TBluetoothSocket;
end;
begin
while not Terminated do
Most of this class is protected so descendants have begin
access to extend the functionality. It could be locked LSocket := FSocket.Accept(FTimeout);
down further or opened up more but all developers if LSocket <> nil then
begin
should avoid over designing.
ReadAvailableData(LSocket);
SendAvailableData(LSocket);
Client end;
The client thread is capable of reading and writing to Sleep(500);
the socket passed as a parameter at its creation; end;
end;
however it is slightly different from the server thread.
The client thread is responsible for making sure it is This is where we stop for this article. We have a client
connected to the server before attempting to read and server which happens to be the same application
data from or send data to the socket. which can send and receive plain text for display.
The Execute method for the client thread checks the The OnReadData and OnSendData handlers merely
Connected property of the socket and attempts to output the received and sent content into a memo
connect if is not. control.
procedure TClientThread.Execute; procedure TfrmMain.ReadDataHandler(Sender:
begin TObject; const Data: string);
while not Terminated do begin
begin TThread.Synchronize(TThread(Sender),
if not FSocket.Connected then procedure
FSocket.Connect; begin
if FSocket.Connected then ConnectionMemo.Lines.Add(' read: ' +
begin Data);
SendAvailableData(FSocket); end
ReadAvailableData(FSocket); );
end; end;
Sleep(500);
end; procedure TfrmMain.WriteDataHandler(Sender:
end; TObject; const Data: string);
begin
TThread.Synchronize(TThread(Sender),
Once the socket has connected, it can then process procedure
unsent data (if any) and check the socket for begin
additional data. ConnectionMemo.Lines.Add(' write: ' +
Data);
end
Server );
The server thread is instantiated using a end;
TBluetoothServerSocket. This socket class is
not able to read or send any data. It is however
capable of accepting connections initiated by a
TBluetoothSocket. Use the Accept method to
allow another socket to connect. If successful, the
result is a TBluetoothSocket instance that can be
used to read and send data.
The Accept method is a blocking call which takes
a cardinal parameter for Timeout.
This value can be
-1 (never timeout),
0 (instantly timeout) or any other millisecond timeout
value.

20 COMPONENTS
DEVELOPERS 4 Nr 4 / 2014 BLAISE PASCAL MAGAZINE
Using Bluetooth Classic in Delphi XE7 (Continuation 5 end)
As mentioned earlier, the synchronisation occurs in
the execution of the event, instead of while the event
is executed. This technique makes use of anonymous
methods which is still a relatively new feature in
Delphi.

Next Time
The next article will extend the code given in this
article and create a demo which actually uses
different applications for the client and server, and
which also allows connections of multiple clients to
the server and some other points of interest.
Instead of sending raw text between client and server
(the easiest way to demonstrate a connection between
end points) we will implement a custom protocol
format for communicating. Since this will be a full
application, it will also include exception handling
which is absent in the demo application provided.

Conclusion
Hopefully this article has given some insight into the
Bluetooth Classic support available in Delphi XE7.
I've highlighted what platforms support Bluetooth
Classic and provided a fully documented demo
application which I hope will improve understanding Figure 8:
Sport actvity app
of this topic.
About the author
Jeremy North
owns a company called JED Services Pty. Ltd,
which includes JED Software.
He sells his components and IDE experts
through JED Software and does contracts under
JED Services.
He works exclusively on Win32 at the
moment and has also done quite a bit of .Net in
the past. He wrote most of the initial release of
the Ribbon controls for Delphi 2009.

Figure 8: More Apple items

Nr 4 / 2014 BLAISE PASCAL MAGAZINE


COMPONENTS
DEVELOPERS 4 21
DAVID DIRKSE
presales at
www.blaisepascal.eu/DavidDirkse/ComputerMath_Games.html

procedure ;
var
begin
for i := 1 to 9 do
begin

end;
end;

BLAISE PASCAL MAGAZINE


is proud to announce the first
edition of David Dirkses book:

COMPUTER MATH &


GAMES IN PASCAL
22 Nr 4 / 2014 BLAISE PASCAL MAGAZINE
3D Printing Lab By Max Kleiner maXbox Xb ox
We need an API For each layer, the ma
3D printing or additive physical manufacturing is (virtual in the simulation script) laser beam traces a
a process of making three dimensional solid cross-section of the part pattern on the surface of the
objects from a digital file like a CAD Stereo liquid resin. Exposure to the ultraviolet laser light
lithography (SLA). The topic is huge and the cures and solidifies the pattern traced on the resin
applications include research (so in our school),
and joins it to the layer below.
design visualization, prototyping/CAD/CAM, metal
and box casting, architecture, education,
So the main technology in which
geographical topology, healthcare and also photopolymerization is used to produce a solid part
entertainment and amusement. from a liquid is SLA, mentioned in the first line of
Such an amusement was a flyer I have seen a this report.
while ago with the following content: The Future
is now! And what they told us is more fun than By the way this technique was invented in 1986 by
future, that you can get your portrait or family Charles Hull, who also at the time founded the
portraits by 3d printing. The company say they company, called 3D Systems.
can scan virtually anyone, including babies,
children, monsters, dogs, cats or rats.
The figures are made using an eco-friendly
The fact that the topic is so large we start with a real
material called high-performance composite. A API of the Doodle3d Interface. We also focus on
3D printer creates the objects from a white a less often discussed feature of open source printers
powder (not resin) which is laid out layer by layer and models and I want to highlight, or should I say
and solidified by multiple jets across the ground. stress, some of the practical problems that can arise.
As you may know these codes are widely used in
It's hard to imagine but take a look at this slicing the web of things or embedded computing industry;
simulation and you get the idea: Beside the fact that many firmware is about new
ideas, prototyping, concepts and new technologies
https://github.com/maxkleiner/maXbox3/blob/ma that are in the lab, we start with end-users,
sterbox2/examples2/356_3D_printer.txt programmers and products for:

Then load the script 356_3D_printer.txt in the box an Electronics and Gadgets
run it. It produces a pic like this: 3D Printing Production
Modelling and Entertainment Pictures

Nr 4 / 2014 BLAISE PASCAL MAGAZINE maXbox 23


3D Printing Lab (Continuation 1)
3D Interface as Printerface penDown:= true;
setpos(180, 430);
Doodle3D supports almost all open source printers
cPort.WriteStr(chr(180));
(because their firmware is usually based on Marlin, more
//# marlinServo body
below), this includes printers like the Ultimaker, //turn(aturn)
PrintrBot, Delta RostockMax. They also support the sleep(1000)
Makerbot printers and printers that use the same left(180)
firmware. cPort.WriteStr(chr(180));
sleep(1000)
moveforward(100)
Doodle3D is a product line for 3D printing. right(90)
The Doodle3D WiFi-Box makes almost all 3D printers cPort.WriteStr(chr(120));
wireless controllable through a simple REST API
(second part). This means you can control them using The point is that through this piece of Turtle G Code,
Processing with open Frameworks, JavaScript, Pascal, the head will be moved from its current position to X,
Lazarus, Arduino, Cinder etc. Y position 180.0 which in this case is an angle. The Z
Basically any language that can send and receive position is missing. This will happen at the last speed
HTTP requests (AJAX). setting (feed-rate, F) that was sent, depending on the
printers specification in FDM or FFF technology:
Lets start with G-Code.
In fundamental terms, G-code is a
language in which people tell
computerized machine tools what
to make and how to make it.
The "how" is defined by instructions
on where to move to, how fast to
move, and along what path to move.
The G-Code we focus on is based
on what is supported by Marlin
and this software (firmware) runs
on the 3D printer itself.
Almost all open source 3D printers
use a version of Marlin.
G-Code is a commonly use language
to control CNC machines. It is
light-weight, simple to parse as a
format, designed to be able to run
on modest hardware, such as
Arduino loaded with this firmware
(in this case). It is a format that is
prepared in advance and created
from the digital design files Printing technology: FFF (Fused
(CAD files). Filament Fabrication)
Printing volume: 170x170x160m
G1 X0.0 Y0.0 Z0.0 Layer resolution: 100 (0.1mm)
G1 X10.0 Y10.0 Z0.0 F1000 X-Y-Z precision: 20 (0.02mm)
Filament diameter: 1.75mm
These instructions can then be sent to a machine that Heated bed: No
will interpret these lines and execute them one by Bed autoleveling: Yes
one. The G Code instructions frequently have an X, Y Printing material: PLA (any material
with not a heated bed)
and Z coordinate, these are the points in 3D space
Time to first print-out: <1m
that the print-head will move in. We developed with Injector diameter: 0.4mm
Turtle in maXbox/Arduino these steps to move the Filament capacity: 500gr
print-head: Dimensions: 275x275x360
Approx. weight: 7Kg
Chassis: Unibody aluminum

24 maXbox Nr 4 / 2014 BLAISE PASCAL MAGAZINE


3D Printing Lab (Continuation 2)
Note that the X and Y will expand if you expand the You can think of Doodle3D as the first application
size() and it is possible that you make the printer written on top of the API, it makes 3D printing a
move outside of its border! This can do harm or simple sketch child's play.
damage to your 3D printer!! There are projects, which uses the API to enable
The G-Code firmware source is available from sending a print to your printer. Using the WiFi-Box
Source Forge as part of the RepRap Arduino you could control a printer using a Kinect, influence a
firmware package. print with sound input in a sonar way, maybe create a
Apart from printing your objects, the Doodle3D cup designer or adding an embeddable print button to
WiFi Box will also be able to wirelessly 3D print an existing design application.
more complex 3D models by streaming the GCODE Our API enables you to go to a URL, and retrieve
to your printer. You can also monitor your printers a json or XML object with information. Like retrieving
speed, temperature and progress. status info using the following URL snippet:
But wait a minute, what is RepRap?
{IP address of WiFi-
RepRap is a general-purpose self- Box}/d3dapi/info/status
replicating manufacturing machine.
RepRap takes the form of a desktop 3D printer The call could be that simple:
capable of printing plastic objects. Since many parts
of RepRap are made from plastic and RepRap prints import httprocessing.*; TurtleSim
String boxIP = "10.0.0.188";
those parts, RepRap self-replicates by making a kit of PostRequest post = new PostRequest(
itself - a kit that anyone can assemble and build given "http://"+boxIP+"/d3dapi/printer/print");
time and materials. void setup() {
But which RepRap to choose?
post.addData("gcode", "G28 X0.0 Y0.0 Z0.0");

// Send printer to the x0 and y0 position

post.addData("start", "true");
post.send();
size(100, 100);

This is so simple because Doodle3D provides a


service called host module we use.
The parts that connects users wirelessly to their
printer (or more specificly the controller) are:

The web (websocket / REST) API,


The logic to connect to networks and talk to the
Controller.

So in my opinion the Prusa I3 (picture) or Mendelmax


is well appreciated and documented in the
community.
For about a thousand dollars people have been
able to buy the RepRap kit and put together their
own personal 3D printer, complete with any
customizations they were capable of making.
What really speeds the development is the open
source idea and made some prototypes to share.
Using 3D printers for these purposes is called rapid
prototyping.
But whats the matter with the REST API?
Simply that each thing, device or gadget will have an
REST API to communicate, could also be a code to
implement.

Nr 4 / 2014 BLAISE PASCAL MAGAZINE maXbox 25


3D Printing Lab (Continuation 2)

So in a next number we will go deeper in that Feedback @ max@kleiner.com


API Code and we will made some calls. Literature: Kleiner et al.,
Concerning G-Code is still under research. Patterns konkret, 2003, Software & Support
For example a Web-Interface means that most of the
proposals are too large, had an unusable interface or Links of maXbox, 3D Printing and Web of Things:
are unsupported for various reasons. http://www.slideshare.net/maxkleiner1/
Node.js for instance, cannot be used because it a-3d-printing-solutionekon
cannot currently be built for MIPS processors (issues http://www.softwareschule.ch/download/
with big endian instructions). webofthings2013.pdf
Python is simply too big, even python-mini http://3dprinting.com/what-is-3d-printing/
leaves only about 200 KB on the device even without http://www.doodle3d.com/help/
api-documentation
any dependencies.
http://replicat.org/mcodes
To keep the firmware code simple and consistent it http://www.doodle3d.com/help/g-code
will only handle G-code. So the G-code will be
generated using javascript or another scripting
language.

26 maXbox Nr 4 / 2014 BLAISE PASCAL MAGAZINE


Don't Miss Out!
Offer Extended plus Exclusive Training Session

Don't miss out on your upgrade discount up to 45% off


For a limited time, users of any earlier version qualify for the upgrade price.
Upgrade eligibility for registered users of RAD Studio, Delphi and C++Builder
XE2 or earlier ends 31 December 2014. Recharge eligibility for XE6 registered
users also ends 31 December 2014 so buy now.
Upgrade to Enterprise edition or higher for the best value!
With Enterprise edition and above, you get exclusive additional features and
more bonus items. If you are currently using Professional edition, you qualify
for the Enterprise edition upgrade price, where you get:
Mobile app development with no add-ons required
Built-in Enterprise database connectivity
and multi-tier database connectivity
Advanced XML, coding and modeling tools
Free Rapid SQL, the SQL IDE to create high performing SQL code

Learn more about all the value in RAD Studio XE7 Enterprise version and higher
in these video playlists: Delphi, C++, Rapid SQL.

Just Added:
Free Delphi training with Marco Cant!

Register now to attend this year's most exclusive half-day technical


training with Marco Cantu (value 500). To qualify, all you need to do
is register your RAD Studio, Delphi or C++Builder or trial.
(All other specials are available with paid licenses only)
Free bonus pack and extras for XE7 registered users
Free tools including Castalia and FastCube VCL, Premium Styles, Mida
VCL to FireMonkey converter and Marco Cantu's new Object Pascal
Handbook e-book.

www.barnsten.com Figure5: Raspberry

Nr 4 / 2014 BLAISE PASCAL MAGAZINE 27


Converting Delphi to Lazarus and Vice Versa
starter expert

On the latest Pascon Lazarus event we talked


Unicode support
about conversions from one to the other. Because Versions of Delphi up to Delphi 2007 didn't support
that is a lot to remember, we gathered some Unicode, but used Windows ANSI encoding.
instructions about this. Delphi supports Unicode by using UTF-16 encoded
So most of this is originating from the Delphi and strings from the 2009 version.
Lazarus websites. Lazarus on the other hand started its Unicode
support earlier and uses UTF-8 encoded strings.
Lazarus is an Rapid Application Development
For more information see LCL Unicode Support,
(RAD) tool like Delphi. That means it comes with a http://wiki.freepascal.org/
visual component library and an IDE (Integrated
LCL_Unicode_Support,
Development Environment).
Since Lazarus (0.9.25) it has full Unicode support in
all platforms except Gtk 1.
Differences and Similarities
Even though Lazarus has Unicode widgetsets,
The Lazarus component library (LCL) is very similar
it's important to note that not everything is Unicode.
to Delphi's VCL (Visual Component Library).
It's the responsibility of the developer to know what
Most of the Lazarus units, classes and properties
is the encoding of their strings and do the proper
have the same name and functionality as their
conversion between libraries which expect different
equivalents in Delphi.
encodings.
This makes porting Delphi applications to
Usually the encoding is per library (e.g. a
Lazarus relatively easy. But Lazarus is not an 'open
dynamic library DLL or a Lazarus package).
source Delphi clone'. So don't expect 100%
Each library will uniformly expect 1 kind of
compatibility.
encoding, which will usually either be Unicode
(UTF-8 for Lazarus) or ANSI (which actually means
The biggest differences between Lazarus and Delphi
the system encoding, and may be UTF-8 or not). The
Lazarus is completely open source
RTL and the FCL of FPC <= 2.6 expect ANSI strings.
Lazarus is written in a
platform-independent way
You can convert between Unicode and ANSI using
Lazarus uses the Free Pascal compiler (FPC) the UTF8ToAnsi and AnsiToUTF8 functions from
the (FPC) System unit or the UTF8ToSys and
FPC runs on more than 15 platforms.
SysToUTF8 from the (Lazarus) FileUtil unit.
Not all FPC packages and libraries have been ported
The latter two are smarter (faster) but pull more code
to all 15 platforms, so Lazarus currently runs on:
into your program.
Linux (i386, x86_64)
FreeBSD (i386) FPC is not Unicode aware
Mac OS X (powerpc, i386) The Free Pascal Runtime Library (RTL), and the Free
Windows (i386, x86_64) Pascal Free Component Library (FCL) in current FPC
versions (<= 2.6.x) are ANSI, so you will need to
The first thing to do convert strings coming from Unicode libraries or
when converting a Delphi project to going to Unicode libraries (e.g. the LCL).
Lazarus
Having opened Lazarus, you should go to to Tools There are significant improvements to development
and then Convert Delphi Project to Lazarus Project branches of FPC 2.7.1 with regard to Strings.
(Since Lazarus 1.2.6 the menu structure is Tools -> Delphi See RawByteString and UTF8String in FPC
Conversion -> Convert Delphi Project to Lazarus Project). Unicode support.
This won't do everything for you,
but nonetheless will take you a good deal of the way.
Converting between ANSI and Unicode
Note that the Lazarus IDE's conversion tools are Note: AnsiToUTF8 and UTF8ToAnsi require a
generally one-way conversions. widestring manager under Linux, BSD and
If you need to retain Delphi compatibility (so you can Mac OS X. You can use the SysToUTF8 and
compile your project with both Delphi and Lazarus) UTF8ToSys functions (unit FileUtil) or add the
consider converting your files with the
widestring manager by adding cwstring as one of
XDev Toolkit instead. the first units to your program's uses section.

28 COMPONENTS
DEVELOPERS 4 Nr 4 / 2014 BLAISE PASCAL MAGAZINE
Converting Delphi to Lazarus and Vice Versa (Continuation 1)
Converting Projects For example: You are debugging an application, and
The main file for a Delphi application is its .dpr file. set a lot of breakpoints and bookmarks.
A Delphi .dpr file is both the program main source, You can save the project at any time, close Lazarus or
and also the file where the Delphi IDE stores open another project. When you reopen the project
information about relevant compiler switches and (even on another computer) all your breakpoints,
unit locations. bookmarks, open files, cursor positions, jump
A Lazarus application has a corresponding histories, etc. are restored.
.lpr file, which is also the principal Pascal source
file for the project. Source Editor
However, the main file of a Lazarus project is the Nearly all keys and short cuts can be defined in
.lpi file (Lazarus Project Information), which is Tools -> Options -> Editor -> Key Mappings
created separately - together with the .lpr file. The Lazarus IDE has a lot of tools for sources.
All project-specific information (such as compiler Many of them look and work very similar to Delphi.
switches used, paths to units used etc.) is stored in the But there is one important difference:
.lpi file. Lazarus does not use the compiler to get code
So, the important file is the .lpi file. information. It parses the sources directly.
On most platforms, double-clicking on an .lpi file This has a lot of important advantages:
in the system's file explorer will start the Lazarus IDE The source editor works with "comments".
with that project open. For example: For Delphi the comments in the source are just
Delphi stores the paths of the project's units in the space between code.
.dpr file. No code feature works there and when new code is
For instance: unit1 in 'path/Unit1.pas'; auto inserted, your comments will travel.
These 'in' paths are Delphi-specific and are not Under Lazarus you can do a find declaration even on
read by the Lazarus IDE. Don't use them. code in comments.
Instead, in the Project Options dialog (Project- Although this is not completely reliable, it often
>Project Options...) use the Paths page under works. And when new code is inserted, the IDE uses
Compiler Options to set unit paths where they differ some heuristics to keep comment and code together.
from the project directory path. For example: It will not split the line c: char; //
comment.
Note that most unit paths you will need are set
automatically by the IDE when any package
Delphi's "Code Completion" (Ctrl+Space) is called
dependency is added.
"Identifier Completion" under Lazarus.
For instance, all standard Lazarus LCL projects have
The Lazarus term "Code Completion" is a feature,
the LCL added as a dependency by default, and so
combining "Automatic Class Completion" (same as
any new Lazarus LCL project (Project->New
under Delphi), "Local Variable Completion" and
Project->Application) knows all paths to all LCL
"Event Assignment Completion".
compiled units without further work on your part.
All of them are invoked by Ctrl+Shift+C and the
IDE determines by the cursor position, what is
Delphi stores compiler options in the .dpr file.
meant.
For instance {$APPTYPE CONSOLE}.
These are ignored by the Lazarus IDE.
Packages
Don't use them. Use the Compiler Options page of
Can Lazarus install and use Delphi
the Project Options dialog instead.
Packages?
No, because they require Delphi compiler magic.
No "empty" IDE with Lazarus Do we need ones specially made for lazarus?
One important rule: Yes.
There is always a project. The only way to "close" a Create a new package, save it in the package source
project is to exit Lazarus, or open another project. directory (normally same directory of the .dpk file), add
This is because a Lazarus project is also a "session". the LCL as required package and finally add the
So session information (e. g. the current editor settings) .pas files.
is also stored in the .lpi file and the Lazarus editor
You can install it, or use it in your projects now.
is restored to its last saved state when the project is There are some differences between Lazarus and
later reopened. Delphi packages, so please read
- see docs/Packages.txt in the Lazarus sources.

Nr 4 / 2014 BLAISE PASCAL MAGAZINE


COMPONENTS
DEVELOPERS 4 29
Converting Delphi to Lazarus and Vice Versa (Continuation 2)
VCL versus LCL For example if using a GTK interface, and the gtk
While the VCL and the LCL both serve much of the theme supplies a specific font for buttons, then LCL
same purpose - of an Object Oriented Component buttons will always try to use this font.
Hierarchy especially geared toward rapid application This means that most LCL controls do not have the
development, they are not identical. same level of design control that is often expected in
For instance while the VCL provides many non- the VCL, rather only those custom controls which are
visual components, the LCL tries to only provide Canvas drawn instead of interface allocated can
visual, while most non-visual components (such as db consistantly be modified in this manner regardless of
access) are provided by the FCL, included with Free the Interface used.
Pascal .
TDBImage
Additionally many controls may not exist in the LCL Delphi and Lazarus both have a TDBImage control
that are in the VCL, or vice versa, or even when that shows images stored in a database field.
controls do exist in both, they are not clones, In current stable versions (1.2.4), Lazarus stores
and changes must be made in applications, information about the image type in the database
components and controls if porting. field before the actual image data.
See procedure TDBImage.UpdateData .
The following is an attempt to provide fairly
complete descriptions of major differences or Note: This means that Delphi and older Lazarus
incompatiblities between the two for the Delphi user. implementations are not compatible.
It covers differences primarily with the VCL of D4
especially, though at times D5, D6, or D7 as well; Current stable Lazarus (1.2.0+) has implemented
and with the current LCL, as is in CVS. changes that allow Delphi compatible behaviour.
As such it may not always be accurate to the version
of Delphi you are used to, or completely match the Please see http://wiki.freepascal.org/
Lazarus_1.2.0_release_notes#TDBImage
current LCL you have.
for details on how to activate this.
Current Lazarus trunk falls back to Delphi-
TControl.Font/TControl.ParentFont
compatible behaviour on reading Delphi-formatted
In the VCL it is quite common and normal to use a
database fields into TDBImage.
specific font name and font properties such as bold
and italics for controls, and expect this value to
always be followed. Messages / Events
The order and frequency of messages and events
Further is provided the TControl.ParentFont
(OnShow, OnActivate, OnEnter, ...) differ
property which ensures that a control will always
from the VCL and depend on the widgetset.
follow its parent's font.
(Widgetsets support platform-sensitive development with
Again the implicit assumption being that these values
the Lazarus IDE. They act as adapter libraries that provide
will always be followed, even regardless of Windows an interface between a platform-inpedentent sourcecode
Apearance Settings. This is not always true in the written in Free Pascal and platform-specific system
LCL, nor can it be. functions. Thus they allow for development of
The LCL being cross-platform/cross-interface in platform-native software without requiring to
nature prefers to take a balanced aproach, provide specific source code for different target
and instead will always try to use native platforms.
Desktop / Toolkit Apearance or Theme settings on Widgetsets act as basis for the Lazarus Component Library
any widgets. (LCL).)
Widget set Supported Operating Systems Status
Windows API, GDI Windows Mainstream use
Windows CE API, GDI Windows CE Mainstream use
GTK+ 1.2.x Linux (via X11) Deprecated
GTK+ 2.8+ Windows, Linux (X11 and framebuffer)
and Mac OS X (via X11) Mainstream use
GTK+ 3.x As Gtk2 Alpha
Qt 4.5+ Windows, Linux (X11 and framebuffer),
Mac OS X Mainstream use.
Works in Windows,
Linux, Mac OS X, Maemo, etc
Cocoa Mac OS X In progress
Carbon Mac OS X Mainstream use
fpGUI Windows, Windows CE,
Linux (via X11) Initial stage
Lazarus Android, Windows, Linux (via X11),
Custom Drawn Controls Mac OS X Initial stage

30 COMPONENTS
DEVELOPERS 4 Nr 4 / 2014 BLAISE PASCAL MAGAZINE
Converting Delphi to Lazarus and Vice Versa (Continuation 3)
The LCL provides a subset of WinAPI like messages License selection is especially important with
to make porting of Delphi components easier, components since dropping one on a form can
but almost all LCL messages work a little bit different impose an unwanted or incompatible license on an
than the VCL/WinAPI counterpart. entire application.
The biggest part of Delphi code using WinAPI When converting components, please respect the
messages uses them, because the VCL lacks a feature wishes of the original author and retain all copyright
or for speed reasons. and licensing headers along with email addresses
Such things will seldom work the same under and url's.
the LCL, so they must be checked manually. It's courteous and often useful to inform the author
That's why LCL messages are called for example that their component is being converted... especially
LM_SIZE instead of WM_SIZE (unit lmessages). if the component is under a restrictive license.
Note on handling of custom messages! New interest in an old or forgotten component can
As of version 0.9.26 (December 2008), way of sometimes inspire authors to revise their original and
handling custom WinApi messages overly restrictive licensing.
(e.g. WM_HOTKEY, WM_SYSCOMMAND) differs
In general, Public Domain (freeware), and the
from the way of handling these messages in Delphi.
LGPL/MPL are the the most flexible for distributing
At the moment you cannot handle them via
components.
message directive or via overriding of WndProc
For more information, the Open Source Definition is
method of the form. The only way to handle them in
the form is to hook Windows windowproc by a good place to start. There are also several
yourself. comparisons available to help clarify how the various
Read more here: types of licenses work and what impact they'll have
http://wiki.lazarus.freepascal.org/Win32/64_ on code they're linked to. Search for "open source
Interface# license comparison"
Processing_user_messages_in_your_window
This page is about how to port or convert existing
Delphi code to work with the Free Pascal Compiler Doing the conversion
Setting up the Lazarus environment
and Lazarus IDE.
While Lazarus and the Free Pascal Compiler have for a conversion project
aspects in common with Delphi, they are not clones.
There are a number of library call and convention Create a test projec
differences... Place code to be converted into a subdirectory
and in some areas, FPC is enhanced and can be more (ie: convertdir)
demanding about correct syntax. Bring up Lazarus
Please see the Lazarus For Delphi Users guide for a File->Save All to the convertdir subdirectory.
description of some of the functional differences. Meaningful names for the Project and default
unit are optional.
Where to find code to convert Open the "main" unit to be converted in
There is a LOT of code available on the net that can convertdir
be converted for use with FPC and Lazarus. Add it to the project:
Here is a Page Of Code Sites that is just a start: Project->Add Active Unit to Project
http://wiki.freepascal.org/Page_Of_Code_Sites Run Tools->Quick Syntax Check or Run
To avoid duplicating effort, packages that have Build All to get started.
already been converted are listed on the Components
and Code examples page Initial items to watch out for
http://wiki.freepascal.org/ Filenames are case sensitive with the 1.0.x series
Components_and_Code_examples.
compilers. If you're working with this version,
make all your filenames lower case.
Licensing
You'll get "File not found" errors if you don't.
Licenses for existing code range from freeware /
public domain to restrictive versions that prohibit
Delphi VCL Sources in Lazarus
modification, re-distribution and commercial use.
When converting Delphi sources, it is often useful to
Before converting any package, it's a good idea
do a find declaration to see, what a specific function
to examine its licensing and make sure it's going to be
is doing.
compatible with Lazarus and the Free Pascal
The Lazarus IDE can parse the Delphi sources.
Compiler.
To do this it needs some searchpaths and compiler
settings. You can easily setup this in Environment-
>CodeTools Defines Editor->Insert Template

Nr 4 / 2014 BLAISE PASCAL MAGAZINE


COMPONENTS
DEVELOPERS 4 31
Converting Delphi to Lazarus and Vice Versa (Continuation 4 - End)
Another method to convert a Delphi or Dependencies
Kylix project to Lazarus Another step before starting to work on a conversion
Rename or copy all .dfm or .xfm files to .lfm is to verify that the code doesn't have deep
(Very old Delphi versions do not produce a text-based dependancies on other packages that might not be
.dfm file. The convert utility, if present in the \bin available or represent a considerable conversion
folder can be used to convert the .dfm first)) challenge. Some freeware offerings are bound to or
Rename or copy .dpr file to .lpr extend proprietary packages that are frequently no
Make all necessary changes to .lpr file: longer available or come with inappropriate licenses.
1. Add {$mode delphi}{$H+}
or {$mode objfpc}{H+} directives Compiler Issues See: Known problems
2. Add 'Interfaces' to uses clause
3. Comment out or delete {$R *.res}
or directive if needed Platform and OS Issues
Lazarus and the Free Pascal Compiler are cross-
Make necessary changes to all .pas unit files: platform and cross-architecture development tools.
1. Add {$mode delphi}{$H+} In contrast, most existing Delphi code was
or {$mode objfpc}{H+} directives specifically designed to run on an Intel processor
2. Add 'LResources' - to do: check if this is still under Win32. If your candidate component has a lot
needed for any vaguely new Lazarus version of Win32 specific code, it might be wise to try and
3. If the form has buttons, add 'Buttons' find a less platform dependent alternative.
to uses clause But don't let this stop you... it's genuinely amazing
4. Comment out or delete {$R *.dfm} what the LCL supports!
or {$R *.xfm} directive
5. Add 'Initialization' section at the end of each
unit file, and add {$I unitname.lrs} directive in it
Select Project->New Project from file
Select the .lpr file
In the 'Create a new project' window, choose
'Application
Build project and make further necessary
corrections to get proper compilation. At this
point the .lpi file is generated automaticaly. You
may get 'Error reading Form' messages, click on
'Continue Loading' if you do.
Save all, and you have a Lazarus project

Conversion problems and solutions Delphi file equivalents in Lazarus


Delphi / Kylix Description Lazarus Description
.pas Delphi Source File, .pas, .pp Pascal unit file,
.dfm/.xfm, Delphi Form, .lfm, Form data file,
.dcu/.dpu, Delphi Compiled Unit, .o, Compiled unit file,
.dpr(main project file), Delphi Project, .lpr Project file,
.res, Windows Resource File, --- Resource file,
.dof/.kof Delphi Option File --- Project options file,
--- .lrs, Lazarus resource file,
--- .lpi(main project file), Lazarus project information file,
--- .ppu FPC unit description file

32 COMPONENTS
DEVELOPERS 4 Nr 4 / 2014 BLAISE PASCAL MAGAZINE
Dienstverlening:
Project-/Requirements-management
Consultancy/Projectbegeleiding/ondersteuning
Software Audits | Software ontwikkeling
Database management | Detachering

Branches:
Productiebedrijven | Importeurs/Distributeurs
Groothandel/detailhandel
Logistiek | (Sociale) Woningbouw

Projecten:
Administratieve systemen
(o.a. Inkoop/Verkoop/Voorraadbeheer/logistiek)
Planningssystemen
(o.a. Productie/Inkoop/Voorraad)

Techniek:
Delphi | InterBase | Firebird | SQL Server | MySQL

better office benelux | asterlaan 6 5582EH waalre | 040 222 26 43


gtan@better-office.com
BLAISE 2014
Lazarus for beginners by Howard Page-Clark
starter expert Information in the wider world is
sometimes clearly digital, particularly numerical
STARTING TO PROGRAM information. Numbers other than 0 and 1 can be
represented as combinations of 0s and 1s. This is familiar
What is programming?
to people who have studied binary arithmetic. It is possible
Computer programming is the art of making a computer do
to count using only the digits 0 and 1 rather tedious, but
exactly what you want without errors. Computers have as
possible. In this severely digit-limited binary system it is
their brain one or more central processing units (CPUs)
obvious which digits represent zero and one. But by
containing numerous miniature electrical circuits in which
combining 0 and 1 in logical patterns whose meaning
electrons may or may not be moving, and these circuits can
everyone can agree on, we can also represent the numbers
indicate to the world beyond the CPU whether those
beyond 0 and 1 (even though we deliberately discard the digits
particular electrons are moving or not.
2, 3, 4 etc. which we use in decimal arithmetic, and stick to just 0
and 1). The first few numbers in the binary system are
This simple difference between a circuit that is switched on
written like this Figure 1.
(where electrons move), and the same circuit when it is
switched off (when no electrons move) is the basis of the Decimal 0 1 2 3 4 5 6 7 8
incredible complexity we know as todays software. The
Binary 0 1 10 11 100 101 110 111 1000
computer's circuitry, CPUs, disks, memory, screen and so
on are known as hardware. Patterns of 0s and 1s such as this, then, are the basic
The programs that run on this hardware are termed language of the computer, which is why computers are
software. You can touch hardware, just as you can touch often termed digital devices. We can assign any meaning
the human body with its hands and face. Software is more we want to these patterns of 0s and 1s. If we regard a
like the plans, thoughts and words that a human can pattern of binary digits as integers, then the pattern 1000
communicate the ideas, commands and requests that means the number 8. If, on the other hand we regard the
cannot be physically touched. pattern of binary digits as letter characters, then one
At the lowest level then, a computer can speak a standard meaning of the pattern 1001011 is the capital
language with two words: On and Off (or Yes and No, or if letter K.
we use numbers rather than words to represent the electrical
These are examples of treating a binary digit pattern as
state, 1 and 0). Even the most advanced multi-processor
data, that is, as information that represents an agreed
supercomputers that execute billions of instructions each
arithmetic or alphabetic entity. It is straightforward to
second have this fundamental binary design. It is
agree on a mapping that relates such patterns of bits to
extraordinary in fact how much complexity has evolved
numbers, or to characters, each of which is unique and
from such a simple building block as a circuit that can
discrete.
communicate just one of two possible states: On or Off.
You may know the very old quip: There are just 10
(Engineers may object that the detected difference is between a
sorts of people in the world those who understand binary
High signal and a Low signal rather than strictly a distinction
and those who don't.The state of being either-0-or-1 is the
between On and Off however oversimplifications of this sort are
minimum amount of information we can know. Streams of
par for a beginners' course).
0s and 1s are termed bit patterns, and when we combine
Software complexity is possible because CPU hardware
eight bits of information together that larger amount of
designers and manufacturers have found ways to pack
information is termed a byte. You are probably familiar
literally millions of these circuits into very small chips,
with kilobytes (kB) and megabytes (MB) and gigabytes (GB)
and have found ways to prevent the heat caused by
used as measurement units for hard disk and USB memory
millions of electron movements from melting the chip.
stick capacity, or memory (RAM) capacity installed in a
The complexity is also possible because software engineers
computer or a mobile. These quantify the amounts of
have devised ways to make streams of on/off signals (which
information that can be stored on that device, and let you
is all a CPU can process) assume meaningful patterns that
know how big, say, a particular downloaded file is.
correspond to the world outside a CPU chip.
With some effort, it has proved possible to represent
Understanding the world inside the CPU is termed
even analogue data too (which on first appearance is far from
working at a low level. Understanding the world outside
being digital) by unique bit patterns. Consider the colours of
the CPU is termed working at a higher level.
the rainbow, for instance, that in differing intensities and
brush strokes make up the work of an Impressionist
The worlds inside and outside the CPU
painter. Works of art such as Monet's Water Lilies can be
Computer processors are designed to handle streams of
represented digitally as a collection of millions of points of
on/off signals (or 1/0 signals). Information theory calls a
colour, each colour point itself being represented as one of
state which can be either On or Off (either 1 or 0) a binary
thousands of possible subtle shades of colour.
state, and the knowledge of whether that state is 1 or 0 is a
The result of such digitisation is that even complex
piece of information called a bit. Information processed as
colour images in 2-D or 3-D can be translated into a form
bits is known as binary information, or digital information
that computers can process. A corresponding process
since the smallest element of such information, the bit, can
allows music to be translated into mp3 and other formats
be represented by the digits 1 or 0.
that computers can store and process. In this way
There is an unambiguous separation between the two
information that seemed rather unpromising as grist for the
states 1 and 0 (On and Off). Each state is unique and
computer mill has proved to be just that. Provided it can be
discrete. The CPU does not ever mistake one for the other
digitised, the world outside the computer can be
(unless it is faulty). There is no half-On or half-Off.
represented fairly faithfully in the internal world of a
computer's CPU.
Nr 4 / 2014 BLAISE PASCAL MAGAZINE
COMPONENTS
DEVELOPERS 4 35
Lazarus for beginners (Continuation 1)
Not only digital data, but also digital code Hardware that was standard yesterday may be almost
It is also possible, and immensely useful for controlling completely obsolete in just a short time from now. From
computers, to assign instructional meanings to binary the point of view of software developers what is needed is
patterns. One pattern might mean add the next two a single language that is applicable to various different
numbers together, another pattern might mean send the platforms, whatever the underlying CPU, peripherals and
result of the addition to the output. This means we have a operating system.
digital way not only of feeding data to a CPU, but of What most programmers need is a higher level language
getting it to process the data in some way. (higher than assembler) that uses meaningful instructional
Computers are devices designed to process words, whose syntax is closer to the pattern of familiar
information. They do this by receiving everything they instructions such as draw the phrase Free Pascal
need to know about as streams of bit patterns which Compiler on the screen. A language which would shield
represent either the (digitised) data to be processed, or the programmer from having to deal with low-level,
instructions about how to process the data, or both. processor-specific interaction with the CPU's registers and
This is most unfortunate for humans, who find patterns of internal clock cycles.
bits not only tedious and error-prone to write, but High level languages are designed to be close to
meaningless, because we cannot distinguish at a glance the natural languages.
meaning of 1000110101011 from 1000110101001. Indeed, we They combine mathematical symbols with natural
might not even notice there was a difference between these language specifically chosen for communicating with a
two patterns (whereas most people immediately notice the computer's CPU and operating system. High level
difference between the two character patterns dame and damn). languages provide a convenient, comprehensible interface
CPUs are designed specifically to excel at processing such between the programmer and the computer, but they need
bit patterns, whether these bit patterns are machine code to interface to the CPU as well. This is achieved by a
(instructions) or data to be processed (information). process called compiling, in which the meaning of the high
Computer programming means clearly distinguishing level language is translated into the low level instructions
what is data and what is code (instructions) and using the that are the language the CPU can process.
computer's short term memory and long term storage to
keep track of the massive amounts of data flowing in and Pascal: a universal computer language
out of the CPU, while sending the correct instructions (code) Lazarus is a development tool that uses the Pascal
so that processed data then flows to the appropriate place programming language. Niklaus Wirth designed this
(perhaps to the display to be viewed, or to an earpiece to be heard,
computer language to encourage good programming
or to a plotter to be printed). practice, publishing his work in 1970. Pascal uses a small
Different computer languages vocabulary of English words which are all self-descriptive.
at different levels Pascal was extended in the 1980s to be object-oriented, and
The bit patterns (machine code) that instruct the CPU what so the Pascal dialect used in Lazarus is termed Object
to do with the data it receives are not understood by Pascal.
humans. There is a computer language called assembler Object-oriented means that Lazarus uses code
that maps human-readable symbolic instructions to each constructs called objects Lazarus actually calls them
machine code instruction. classes which model real-world situations more
satisfactorily than the original plain procedural Pascal,
Learning and using assembler means working at a very low which was designed to teach programming well. (Pascal
level, dealing with the minutiae of small on-chip memory was not designed originally for commercial-quality software
areas called registers, and paying careful attention to the production, for which it has come to be used since but that is
size of all data and instructions at the level of individual the power and potential of a well-designed computer language).
bits and bytes. This is error-prone, and difficult to master. The Oxford English Dictionary lists over 500,000
The following is a tiny example of the sort of English word forms, and there are about the same number
instructions assembly language uses: of additional unlisted English technical and scientific
terms. By contrast, Object Pascal (as used in Lazarus and Free
movl (%esp),%eax Pascal) has just over 70 reserved words (or keywords), and
addl $5,%eax you will use less than half of those regularly. In terms of
vocabulary, then, learning to use Pascal is far easier than
learning to speak English! Here is a selection of the most
Assembler programming has the further disadvantage that commonly used words in the Pascal language (notice that
it is processor-specific. Instructions that work on one one or two like const and var are abbreviations of longer English
manufacturer's processor may not work or even have an words):
equivalent on another make of processor. Just as a car
and file or then
mechanic knows that a VW alternator will not fit as a
array for procedure to
replacement for a faulty alternator on an Audi. Little about begin function program type
hardware is standardised to the extent that different class if property unit
manufacturers' parts are interchangeable or software- const implementation record uses
compatible. The situation is complicated further by do interface repeat var
increasingly rapid technical advances which render the else not set while
entire spectrum of IT devices a constantly changing end of string
marketplace.

36 COMPONENTS
DEVELOPERS 4 Nr 4 / 2014 BLAISE PASCAL MAGAZINE
Lazarus for beginners (Continuation 2)
Rather than diving into details about the Pascal language at
this point, we shall look now more closely at Lazarus, the
main tool you will be using to write Pascal code. Details of Lazarus IDE Pascal
Pascal syntax and usage follow in later chapters. Code
FPC (text)
Free Pascal
Lazarus: an IDE for Pascal Compiler Object
High level computer programming languages, including Code
Pascal, allow the programmer to use a specialised language Internal or (binary)
(nearly always based on English) to give instructions to the External
computer's CPU. The CPU does not understand Pascal, so Linker
Executable
the Pascal code has to be changed into digital electronic Applcation
Operating (binary file)
signals that the CPU can accept. This translation process System
(producing machine code that a CPU can accept) is called
compilation and assembly.
Sections of compiled, assembled code then require
linking (that is, joining together appropriately) to produce an
executable program file that the operating system can run. Figure 2 The software and
Lazarus uses the Free Pascal Compiler (FPC), which on CPU and other hardware needed to develop an
some platforms has its own internal linker, to transform hardware application that runs on a computer
Pascal code into an executable program.
Lazarus and similar programming tools such as Eclipse An open source approach to software
Since 1998 the phrase 'open source' has been officially
and Visual Studio are termed Integrated Development
sanctioned to designate that category of software which
Environments or IDEs because they integrate in one
publishes its source in the public domain. This radical
toolbox the many functions that are needed for you to
approach to software development has flourished
produce an executable program starting with only an idea,
alongside the long-established closed source, commercially
and no written code. The Lazarus IDE provides:
licensed software typical of the products of many of the IT
companies that mushroomed in the latter part of twentieth
an exceptionally versatile text editor with numerous
century.
features designed for rapidly writing, modifying and
Most open source software is free (no payment is charged),
navigating your program source code
and all of the source code is publicly available. This means
a visual editor for designing your
that it can be continuously corrected and improved by a
program's user interface (UI)
large community of interested people, none of whom may
three major libraries of ready-to-run code routines
be employees whose wages depend on their work for the
and components: the RTL, FCL and LCL
project. Knowledgeable users who find bugs can submit
tools to compile, assemble and link your program's
solutions (known as patches) which, if accepted, improve
modules into a finished executable
the software for all subsequent users, often within a matter
tools to analyse, test, document and debug the code
of days following the discovery of the bug. Patches might
you write
also be improvements or enhancements adding new
The Lazarus IDE includes many specialised ancillary functionality, not related to bugs at all.
components including tools which aid in: Open source software usually has many, many versions.
Often a new 'bleeding edge' version is available daily. This
setting initial values for individual program components is true of both the Free Pascal Compiler (FPC) and the
such as typeface, width, colour Lazarus IDE that are principal topics in this book.
debugging programs However, periodically a 'release' version is tagged and
writing specialised forms such as dialog windows numbered. This is a version that has received extensive
preparing programs for internationalisation and testing in the field (including use in commercial programs
translation of included texts developed using Lazarus/FPC), and for which bug fixes have
converting Delphi projects into Lazarus/Free Pascal been found and applied for known bugs identified up to
projects the point of the release.
customising the formatting of source code Screenshots in this book are based on Lazarus 1.0 which
creating data dictionaries and writing boilerplate code was released on 29th August, 2012 and a bug-fix release
for object-database mapping Lazarus 1.0.4 dated 3rd December 2012. It uses the Free
code analysis and review Pascal Compiler version 2.6.0 which was released on 1st
testing code modules January 2012. Version 2.6.2 was about to be released as this
documentation of routines, libraries and programs book went to press. If you are using a later Lazarus (or Free
Pascal) release the code examples should work identically,
The following illustration depicts the process which starts but you may find some screenshots do not match your
with writing high level Pascal code in the Lazarus IDE version exactly. Windows is the most popular Lazarus
right through to creating and running the final executable platform (if SourceForge download statistics are a reliable
application. guide), and this book's screenshots are based on a 32-bit
Windows 7 Lazarus installation.

Nr 4 / 2014 BLAISE PASCAL MAGAZINE


COMPONENTS
DEVELOPERS 4 37
Lazarus for beginners (Continuation 3- End)
If you are working on Ubuntu or other Linux, or Mac OS X,
or on one of the various other Lazarus-supported platforms
you will of course find this book's screenshots somewhat
different from the appearance of Lazarus running on your
operating system with your current theme. However
Lazarus is truly cross-platform. Both the IDE itself and the
code examples that come with it compile on all supported
platforms, both 32-bit and 64-bit.

Getting help
Experienced software developers often encounter coding
problems. How much more likely is this for beginners! But
your choice of Lazarus to learn programming is a good one
for several reasons.

Figure 3. Great news:


Lazarus uses Pascal, one of the best languages for a there is a
beginning programmer to learn. Moreover the better open fantastic film spotted
source projects attract and consolidate a community
around them. Not only are there the core developers (in the about our future:
case of Lazarus this is currently a team of about twenty regular
contributors) but scores of other experienced people who are
involved in the project as users, testers, bug reporters,
INTERSTELLAR:
patch submitters, translators, documenters, contributors to their main computers
the forums and mailing lists.
are programmed with:
To get help in the Source Editor of the Lazarus IDE you place the
cursor somewhere in the word you want help on and press [F1]. If
that is unhelpful you can also consult the wiki:
LAZARUS
http://wiki.lazarus.freepascal.org

You can browse the Lazarus and Free Pascal forums and mailing
lists where you can pose questions and ask for (or offer) assistance
on specific problems. This is the main Lazarus forum link:
http://www.lazarus.freepascal.org/
index.php?action=forum

Of course you might encounter a lunatic on one of the forums (as


you might anywhere on the web), but generally the Lazarus and
Free Pascal online community is a source of help, support and
encouragement. You can also download and consult the
documentation. Indeed you would be daft to overlook such a vast
and generally well-organised resource. Most of the information in
this book is based on it.
http://sourceforge.net/projects/lazarus/
files/Lazarus%20Documentation

Or you can search one of the mailing list archives such as:
http://lists.lazarus.freepascal.org/
pipermail/lazarus

There are several free online tutorials available which offer


alternatives to the material presented here. One of them can be
found here: http://wiki.lazarus.freepascal.org/
Lazarus_Tutorial

38 COMPONENTS
DEVELOPERS 4 Nr 4 / 2014 BLAISE PASCAL MAGAZINE
RASPBERRY PI

BLAISE PASCAL MAGAZINE


is now a supplier of all
products of Vogelaar Electronics
Check our website for full details.
http://www.blaisepascal.eu/index.php?actie=./subscribers/UK_Electronics_Department
TMS XData and TMS Aurelius By Wagner Landgraf
Learning by Example DBDemos database
To get things running really
In this article we will show you how to use TMS XData fast, we will use the existing
and TMS Aurelius to create an HTTP Server which
publishes server objects through REST/JSON. Delphi XE7 DBDemos database that is provided with
will be used. Delphi/RAD Studio install. It's an Interbase database
TMS Aurelius is a Delphi ORM framework library (so you need an Interbase server installed and running)
from TMS Software. ORM stands for Object-Relational
and it's usually located in directory
Mapping which means mapping existing database tables
and columns to classes and its fields/properties. In C:\Users\Public\Documents\Studio\15.0
short, an ORM library helps you retrieve data from \Samples\Data\dbdemos.gdb.
database as objects so you can write all your code in a Also, we will only publish the Customers table.
more object-oriented way without worrying about SQL
statements and low-level mechanisms to access the
database. 1. Setting up the database connection
TMS XData is a framework that allows you to create using FireDac
an HTTP Server that publishes those objects (Aurelius (DBDemosModule unit)
entities) to clients through a REST/JSON interface, using A) Create a new TDataModule , name it
predefined URL conventions so you don't have to worry dmDBDemos and save the unit with name
to manually create the URL that retrieves each type of
object.
DBDemosModule.
From now on we will explain, step by step, how to B) Drop a TFDConnection component on it
create such server using Delphi, and at the same time C) Double-click the FireDac component and
we will explain the code and the concepts used, so even
configure the connection settings to the
if you are not familiar with those tools you will be able to
understand what is being done. DBDemos database. Usually it will look like
the following screenshot.

40 productivity software building blocks Nr 4 / 2014 BLAISE PASCAL MAGAZINE


TMS XData and TMS Aurelius (Continuation 1)
Your settings might be different of course, but This unit declares a class named TCustomer and
usually you need to set the DriverID to IB uses Aurelius attributes (declared I unit
(Interbase), set user name and password to default Aurelius.Mapping.Attributes) to map it to
Interbase ones (sysdba/masterkey) and specify the database. The first attributes added to the class
the location of the dbdemos database. are Entity (which just indicates that the class is an
Aurelius entity class).
Be sure your connection is working fine by setting
Connected property of FDConnection1 The Automapping attribute is very handy in our
component to true at design-time (then false again to example. It uses some conventions to perform
make sure the component is created disconnected) automatic mapping so we don't need to do most of
mapping ourselves. Some of the conventions are:
2. Creating Aurelius entity classes and
mapping to database
(DBDemosEntities unit) The table name is the class name without the
Create a new unit named DBDemosEntities initial T. So, it will map the class
with the following code. TCustomer to table Customer;
unit DBDemosEntities; Each class field is mapped to a table column;
The column name is the field name without the
interface
initial F. So, the field FCountry for
uses Aurelius.Mapping.Attributes; example will be mapped to table column
Country;
type
[Entity, Automapping] If the field name has non-lowercase characters,
[Id('FCustNo', TIdGenerator.None)] they will be separated by underline (_).
TCustomer = class For example, a field named TaxRate
private
FCustno: double; would be mapped to a table column
FCompany: string; Tax_Rate. That is why we named some
[Column('Addr1', [])]
FAddr1: string; properties with lowercase chars only.
[Column('Addr2', [])] Our FTaxrate field will be mapped to
FAddr2: string; table column Taxrate (which is the correct
FCity: string;
FState: string; name in DBDemos database)
FZip: string; If the class has a field named FID (case-
FCountry: string; insensitive), then set it as the object identifier
FPhone: string;
FFax: string; (primary key)
FTaxrate: double;
FContact: string;
Since we are going to use the existing DBDemos
FLastinvoicedate: TDateTime;
public Customer table, we made sure to set the class
property Custno: double and property names having those conventions in
read FCustno write FCustno;
property Company: string mind so we don't need to map much of our class.
read FCompany write FCompany; But TMS Aurelius is flexible enough so you can
property Addr1: string build the class in any way you want and just use
read FAddr1 write FAddr1;
property Addr2: string attributes to map to an existing database.
read FAddr2 write FAddr2; We actually had to use two specific attributes to
property City: string finish our mapping:
read FCity write FCity;
property State: string [Id('FCustNo', TIdGenerator.None)]
read FState write FState;
property Zip: string read FZip write FZip; Since our table doesn't have an FID field, we had
property Country: string
read FCountry write FCountry;
to use the [Id] attribute to tell Aurelius that our
property Phone: string primary key is FCustNo field (which will be
read FPhone write FPhone; mapped to CUST_NO column) and specify that such
property Fax: string read FFax write FFax;
property Taxrate: double
identifier will be manually generated
read FTaxrate write FTaxrate; (TIdGenerator.None).
property Contact: string
read FContact write FContact;
property Lastinvoicedate: TDateTime Finally, we used the [Customer] attribute to
read FLastinvoicedate manually map a class field to the table column:
write FLastinvoicedate;
end; [Column('Addr1', [])

implementation If we didn't do that, the FAddr1 field would be


mapped to Addr_1 column which is the incorrect
initialization
RegisterEntity(TCustomer);
one.
end. productivity software building blocks
41
TMS XData and TMS Aurelius (Continuation 2)
Finally, we just called The unit is very simple and the key part is in
RegisterEntity(TCustomer); StartMyServer procedure, which does the
at the end of our unit only to make sure the linker following things:
won't remove TCustomer class from our
application. That is it, our Aurelius classes and A) Create an HTTP Server (listener)
This is done by this single line:
mapping are finished.

3. Creating the server (MyServerUnit unit) MyServer := THttpSysServer.Create;

The third unit we need is the one that implements


and starts the TMS XData server itself. The THttpSysServer class works as the
HTTP Listener
The unit will only have two procedures:
(using modern http.sys stack)
StartMyServer and StopMyServer.
and that you can plug modules into it.
Create a new unit named MyServerUnit with
Each module has an URL it responds to (you can
the following code.
relate to endpoint concepts).
unit MyServerUnit;

interface B) Create a connection factory


ConnFactory := TDBConnectionFactory.Create(
procedure StartMyServer; function: IDBConnection
procedure StopMyServer; var
Module: TdmDBDemos;
implementation begin
Module := TdmDBDemos.Create(nil);
uses Result :=
Sparkle.HttpSys.Server, TFireDacConnectionAdapter.Create(
Aurelius.Drivers.FireDac, Module.FDConnection1, Module);
Aurelius.Drivers.Interfaces, end);
Aurelius.Drivers.Base,
Aurelius.Sql.Interbase, The connection factory is used by the XData
XData.Aurelius.ConnectionPool,
server to create a new database connection
XData.Server.Module, DBDemosModule;
(IDBConnection Aurelius interface)
var whenever it's needed. To do so, you just create a new
MyServer: THttpSysServer; TDBConnectionFactory class
procedure StartMyServer; (which implements the
var IDBConnectionFactory interface) passing an
ConnFactory: IDBConnectionFactory;
begin anonymous method in the Create constructor that
if MyServer = nil then returns a new IDBConnection interface.
begin Whenever XData needs a new database connection, it
MyServer := THttpSysServer.Create;
will execute that method.
ConnFactory := TDBConnectionFactory.Create( You can implement the method in any way you
function: IDBConnection
var
want. But since we have created a TDataModule
Module: TdmDBDemos; with an existing FireDac connection, it is way easier
begin to use it. So we just create a new instance of our
Module := TdmDBDemos.Create(nil);
Result := TdmDBDemos data module, and use Aurelius'
TFireDacConnectionAdapter.Create( FireDac adapter to create an IDBConnection from
Module.FDConnection1, Module); the existing TFDConnection component.
end);

MyServer.AddModule(TXDataServerModule.Create( Note that you can use adapters for many other
'http://+:80/tms/dbdemos/rest',
TDBConnectionPool.Create(
database-access component libraries than FireDac
15, ConnFactory))); (dbExpress, dbGo/ADO, IBX, NexusDB,
end; ElevateDB, etc.). The second parameter of
MyServer.Start;
end; TFireDacConnectionAdapter Create method
just indicates what object must be destroyed when
procedure StopMyServer;
begin
IDBConnection interface reference count reaches
if MyServer = nil then Exit; zero (we want the data module to be destroyed).
MyServer.Stop;
end;
C) Create an XData Module and add it to
initialization the HTTP Server
MyServer := nil; MyServer.AddModule(TXDataServerModule.Create(
finalization 'http://+:80/tms/dbdemos/rest',
MyServer.Free;
TDBConnectionPool.Create(
end.
15, ConnFactory)));

42 productivity software building blocks Nr 4 / 2014 BLAISE PASCAL MAGAZINE


TMS XData and TMS Aurelius (Continuation 3)
Now we created the TXData module which root 5. Reserving the URL in Windows
URL will be /tms/dbdemos/rest on port 80. TMS XData HTTP server is based on http.sys
The second parameter provides a connection pool Windows kernel.
that will be used by XData to manage the database Basically it's an HTTP server that is at Windows level
connections. We have configured a maximum of 15 (not IIS level).
database connections in our pool. This should be To be able to use it, you must reserve the URL your
enough for most medium-sized applications. application is responding to. TMS Sparkle provides
Note that 15 is the maximum of connections used a nice tool for that, named TMS Http Config,
simultaneously by XData. When processing one which is installed when you install
client request, XData grabs one connection from the TMS Sparkle or TMS Business Subscription Trial.
pool only when needed, perform some database
operations, and release the connection to the pool as Just click Add button and type the base address you
fast as possible. Even then, if a database connection is want to reserve:
not available in the pool, it will wait until one is
available, so no error is sent to the client unless of
course a timeout error occurs.

D) Starts the server


MyServer.Start;

4. Creating the main unit and running the


server (MainForm unit)
Most of the server code is done at this point.
All we need now is create a new VCL application,
put a TLabel component in the main form just to
show a status, and add some code in the
OnCreate and OnDestroy events:
unit MainForm;

interface And it will be now listed as one of the reserved URL's:

uses
Winapi.Windows, Winapi.Messages,
System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.StdCtrls;

type
TForm1 = class(TForm)
Label1: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
end; Supported databases for Aurelius
var
Form1: TForm1;

implementation

uses
MyServerUnit;
Firebird
{$R *.dfm} Interbase
Microsoft SQL Server
procedure TForm1.FormCreate(Sender: TObject); MySQL
begin NexusDB
StartMyServer; Oracle
Label1.Caption := 'Server running!'; SQLite
end;
PostgreSQL
procedure TForm1.FormDestroy(Sender: TObject); DB2
begin ElevateDB server
StopMyServer; Absolute Database
end;

end.
productivity software building blocks
Nr 4 / 2014 BLAISE PASCAL MAGAZINE 43
TMS XData and TMS Aurelius (Continuation 4)

You can now run your application to start your server!

6. Testing the server


If we go to the browser and type the root address of our server, this is what we get:

The root address response includes a JSON array that lists all relative URLs available in
the server that publishes objects. Since we have only created TCustomer entity class, this
is what we have currently available. We might have listed here other entities likes
Order, Biolife, etc. If we then try to get URL
http://localhost/tms/dbdemos/rest/Customer, this is what we get:

44 productivity software building blocks Nr 4 / 2014 BLAISE PASCAL MAGAZINE


TMS XData and TMS Aurelius (Continuation 5)

The server now responds with a JSON array D) It will create all TCustomer objects and fill its
containing JSON objects representing each customer properties according to data retrieved from
in our database. That's the magic TMS XData database
does. Since we have told it how to connect to the E) It will serialize all objects as JSON response
database, what entity classes we have and how those based on object properties and existing
classes are mapped to our database, it does mappings
everything for us: F) And send the JSON response back to client

A) Detect that client wants a list of TCustomer You can even perform queries on that objects from the
objects since it asked for relative address URL itself.
/Customer For example, the following URL
B) Connect to the database using one of the http://localhost/tms/dbdemos/rest/
available database connections in the pool Customer?$orderby=Company&$filter=Country eq
'Fiji'
C) Build the correct SQL statement that retrieves
records from Customer table.
will automatically return all customers which Country
Even if our class had associations or filtering
property value is equal to Fiji,
conditions, it will build it correctly,
ordered by Company property.
using INNER JOINS and WHERE, ORDER BY
clauses
If you want to access the URL of a specific customer,
you can pass the customer Id in parenthesis:

productivity software building blocks


Nr 4 / 2014 BLAISE PASCAL MAGAZINE 45
TMS XData and TMS Aurelius (Continuation 6)

The above screenshot shows the JSON representation The previous example just changed the Phone
of the customer with id 1221. property. You could do so by using PATCH method
Such URL representing the customer resource can and just sending the properties you want to change:
also receive HTTP requests for different methods,
PATCH /tms/dbdemos/rest/Customer(1221) HTTP/1.1
allowing data modification. Host: localhost
You can for example change the Phone number of
{
such customer by performing a PUT request sending "Phone": "808-555-4321",
the new JSON representation of the customer: }

PUT /tms/dbdemos/rest/Customer(1221) HTTP/1.1


Host: localhost To create new customers, just send a POST request to
the /Customer address with the JSON
{
"$id": 1,
representation of the new customer.
"@xdata.type":XData.Default.Customer", And DELETE to delete the customer.
"Custno": 1221,
"Company": "Kauai Dive Shoppe",
"Addr1": "4-976 Sugarloaf Hwy",
"Addr2": "Suite 103",
"City": "Kapaa Kauai",
"State": "HI", About the Author
"Zip": "94766-1234", Wagner Landgraf
"Country": "US", Graduated in Electronic Engineering at UTFPR
"Phone": "808-555-1234",
university and has a Master of Science degree in
"Fax": "808-555-0278",
"Taxrate": 8.5, Industrial Information Technology, works with
"Contact": "Erica Norman", Delphi since its first version in 1995. After years
"Lastinvoicedate": "1995-02-02T01:05:03" running a software company focused on
Metrology, Quality and Firmware development,
joined TMS in 2001, being since then the
creator/manager of products like TMS Aurelius,
TMS Data Modeler, TMS Diagram, TMS Workflow
and TMS Scripter.

46 productivity software building blocks Nr 4 / 2014 BLAISE PASCAL MAGAZINE


TMS XData and TMS Aurelius (Continuation 7)
7. Using TXDataClient MyCustomer := XDataClient.Get<TCustomer>(1221);
Since the XData server we have built does use
standard protocols and concepts like HTTP, REST, and the client will make the proper HTTP request to
JSON, it can be easily access from any client and/or the server and create a TCustomer object based on
development tool that can send HTTP requests and server JSON response.
has reasonable JSON support (which is pretty much
almost every client and development tool these days). You can even use the TAureliusDataset to bind
The screenshots showing the use of Google Chrome the retrieved objects to a data-aware control or using
to retrieve the JSON results is a very good example of Live Bindings.
that. For example, let's create a new VCL application and
But, if your client application is built with add the following components to the main form:
Delphi, TMS XData provides very helpful classes A) TButton
and components to access the server objects so you B) TEdit
don't have to deal with HTTP requests, JSON C) TAureliusDataset
serialization/deserialization, etc. D) TDatasource (linked to the dataset)
There is a TXDataClient class available that E) TDBGrid (linked to the datasource)
provides methods like Get, Post, Put, Delete
and List which automatically does all that for us. The form would look something like this:
Once you have set the root URL of the server, you
can retrieve a TCustomer object like this:

Feature details TMS Aurelius


Several database servers supported (MS SQL Server, Firebird, MySQL, DB2, Interbase, Oracle,...)
Several database-access components supported (dbExpress, AnyDac, SQLDirect, ADO, IBX,...)
Multi-platform solution - Win32, Win64, Mac OS X, VCL, FireMonkey
Saving, updating and loading of entity objects in an object-oriented way
TAureliusDataSet for easy and fast interfacing to DB-aware controls in VCL
Multi-model design to allow different mapping models in a single application
Queries - Powerful query API using criteria expressions, projections,
grouping, conditions and even logical operators in a LINQ-like approach
Inheritance mapping and polymorphism - map a full class hierarchy into the database
Cross-database development - use a single Delphi code to target multiple databases in a transparent way
Choose from classes-to-database approach (creating the database structure from classes)
or database-to-classes approach (creating classes source code from database, using TMS Data Modeler )
Mapping directly in classes using custom attributes
Association mapping
Lifetime management of objects using object manager
Cached and identity-mapped objects
Automatic database structure generation
Nullable types support
Lazy loading for associations and blob fields
Allows logging of SQL commands
Allows mapping enumerated types to database values
Open architecture - easy extendable to use different component sets or database servers

productivity software building blocks


Nr 4 / 2014 BLAISE PASCAL MAGAZINE 47
TMS XData and TMS Aurelius (Continuation 8)
Our final source code for the main form unit will be something like this:

unit XDataMainForm;

interface

uses
System.Classes,
Vcl.Forms, Vcl.StdCtrls, Data.DB, Vcl.Controls, Vcl.Forms,Vcl.Grids, Vcl.DBGrids,
Aurelius.Bind.Dataset, Generics.Collections,
DBDemosEntities, XData.Client;

type
TForm2 = class(TForm)
AureliusDataset1: TAureliusDataset;
DataSource1: TDataSource;
DBGrid1: TDBGrid;
btList: TButton;
edQuery: TEdit;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure AureliusDataset1ObjectUpdate(Dataset: TDataSet; AObject: TObject);
procedure btListClick(Sender: TObject);
private
XDataClient: TXDataClient;
FCustomers: TList<TCustomer>;
procedure SetCustomers(const Value: TList<TCustomer>);
property Customers: TList<TCustomer> read FCustomers write SetCustomers;
public
end;

var
Form2: TForm2;

implementation

{$R *.dfm}

procedure TForm2.AureliusDataset1ObjectUpdate(Dataset: TDataSet; AObject: TObject);


begin
XDataClient.Put(AObject);
end;

procedure TForm2.FormCreate(Sender: TObject);


begin
XDataClient := TXDataClient.Create;
XDataClient.Uri := 'http://localhost/tms/dbdemos/rest';
end;

procedure TForm2.FormDestroy(Sender: TObject);


begin
AureliusDataset1.Close;
FCustomers.Free;
XDataClient.Free;
end;

procedure TForm2.SetCustomers(const Value: TList<TCustomer>);


begin
FCustomers.Free;
FCustomers := Value;
AureliusDataset1.Close;
AureliusDataset1.SetSourceList(FCustomers);
AureliusDataset1.Open;
end;

procedure TForm2.btListClick(Sender: TObject);


begin
Customers := XDataClient.List<TCustomer>(edQuery.Text);
end;

end.

48 Nr 4 / 2014 BLAISE PASCAL MAGAZINE


TMS XData and TMS Aurelius (Continuation 9 -End)
The client code is very simple: AObject will already have its properties updated by
A) In TForm.OnCreate, we create a new the dataset, so all we need to do is use the client to
TXDataClient object and set the URL of the send the JSON representation of changed
server to our server root address.
TCustomer object to the server using PUT method
B) In TButton.OnClick event, we call the
to get our customer updated!
List<TCustomer> method telling the client we
want a list of TCustomer objects. Optionally we
can pass a filter string to filter/order by the Conclusion
results. If we pass an empty string, all customers The purpose of this article was to show how to
will be retrieved. Then we set the list of create a HTTP Rest/JSON server using TMS XData
customers to the Customers property. and TMS Aurelius step-by-step, explaining the
C) When we set the Customers property, we close concepts while presenting the source code.
TAureliusDataset, set the new TCustomer list as Most of the source code was presented here and
the source list for the dataset, there are no relevant parts of server/client
and then open it again. application that was left unexplained.

If we run the client application and click the List It's also important to note that TMS XData allows
button, we will see something like the image below: you to create complex business logic by
implementing server-side methods that also
So the client retrieved the objects from server through receive/send Aurelius objects, but using some
HTTP and provided those TCustomer objects to the custom logic that your application might need.
dataset. TAureliusDataset in turn makes it easy The implementation of such methods was out of
to show/edit the objects in the grid (or any other data- the scope of this article.
aware control).
Readers interested in the source code of the
There is one last interesting thing in the client
server/client applications used in this article can
source code: TAureliusDataset allows also download the code from here:
editing objects. http://www.tmssoftware.com/business/
So if you edit fields in the grid and Post, resources/blaisepascal2014.zip
the underlying TCustomer object will be updated
accordingly. Since the changes are only being made
in memory, TAureliusDataset provides several
useful events like OnObjectInsert,
OnObjectUpdate, etc. So we made our client to be
able to also update the objects:

D) In TAureliusDataset.OnObjectUpdate event,
we simply call:
XDataClient.Put(AObject);

productivity software building blocks


Nr 4 / 2014 BLAISE PASCAL MAGAZINE 49
UpdateMode and FireDAC DataSets by Cary Jensen
starter expert

Delphi XE7
In this issue I am going
For more than a year now I have been focusing
on FireDAC issues in my Blaise Pascal Magazine
to focus specifically on UpdateOptions.UpdateMode.
articles, FireDAC being the newest data access This property plays a crucial role in reading from and
framework included in Delphi. writing to a relational database.
In this issue I will look at a property that is
involved when a FireDAC dataset is posting its UpdateOptions.UpdateMode
data to its underlying database: UpdateMode is a property of TFDUpdateOptions,
UpdateOptions.UpdateMode. which is the type associated with the UpdateOptions
property found in a number of classes in the FireDAC
Importantly, this property has a default value that
framework. These include FDManager, FDConnection,
makes its operation significantly different that most
FDQuery, FDMemTable, and so on.
other data access mechanisms found in Delphi.
The default value (upWhereKeyOnly ),
These classes are related in a hierarchical sense,
and its impact, is discussed at the end of this article.
in that the settings found in the UpdateOptions
property of the FDManager (there is never more than
Overview
one of these) are inherited by all FDConnections in the
In a typical application, a FireDAC dataset,
application. Similarly, any FireDAC dataset,
such as an FDQuery, is connected to a database by
such as an FDQuery or FDMemTable, will employ the
way of an FDConnection component.
settings found in the FDConnection to which they are
The connection component uses one of FireDAC's
connected.
drivers to connect to the database, where the
particular driver is design for the specific database.
While these settings are inherited, they can easily be
For example, to connect to InterBase, you typically
overridden by the inheriting class. For example,
use the FireDAC InterBase driver.
if you do not change any of the UpdateOptions of an
FDQuery, it will use the UpdateOptions settings of its
FireDAC includes drivers for a wide range of the
FDConnection. However, individual UpdateOptions
more popular databases, including MS SQL Server,
can be changed for the FDQuery, and those setting
Oracle, PostgreSQL, MySQL, DB2, and SQL
will take precedence over those defined for the
Anywhere, to name a few. In those cases where a
FDConnection.
specific driver for your database does not exist,
you can probably connect using one of the FireDAC
Let's return our focus back to the UpdateMode
bridging drivers, such as the ODBC driver.
property of UpdateOptions. This property affects how
This driver can be used with any database for which
a FireDAC dataset will generate the SQL that updates
there is an ODBC (open database connectivity)
the underlying database.
driver, and that pretty much covers every relational
database imaginable.
The UpdateMode property is of the type
TUpdateMode. The following is the declaration of the
It should be noted that there are applications where a
TUpdateMode type:
database is not involved. For example, if you are
using an FDMemTable you can load and save data TUpdateMode =
directly to a file or stream. The file, or stream, in this (upWhereAll, upWhereChanged, upWhereKeyOnly);
case is the data store, and no additional database may
be needed. When UpdateMode is set to upWhereAll, all non-
BLOB fields are included in the WHERE clause of
Likewise, other FireDAC datasets, such as FDQuery UPDATE and DELETE queries. This results in update
and FDTable, can load and save their data to a file or failures if any of the non-BLOB fields of the
stream. This data, however, is often saved in order to underlying record were modified since the time that
persist data offline, permitting that data to be loaded the table was opened, the query or stored procedure
again at a later time, keeping any data changes intact. was executed, or the FDMemTable was loaded.
However, this persistence to a file or stream is (INSERT queries are not affected, although the insert
usually temporary, in that the data is typically loaded operation will fail if the data being inserted violates a
originally from a database, and once a connection to database constraint, such as a primary key violation.)
the server can be re-established, the data is written
back to the underlying database server from which it
was obtained.
Or call: +31 (0)23 542 22 27

50 COMPONENTS
DEVELOPERS 4 Nr 4 / 2014 BLAISE PASCAL MAGAZINE
UpdateMode and FireDAC DataSets (Continuation 1)
This approach is known as optimistic locking, Here is how this can happen. If two or more users
and when two or more users are trying to apply read the same record (by way of a query,
changes to a specific record at about the same time, stored procedure call, or by opening an FDTable),
only the first to apply changes will succeed. All and two or more post a change to that record,
others will fail. the last user to post their changes will replace those
changes posted before them. The problem with this is
When UpdateMode is set to upWhereChanged, only that the users who posted before the last user will
the primary field keys and the fields that have been have no idea that their changes have been
modified are included in the WHERE clause overwritten.
predicates of UPDATE queries. (Again, INSERTs are
not affected. DELETE queries continue to use an By comparison, most databases use either pessimistic
exact match criteria since there are no changed fields locking (the first user to start editing a record
in a deleted record.) As long as none of the primary prevents any other user from editing that same
key fields of an updated record are affected, record until the first user's changes have been posted
and all non-primary key fields that have been or the first user performs some task that releases the
modified have also not been updated in the lock, such as canceling their changes), or optimistic
underlying table since the time the data was loaded locking (once the first user posts a change to a record,
into the dataset, these queries should succeed. subsequent attempts to post to that same record will
fail, since the original record no longer can be found,
Using upWhereChanged permits two or more users based on the WHERE clause predicates).
to apply their changes to the underlying database so In these scenarios, the first user to post their changes
long as none of them have made changes to common to a particular record succeeds, and other users must
fields. For example, if one user changed a field called first re-read the posted record, after which they can
Address, and another changed a field called decide whether or not to update the current contents.
PhoneNumber, and neither of these fields are part of
the primary key, both users will successfully apply FireDAC defaults to an UpdateMode of
their changes. This type of update permits merges. upWhereKeyOnly, since the queries required to
update the database tend to execute faster using this
The final UpdateMode value is upWhereKeyOnly. mode than the alternative modes. It is up to you,
With UpdateMode set to upWhereKeyOnly, however, to decide whether or not the performance
the WHERE clause predicates of UPDATE queries improvement is more important than the possible
only includes the values of the primary key fields. unintentional loss of data.
(INSERT and DELETE queries continue to act as they
do with upWhereAll.) Using this mode, so long as the The difference between upWhereKeyOnly and
key fields of the underlying record have not been upWhereAll is shown using a simple project, whose
changed, the updates are applied, replacing any main form is shown in Figure 1.
updates that other users may have applied.

Assuming that key fields are not touched (this is a


pretty safe assumption in most database
architectures), the use of upWhereKeyOnly permits
everyone to succeed in posting their changes.
As a result, when two or more users are editing a
common record, the last user to post is the user
whose data appears in the underlying database.

The default value of UpdateOptions.UpdateMode is


upWhereKeyOnly, and this is a really big deal.
It means that if you use FireDAC datasets without
changing this default value, there is a good chance
that some users may report that their changes have
disappeared.

Nr 4 / 2014 BLAISE PASCAL MAGAZINE


COMPONENTS
DEVELOPERS 4 51
UpdateMode and FireDAC DataSets (Continuation 2)

Figure 1. A simple FireDAC application


Everything you need to know about the configuration of the components on this form
can be seen in the following code, which is the only code associated with this project:
procedure TForm1.FormCreate(Sender: TObject);
begin
FDConnection1.Params.Clear;
//Change the following location to match your Delphi version
FDConnection1.Params.Add('Database=localhost:C:\Users\Public\' +
'Documents\Embarcadero\Studio\15.0\' +
'Samples\Data\dbdemos.gdb');
FDConnection1.Params.Add('User_Name=sysdba');
FDConnection1.Params.Add('Password=masterkey');
FDConnection1.Params.Add('DriverID=IB');
FDConnection1.LoginPrompt := False;
FDQuery1.SQL.Text := 'SELECT * FROM Customer';
end;

procedure TForm1.OpenCloseBtnClick(Sender: TObject);


begin
if FDConnection1.Connected then
FDConnection1.Close
else
FDquery1.Open();
end;

procedure TForm1.FDConnection1AfterConnect(Sender: TObject);


begin
OpenCloseBtn.Caption := 'Close';
end;

procedure TForm1.FDConnection1AfterDisconnect(Sender: TObject);


begin
OpenCloseBtn.Caption := 'Open';
end;

52 COMPONENTS
DEVELOPERS 4 Nr 4 / 2014 BLAISE PASCAL MAGAZINE
UpdateMode and FireDAC DataSets (Continuation 3 - End)
The problem can be seen if you perform the Personally, I greatly prefer how the FireDAC applies
following steps: its updates to data when UpdateMode is set to
upWhereAll as opposed to upWhereKeyOnly.
1. Run two (or more) versions of this compiled This behavior can be changed by adding this single
project at the same time line anywhere within the OnCreate event handler
2. In each open application, click the Open button (the FormCreate method).
to execute the SELECT query
3. In one application, make a change to the first FDQuery1.UpdateOptions.UpdateMode := upWhereAll;
record displayed in the DBGrid, after which you
should post that change by clicking the Post Now, after adding the preceding line of code to the
button in the DBNavigator (the button with the OnCreate event handler, if you perform the same
checkmark icon) preceding four steps, the first application will
4. In a second application, make a different change successfully post its change and the second
to the same first record in the DBGrid, after application will generate an exception similar to the
which you should again post that change. one shown in Figure 2.

Following these steps, the last application from


which you post the change post save its data, and all
others will have their data lost.

Figure 2. The update has failed, since the record being posted has been modified by another user

About the Author


Cary Jensen is Chief Technology Officer of
Jensen Data Systems. Since 1988 he has built
and deployed database applications in a wide
range of industries, and is available for
development, consulting, and training. Cary is an
Embarcadero MVP, a best selling author of more
than 20 books on software development, founder
of Delphi Developer Days
(www.DelphiDevelperDays.com), and holds a
Ph.D. in Engineering Psychology, specializing in
human-computer interaction. Visit
http://www.JensenDataSystems.com to learn
more about Cary's services.

Nr 4 / 2014 BLAISE PASCAL MAGAZINE


COMPONENTS
DEVELOPERS 4 53
AMQP (Advanced Message Queuing Protocol) AMQP
Advanced Message Queuing Protocol
by Fikret Hasovick When a successful natural monopoly emerges,
AMQP is an attempt by some very large thanks to luck or regulation or market forces,
businesses, and some smaller suppliers, to it eliminates a lot of waste, also called "friction costs",
change the rules in the business messaging or perhaps "excess profits".
market. Natural monopolies can create huge value.
There are two dominant suppliers in this Vendors (those selling products and services) will try to
market : IBM and Tibco. It is a market which has capture that value.
no open standards or open-source competitors,
There is often a fundamental conflict of interests
a lack which is bad for both clients and vendors.
AMQP was devised by John O'Hara in 2003, when vendors get engaged in standards setting,
working in London at a UK branch of JPMorgan but almost all conventional standards consortia are
Chase & Co. driven by vendors. Here patents jump into the game.
From the outset AMQP was conceived as an So AMQP was born to turn messaging into a
open, co-operative effort. Initial development natural monopoly. It appears to be succeeding.
was done by JPMorgan Chase. The working People are taking AMQP seriously as a solution and
group grew to 23 companies including Bank of
there is general agreement that AMQP's mission
America, Barclays, Cisco Systems, Credit Suisse,
Deutsche Brse Systems, Goldman Sachs, HCL statement makes sense. Already some very large
Technologies Ltd, Progress Software, IIT projects have emerged where open source AMQP-
Software, INETCO Systems Limited, Informatica based solutions are winning over traditional
Corporation (including 29 West), JPMorgan messaging.
Chase, Microsoft Corporation, my-Channels,
Novell, Red Hat, Software AG, Solace Systems, The evolution of AMQP
StormMQ, Tervela Inc., TWIST Process AMQP/0.8, the first published specification, was
Innovations ltd, VMware (which acquired Rabbit
simple.
Technologies) and WSO2.
It is so easy to be complex: it is simplicity that is hard.
A newly emerging standard There is no magic recipe for simplicity, nor is it
We all know how standards work. something you can buy.
You might think it's all about AMQP is essentially the Many of the original AMQP
making revolutionary new Internet Protocol for concepts were over-engineered,
concepts available to the public. Business Messaging. solving problems we had theories
In fact, standards are more about but no practical experience
about stopping innovation than opening the door to with, yet. About 30-40% of AMQP/0.8 was garbage,
it. Or, to be more precise, by freezing innovation at but it was impossible to know in advance what those
one level, it permits more innovation at higher levels. parts were. The 1.0 protocol should have been 90%
Standardization always works from the bottom the size of 0.8, some parts removed, some new bits
up, and from more basic and broadly-used added, and with fixes.
technologies to more sophisticated ones. Instead the AMQP/0.10 specification is many times
The standards 'stack' becomes compressed over time larger than AMQP/0.8 and little of the real garbage
rather like layers of sedimentary rock deposits. has been removed.
Unused layers fall away, leaving fewer and fewer So why has AMQP become more complex over
basic standards underpinning the whole world of time? Writing protocol specifications is very hard
computing. work and above all it needs clear rules, an accurate
AMQP is quite unusual because it starts low in and focused vision, and a strong will.
the stack, building on protocols like TCP rather than The AMQP 0.9.1 Model has the following view of
HTTP. It is also unusually ambitious in going from the world: messages are published to exchanges,
very low level (data on the wire) to very high level which are often compared to post offices or
(application semantics), in a single leap. mailboxes. Exchanges then distribute message copies
The economic basis for making standards is the to queues using rules called bindings. Then AMQP
concept that we call a natural monopoly. In the brokers either deliver messages to consumers
context of computerized networking this means that subscribed to queues, or consumers fetch/pull
a successful standard will attract and hold all users. messages from queues on demand.
Electrical power outlet design, phones, rail
transport, the Internet Protocol, are just a few AMQP version 1.0
examples of standards affecting natural monopolies. AMQP 1.0 was released by the AMQP working
We all want our mobile phone charger to plug group on 30 October 2011, at a conference in
into any power socket. We all want our phone to New York. At the event Microsoft, Red Hat,
VMware, Apache, INETCO and IIT Software
reach anyone and to be reachable by anyone.
demonstrated software running the protocol
Similarly with our computers and operating systems. in an interoperability demonstration.

54 COMPONENTS
DEVELOPERS 4 Nr 4 / 2014 BLAISE PASCAL MAGAZINE
Advanced Message Queuing Protocol (Continuation 1)
CONSUMES
PUBLISHER CONSUMER

EXCHANGE
PUBLISH EXCHANGE ROUTES QUEUE

Figure 1: AMQP version 0.91 Hello world example routing

AMQP version 0.91 provides the pieces necessary to requires a trusted third party, and optionally may use
enable messaging clients and servers to interoperate public-key cryptography during certain phases of
seamlessly, regardless of their technology. authentication. Kerberos uses UDP port 88 by default.
It comprises an efficient wire protocol that How to multiplex a TCP/IP connection in order
separates the network transport from broker that multiple conversations may happen over
architectures and management. It also supports one TCP/IP connection, which greatly simplifies
various broker architectures that may be use to firewall management.
receive, queue, route, and deliver messages or be How to address a source of messages with the
used peer-to-peer. network peer, and to specify which messages are
There are three major pieces specified in the of interest
scope of AMQP 09.1. These define the networking The lifecycle of a message through fetching,
protocol, a representation for message envelope data processing, and acknowledgement. AMQP
and the basic semantics of broker services. makes it very clear when responsibility for a
message is transferred from one peer to another
For example, the AMQP Network protocol defines: thereby enhancing reliability
A peer to peer protocol; though normally in How to enhance performance, if desired, by pre-
AMQP one peer is playing the role of a client fetching messages across the network ready for
application and the other peer is playing the role the client to process without delay
of a trusted message routing and delivery A way of processing batches of messages within
service, or broker a transaction
How to connect to services, including a method A mechanism to allow a complete message
for failing over connections to alternative services transfer from login to logout in one network
A mechanism to enable peers to discover one packet for lightweight applications
another's capabilities Very capable flow control, which enables
Comprehensive security mechanisms, including consumers of messages to slow producers to a
SSL and Kerberos for seamless end-to-end manageable speed, and which enable different
confidentiality. workloads to proceed in parallel at different rates
(SSL Secure Sockets Layer) over one connection
Transport Layer Security (TLS) and its predecessor, Mechanisms for resuming message transfers
Secure Sockets Layer (SSL), are cryptographic when connections are lost and re-established;
protocols designed to provide communication security for example in the event of service failover or
over the Internet. - WIKIPEDIA intermittent connectivity
Kerberos is a computer network authentication
protocol which works on the basis of 'tickets' to allow This low-level network protocol is comprehensive
nodes communicating over a non-secure network to and capable. That said, it is possible for networking
prove their identity to one another in a secure manner. specialists to use this protocol for other purposes, but
Its designers aimed it primarily at a clientserver it is anticipated that by far the greatest use of the
model and it provides mutual authentication protocol will be to connect messaging clients to
both the user and the server verify each other's
messaging brokers; the brokers hosting queues and
identity. Kerberos protocol messages are protected
topics and taking care of safe storage, routing and
against eavesdropping and replay attacks.
delivery.
Kerberos builds on symmetric key cryptography and

Nr 4 / 2014 BLAISE PASCAL MAGAZINE


COMPONENTS
DEVELOPERS 4 55
Advanced Message Queuing Protocol (Continuation 2)
Messaging brokers receive messages from publishers
MESSAGING TRANSACTIONS (applications that publish messages, also known as
producers) and route them to consumers (applications

ECODING TYPES
LINK that process messages). Since AMQP is a network
protocol, the publishers, consumers and the broker
SESSION
can all reside on different machines.
AMQP is a binary, application layer protocol,
CHANNEL
designed to efficiently support a wide variety of
messaging applications and communication
patterns. It provides flow-controlled, message-
CONNECTION
oriented communication with guaranteed message-
delivery. The goal of AMQP is to enable applications
FRAMING
to send messages via the broker services; these lower
level concepts are necessary but not the goal in
themselves. When you send a message via a courier,
VERSION NEGOCIATION
you don't drive the delivery truck or motorcycle
yourself!
SECURITY
AMQP as a binary protocol
Binary protocol means that methods like Queue.Create
SECURITY NEGCIATION
are defined as binary frames in which every field sits
Figure 2
in a well-defined place, encoded carefully to make the
best use of space. Binary encoding of numbers is much
AMQP provides portability between systems.
more compact than string encoding. "123" needs one
It therefore needs a way to represent business data
octet (8) in binary and three(3x8=24) as a string.
that may be required to route and deliver the
Because AMQP is a binary protocol, it is very fast
message in a portable way accessible from many
to parse. Strings are safe, since there is no text parsing
programming languages. The AMQP 0.91 Type to do. AMQP's binary encoding means AMQP software
System and message encoding facilities provide a is not at risk of buffer overflow attacks. And it's easy to
portable encoding for messages to meet this need. generate the encoding/decoding routines, since AMQP
Normally, this encoding is only used to add is defined as easy-to-parse XML.
routing properties to the envelope of the message; Overall, AMQP's binary encoding is a good
the contents inside the envelope are transported thing.That last statement has been proven to be
untouched. Applications will likely use XML, JSON wrong! Evidence shows that AMQP's binary
or similar encodings in their message content. encoding is a fundamental mistake.
Optionally, an application could choose to use Let's look at the advantages, and costs of this approach
AMQP encoding for message content too, but this is .
entirely optional. Advantages of binary encoding:
It is more compact.
AMQP as an enterprise It is faster to parse than a text format.
networking technology It is safer then to parse strings.
AMQP has been positioned as an "Enterprise The codecs can be fully generated.
Technology". Yet as far as AMQP is concerned, Costs of binary encoding:
Enterprise Technology must be 100% reliable, which You need codecs in the first place.
means ensuring that transactions survive a failover It creates endless incompatible versions of AMQP.
It is more complex to understand and use than
from a primary to a backup server. Consequently the string encoding.
protocol must have mechanisms for switching There is a lot of emphasis on data types.
sessions over from one server to another, which in Even the simplest client API is
turn means the atomicity of every operation from significantly complex.
queue creation to message transfer needs to be
redefined. To redefine what a session is, we need to AMQP is designed for speed, and it's Enterprise
treat everything as a message, or perhaps Technology, so complex APIs are not a big problem.
alternatively, we need dozens of new data types,
including multiple variants of that insufficiently Messaging models
Message-delivery can be:
complex concept called a "bit". Now we have
at-most-once (where each message is delivered
something suitable for the Enterprise!
once or never),
AMQP (Advanced Message Queuing Protocol) is a at-least-once (where each message is certain to
networking protocol that enables conforming client be delivered, but may arrive many times over)
applications to communicate with conforming exactly-once (where the message will always
messaging middleware brokers. certainly arrive and do so only once),

56 COMPONENTS
DEVELOPERS 4 Nr 4 / 2014 BLAISE PASCAL MAGAZINE
Advanced Message Queuing Protocol (Continuation 3)
AMQP also supports authentication and/or A binding is a relationship between an exchange
encryption based on SASL and/or TLS. and a queue, telling the exchange which queues
It assumes an underlying reliable transport layer expect which messages.
protocol such as Transmission Control Bindings are independent, except that a queue
Protocol (TCP). will not get the same message more than once.
But I have a question! Just when is a message
delivered? Is it when the exchange has routed it, The AMQP specification is defined in several layers:
when it's been put into a queue, or received by an 1 a type system
application, or when it's been processed and 2 a symmetric, asynchronous protocol for the
acknowledged? transfer of messages from one process to another
What if the message is routed across multiple 3 a standard, extensible message format
servers? What if we want to use a multicast protocol? 4 a set of standardised but extensible messaging
Reliable messaging cannot be reduced to a single capabilities.AMQP and business communication
model, there must always be several, and each has
cost-benefit trade-offs, and each has a specific view of
AMQP is essentially the Iternet Protocol for Business
what "reliable" means:
Messaging. It is an open standard for passing
The request-response model, used to build
service-oriented architectures. A caller sends a business messages between applications or
request, which is routed to a service, which does organizations. It connects systems, feeds business
some work and returns a response. The simplest processes with the information they need, and
proven reliability model is a retry mechanism reliably forwards the instructions that achieve their
business goals.
combined with the ability at the service side to detect
and properly handle duplicate requests. The All AMQP clients interoperate with all AMQP
transient publish-subscribe model, used to servers; diverse programming languages can
distribute data to multiple clients. In this model, if
communicate easily, and legacy
data is lost, clients simply wait for fresh data to message brokers can be retrofitted toremove
arrive. One example would be video streaming. proprietary protocols from your networks. AMQP
The reliable publish-subscribe model, used enables messaging as a cloud service, and has
when the cost of lost data is too high. In this
model, clients acknowledge data using a low- advanced publish-and-subscribe and transactional
volume volume reply back to the sender. If the messaging functionality. Because one of the main
sender needs to, it resends data. This is AMQP goals is interoperability, it is a good idea for
similar to TCP. developers to understand protocol operations and
AMQP message flow not limit themselves to terminology of a particular
In AMQP, the primary semantic is elegant, powerful client library. This way communicating with
and natural: it is the exchange-binding-queue wiring developers using different libraries becomes
model. This model gives application architects full significantly easier.
AMQP enables applications to send and receive
control over how messages flow through the network.
messages. In this regard it is like instant messaging
A queue holds messages, it is a FIFO buffer.
or email. Where AMQP differs enormously from
There are two kinds of queue:
IM and email is that it allows one to specify what
private, for a single consuming application,
messages will be received and where from, and how
and shared, for multiple consuming
applications. trade-offs are made with respect to security,
An exchange routes messages. reliability and performance.
It is an algorithm with no storage.

AMQP is essentially the


Internet Protocol for
Business Messaging.

VENDOR A VENDOR C
NET APPLICATION JAVA APPLICATION

AMQP 1.0 AMQP 1.0


WIRE PROTOCOL WIRE PROTOCOL

VENDOR B
Figure 3 AMQP 1.0 BROKER

Nr 4 / 2014 BLAISE PASCAL MAGAZINE


COMPONENTS
DEVELOPERS 4 57
Advanced Message Queuing Protocol (Continuation 4)
AMQP connects across:
Organizations WEB SERVICES
applications in different organizations
Technologies WSDL
applications on different platforms
Time
systems don't need to be available SOAP
simultaneously
Space
XML SCHEMA
reliably operate at a distance,
or over poor networks
XML
AMQP versus other middleware
alternatives
How does AMQP compare with the many other AMQP
middleware solutions? AMQP differs from other
middleware standards because it is: TCIP / IP
Figure 4
INTEROPERABLE.
ALL AMQP clients interoperate with ALL AMQP Proprietary middleware has been a source of lock-in,
servers. Diverse programming languages can preventing competition in middleware for both
communicate easily. Legacy message brokers can be quality and cost and often forcing the
retrofitted to remove proprietary protocols from your implementation of fragile, inflexible legacy protocols.
network. Messaging can be enabled as a cloud AMQP lets diverse platforms and applications to
service. AMQP provides a straightforward solution communicate easily and securely.
for business messaging and middleware integration, Legacy messaging solutions can be easily
designed to satisfy actual business needs. retrofitted with AMQP to remove proprietary
RELIABLE. protocols from your network.
AMQP is capable of eliminating the communication Java Message Service (JMS), is often compared to
gaps and slowdowns between different platforms, AMQP. However, JMS is an API specification (part
critical systems and application components both of the Java EE specification) that defines how
within your enterprise and beyond when you message producers and consumers are
interface with external systems and organizations. implemented. JMS does not guarantee
UNIFIED. interoperability between implementations, and the
AMQP provides a core set of messaging patterns via JMS-compliant messaging system in use may need
a single manageable protocol. to be deployed on both client and server.
COMPLETE.
JMS provides an API for application protocols, and is On the other hand, AMQP is a wire-level
reliant on Java. AMQP provides a wire level protocol specification. In theory AMQP provides
transport for applications using that API. AMQP is interoperability as different AMQP-compliant
broadly applicable and can be leveraged by any software can be deployed on the client and server
language, and identifies both store-and-forward and sides.
publish-and-subscribe semantics in one specification. Note that, like HTTP and XMPP, AMQP does not
OPEN. have a standard API.
AMQP is vendor and platform agnostic, and has been
created by users and technology providers working AMQP 1.0 Versus 0.9.1
The AMQP group decided to go down a very
in collaboration.
different direction than what had been done
SAFE. up to 0.9.1 before ratification and because of
AMQP offers a secure solution to the problem of that AMQP 1.0 is entirely different.
transporting value-bearing messages across and Some message-oriented middleware had already
between organizations, technology platforms and a been introduced into the market that was built
virtual cloud computing environment. conforming to 0.9.1 and previous versions of the
AMQP completes the picture of an open SOA stack standard. A few examples of this are RabbitMQ,
by utilizing a TCP/IP infrastructure for transport. Apache Qpid, StormMQ and RedHat Enterprise
The protocol is a trusted intermediary for MRG (based on Apache Qpid).
asynchronous message delivery with specific This change has created a pretty big divide in the
qualities of service. XML provides uniform data community from my observations. Some people
encoding, while the XML schema provides metadata involved in earlier versions consider it a big step
specification for proper representation. Expected backwards while others consider it a simplification to
Message Exchange Patterns are provided by SOAP, build on that introduces more flexibility (more on
while Web Services standards provide for business that later).
contract representation.
58 COMPONENTS
DEVELOPERS 4 Nr 4 / 2014 BLAISE PASCAL MAGAZINE
Advanced Message Queuing Protocol (Continuation 5 - End)

MY ENTERPRISE

AMQP AMQP
AWARE SERVICES AWARE CLIENTS
C/C++ JAVA JMS MS DEVICES & WORKSPACES
WCF CLOUD
APPLICATION

BUSINESS PARTNERS
& SERVICES
ORDERS@SUPPLIER.COM TREASURY@FUNDMANGER.COM
Figure 5
AMQP 1.0 is a much more narrow standard In AMQP 1.0 the broker management is shifted from
than the broad standards in the previous a protocol-level command to a message you
versions. It only defines the network wire-level transport over a standard message. This means
protocol for the exchange of messages between two brokers can define their own management
endpoints. The standard supports exchanging commands that any AMQP client library can send.
messages in peer-to-peer or by brokered topologies. Broker capabilities do not have to be part of the
The same protocol can be used to communicate standard that clients must implement to be
client-to-client, client-to-broker or broker-to-broker compatible.
with all of the delivery guarantees available. Since AMQP 1.0 defines how to communicate to
AMQP 0.9.1 heavily influenced broker internals. an endpoint and has the concept of an address, a
AMQP 1.0 does not define the internals of the broker broker could define an XML or JSON message to
implementation and can be used with any broker. send to this address for broker management
This means that existing 0.9.1 implementations (like commands such as creating exchanges, queues and
the ones mentioned above) can add the AMQP 1.0 routing behaviour.
network wire-level protocol support. An example is In theory, if FooMQ was a broker that was
an experimental plugin for RabbitMQ that provides AMQP 1.0 compliant you could send a message to
AMQP 1.0 endpoint support even though RabbitMQ amqp://hostname/queues/bar-queue that was a
is an AMQP 0.9.1 based broker. JSON message with the command to create a new
The AMQP 1.0 network wire-level protocol durable queue named bar-queue.
is not compatible with the AMQP 0.9.1
network wire-level protocol.
components4developers have brought
Important part lost AMQP to the kbmMW framework.
In AMQP 0.9.1 the protocol itself has support for Which means a break-through for Pascal
creating and managing exchanges, queues and related Middle ware.
bindings. This means the broker behaviours are fixed
and limited by what the standard defines.
Nr 4 / 2014 BLAISE PASCAL MAGAZINE
COMPONENTS
DEVELOPERS 4 59
AMQP is essentially the
Internet Protocol for
Business Messaging.

VENDOR A VENDOR C
NET APPLICATION JAVA APPLICATION

AMQP 1.0 AMQP 1.0


WIRE PROTOCOL WIRE PROTOCOL

VENDOR B
AMQP 1.0 BROKER

AMQP
Advanced Message Queuing Protocol

KBMMW V. 4.50 AMQP support


( Advanced Message Queuing Protocol)
KBM-MEMTABLE V. 7.64 WITH XE6 / XE 7
and LAZARUS SUPPORT JUST RELEASED! MP EL
CO DEV
TS
EN RS
ON OPE
4
.
kbmMW is the premier high performance, high
functionality multi tier product for serious
system development.
Supports Delphi/C++Builder/RAD Studio 2009
- Native high performance 100% developer to XE7 (32 bit, 64 bit and OSX where applicable).
defined application server with support for kbmMW for XE5 to XE7 includes full support for
Android and IOS (client and server).!
loadbalancing and failover
- Native high performance JSON and XML kbmMemTable is the fastest and most feature rich
(DOM and SAX) for easy integration with in memory table for Embarcadero products.
external systems
- Native support for RTTI assisted object - Easily supports large datasets
marshalling to and from XML/JSON, now also with millions of records
with new fullfeatured XML schema - Easy data streaming support
(XSD) import - Optional to use native SQL engine
- Supports nested transactions and undo
- High speed, unified database access
- Native and fast build in M/D,
(35+ supported database APIs) with
aggregation /grouping,
connection pooling, metadata and range selection features
data caching on all tiers - Advanced indexing features for extreme
- Multi head access to the application server, performance
via AJAX, native binary, Publish/Subscribe, Warning!
SOAP, XML, RTMP from web browsers, kbmMemTable and kbmMW
embedded devices, linked application
servers, PCs, mobile devices, Java systems
are highly addictive!
Once used, and you are hooked for life!
and many more clients
- Full FastCGI hosting support.
Host PHP/Ruby/Perl/Python applications in
kbmMW!
COMPONENTS
DEVELOPERS 4
EESB, SOA,MoM, EAI TOOLS FOR INTELLIGENT SOLUTIONS. kbmMW IS THE PREMIERE N-TIER PRODUCT FOR DELPHI / C++BUILDER BDS
DEVELOPMENT FRAMEWORK FOR WIN 32 / 64, .NET AND LINUX WITH CLIENTS RESIDING ON WIN32 / 64, .NET, LINUX, UNIX MAINFRAMES,
MINIS, EMBEDDED DEVICES, SMART PHONES AND TABLETS.