Blaise Pascal Magazine 39
Blaise Pascal Magazine 39
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
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,
[email protected] -Editor peter @ blaisepascal.eu michael @ freepascal.org
Alexander @ blaisepascal.ru
Please note:The spacings in the emails was added on purpose. Please delete for use
editor @ blaisepascal.eu
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 [email protected]
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 [email protected]
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
[email protected]
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.
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+
Delphi AVR
development board
with SDK
COMPONENTS
DEVELOPERS 4 Specialist help and consultancy
for kbmMW
if result
then result := EmptyBlock(el,x1,y1,x2,y2);
end; //if result
end;
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.
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;
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.
procedure ;
var
begin
for i := 1 to 9 do
begin
end;
end;
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
post.addData("start", "true");
post.send();
size(100, 100);
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!
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.
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
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
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.
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.
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
Or you can search one of the mailing list archives such as:
http://lists.lazarus.freepascal.org/
pipermail/lazarus
38 COMPONENTS
DEVELOPERS 4 Nr 4 / 2014 BLAISE PASCAL MAGAZINE
RASPBERRY PI
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)));
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)
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:
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:
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: }
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}
end.
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);
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.
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.
Figure 2. The update has failed, since the record being posted has been modified by another user
54 COMPONENTS
DEVELOPERS 4 Nr 4 / 2014 BLAISE PASCAL MAGAZINE
Advanced Message Queuing Protocol (Continuation 1)
CONSUMES
PUBLISHER CONSUMER
EXCHANGE
PUBLISH EXCHANGE ROUTES QUEUE
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
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.
VENDOR A VENDOR C
NET APPLICATION JAVA APPLICATION
VENDOR B
Figure 3 AMQP 1.0 BROKER
MY ENTERPRISE
AMQP AMQP
AWARE SERVICES AWARE CLIENTS
C/C++ JAVA JMS MS DEVICES & WORKSPACES
WCF CLOUD
APPLICATION
BUSINESS PARTNERS
& SERVICES
[email protected] [email protected]
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
VENDOR B
AMQP 1.0 BROKER
AMQP
Advanced Message Queuing Protocol